code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
from __future__ import annotations from collections.abc import Callable SCREAMING_SNAKE_CASE__ : int = list[list[float | int]] def __magic_name__ ( __lowerCAmelCase : Matrix , __lowerCAmelCase : Matrix ) -> Matrix: __lowerCamelCase = len(__lowerCAmelCase ) __lowerCamelCase = [[0 for _ in range(size + 1 )] for _ in range(__lowerCAmelCase )] __lowerCamelCase = 42 __lowerCamelCase = 42 __lowerCamelCase = 42 __lowerCamelCase = 42 __lowerCamelCase = 42 __lowerCamelCase = 42 for row in range(__lowerCAmelCase ): for col in range(__lowerCAmelCase ): __lowerCamelCase = matrix[row][col] __lowerCamelCase = vector[row][0] __lowerCamelCase = 0 __lowerCamelCase = 0 while row < size and col < size: # pivoting __lowerCamelCase = max((abs(augmented[rowa][col] ), rowa) for rowa in range(__lowerCAmelCase , __lowerCAmelCase ) )[ 1 ] if augmented[pivot_row][col] == 0: col += 1 continue else: __lowerCamelCase , __lowerCamelCase = augmented[pivot_row], augmented[row] for rowa in range(row + 1 , __lowerCAmelCase ): __lowerCamelCase = augmented[rowa][col] / augmented[row][col] __lowerCamelCase = 0 for cola in range(col + 1 , size + 1 ): augmented[rowa][cola] -= augmented[row][cola] * ratio row += 1 col += 1 # back substitution for col in range(1 , __lowerCAmelCase ): for row in range(__lowerCAmelCase ): __lowerCamelCase = augmented[row][col] / augmented[col][col] for cola in range(__lowerCAmelCase , size + 1 ): augmented[row][cola] -= augmented[col][cola] * ratio # round to get rid of numbers like 2.000000000000004 return [ [round(augmented[row][size] / augmented[row][row] , 10 )] for row in range(__lowerCAmelCase ) ] def __magic_name__ ( __lowerCAmelCase : list[int] ) -> Callable[[int], int]: __lowerCamelCase = len(__lowerCAmelCase ) __lowerCamelCase = [[0 for _ in range(__lowerCAmelCase )] for _ in range(__lowerCAmelCase )] __lowerCamelCase = [[0] for _ in range(__lowerCAmelCase )] __lowerCamelCase = 42 __lowerCamelCase = 42 __lowerCamelCase = 42 __lowerCamelCase = 42 for x_val, y_val in enumerate(__lowerCAmelCase ): for col in range(__lowerCAmelCase ): __lowerCamelCase = (x_val + 1) ** (size - col - 1) __lowerCamelCase = y_val __lowerCamelCase = solve(__lowerCAmelCase , __lowerCAmelCase ) def interpolated_func(__lowerCAmelCase : int ) -> int: return sum( round(coeffs[x_val][0] ) * (var ** (size - x_val - 1)) for x_val in range(__lowerCAmelCase ) ) return interpolated_func def __magic_name__ ( __lowerCAmelCase : int ) -> int: return ( 1 - variable + variable**2 - variable**3 + variable**4 - variable**5 + variable**6 - variable**7 + variable**8 - variable**9 + variable**10 ) def __magic_name__ ( __lowerCAmelCase : Callable[[int], int] = question_function , __lowerCAmelCase : int = 10 ) -> int: __lowerCamelCase = [func(__lowerCAmelCase ) for x_val in range(1 , order + 1 )] __lowerCamelCase = [ interpolate(data_points[:max_coeff] ) for max_coeff in range(1 , order + 1 ) ] __lowerCamelCase = 0 __lowerCamelCase = 42 __lowerCamelCase = 42 for poly in polynomials: __lowerCamelCase = 1 while func(__lowerCAmelCase ) == poly(__lowerCAmelCase ): x_val += 1 ret += poly(__lowerCAmelCase ) return ret if __name__ == "__main__": print(F'{solution() = }')
369
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_squeezebert import SqueezeBertTokenizer SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Dict = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "vocab_file": { "squeezebert/squeezebert-uncased": ( "https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt" ), "squeezebert/squeezebert-mnli": "https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt", "squeezebert/squeezebert-mnli-headless": ( "https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt" ), }, "tokenizer_file": { "squeezebert/squeezebert-uncased": ( "https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/tokenizer.json" ), "squeezebert/squeezebert-mnli": ( "https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/tokenizer.json" ), "squeezebert/squeezebert-mnli-headless": ( "https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/tokenizer.json" ), }, } SCREAMING_SNAKE_CASE__ : List[Any] = { "squeezebert/squeezebert-uncased": 512, "squeezebert/squeezebert-mnli": 512, "squeezebert/squeezebert-mnli-headless": 512, } SCREAMING_SNAKE_CASE__ : Dict = { "squeezebert/squeezebert-uncased": {"do_lower_case": True}, "squeezebert/squeezebert-mnli": {"do_lower_case": True}, "squeezebert/squeezebert-mnli-headless": {"do_lower_case": True}, } class lowerCAmelCase__ ( __lowercase ): a__ : Optional[int] = VOCAB_FILES_NAMES a__ : Any = PRETRAINED_VOCAB_FILES_MAP a__ : Union[str, Any] = PRETRAINED_INIT_CONFIGURATION a__ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ : Optional[Any] = SqueezeBertTokenizer def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[UNK]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[PAD]" , SCREAMING_SNAKE_CASE__ : Tuple="[CLS]" , SCREAMING_SNAKE_CASE__ : str="[MASK]" , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : int=None , **SCREAMING_SNAKE_CASE__ : Dict , ) -> Optional[Any]: super().__init__( SCREAMING_SNAKE_CASE__ , tokenizer_file=SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , tokenize_chinese_chars=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = 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 ): __lowerCamelCase = getattr(SCREAMING_SNAKE_CASE__ , normalizer_state.pop('''type''' ) ) __lowerCamelCase = do_lower_case __lowerCamelCase = strip_accents __lowerCamelCase = tokenize_chinese_chars __lowerCamelCase = normalizer_class(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = do_lower_case def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[str]=None ) -> str: __lowerCamelCase = [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 : Tuple , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: __lowerCamelCase = [self.sep_token_id] __lowerCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __A ( self : int , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: __lowerCamelCase = self._tokenizer.model.save(SCREAMING_SNAKE_CASE__ , name=SCREAMING_SNAKE_CASE__ ) return tuple(SCREAMING_SNAKE_CASE__ )
339
0
import cmath import math def __magic_name__ ( __lowerCAmelCase : float , __lowerCAmelCase : float , __lowerCAmelCase : float , __lowerCAmelCase : float ) -> complex: __lowerCamelCase = math.radians(__lowerCAmelCase ) __lowerCamelCase = math.radians(__lowerCAmelCase ) # Convert voltage and current to rectangular form __lowerCamelCase = cmath.rect(__lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase = cmath.rect(__lowerCAmelCase , __lowerCAmelCase ) # Calculate apparent power return voltage_rect * current_rect if __name__ == "__main__": import doctest doctest.testmod()
370
from __future__ import annotations def __magic_name__ ( __lowerCAmelCase : list[int] ) -> bool: return len(set(__lowerCAmelCase ) ) == len(__lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
339
0
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert 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 AlignProcessor, EfficientNetImageProcessor @require_vision class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Union[str, Any] ) -> str: __lowerCamelCase = tempfile.mkdtemp() __lowerCamelCase = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] __lowerCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) __lowerCamelCase = { '''do_resize''': True, '''size''': 20, '''do_center_crop''': True, '''crop_size''': 18, '''do_normalize''': True, '''image_mean''': [0.48145466, 0.4578275, 0.40821073], '''image_std''': [0.26862954, 0.26130258, 0.27577711], } __lowerCamelCase = os.path.join(self.tmpdirname , SCREAMING_SNAKE_CASE__ ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : int , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: return BertTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def __A ( self : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : List[str] ) -> int: return BertTokenizerFast.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[Any] , **SCREAMING_SNAKE_CASE__ : Tuple ) -> Optional[int]: return EfficientNetImageProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[Any] ) -> Tuple: shutil.rmtree(self.tmpdirname ) def __A ( self : List[str] ) -> Any: __lowerCamelCase = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] __lowerCamelCase = [Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def __A ( self : Union[str, Any] ) -> int: __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = self.get_rust_tokenizer() __lowerCamelCase = self.get_image_processor() __lowerCamelCase = AlignProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) processor_slow.save_pretrained(self.tmpdirname ) __lowerCamelCase = AlignProcessor.from_pretrained(self.tmpdirname , use_fast=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = AlignProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) processor_fast.save_pretrained(self.tmpdirname ) __lowerCamelCase = AlignProcessor.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 , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor_fast.tokenizer , SCREAMING_SNAKE_CASE__ ) 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 , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor_fast.image_processor , SCREAMING_SNAKE_CASE__ ) def __A ( self : List[str] ) -> Optional[int]: __lowerCamelCase = AlignProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __lowerCamelCase = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __lowerCamelCase = self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) __lowerCamelCase = AlignProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , SCREAMING_SNAKE_CASE__ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[Any] ) -> Tuple: __lowerCamelCase = self.get_image_processor() __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = AlignProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.prepare_image_inputs() __lowerCamelCase = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='''np''' ) __lowerCamelCase = processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='''np''' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __A ( self : Optional[Any] ) -> Optional[int]: __lowerCamelCase = self.get_image_processor() __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = AlignProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = '''lower newer''' __lowerCamelCase = processor(text=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = tokenizer(SCREAMING_SNAKE_CASE__ , padding='''max_length''' , max_length=64 ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __A ( self : List[str] ) -> Any: __lowerCamelCase = self.get_image_processor() __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = AlignProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = '''lower newer''' __lowerCamelCase = self.prepare_image_inputs() __lowerCamelCase = processor(text=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE__ ): processor() def __A ( self : Optional[Any] ) -> Union[str, Any]: __lowerCamelCase = self.get_image_processor() __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = AlignProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __lowerCamelCase = processor.batch_decode(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : Dict ) -> Optional[Any]: __lowerCamelCase = self.get_image_processor() __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = AlignProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = '''lower newer''' __lowerCamelCase = self.prepare_image_inputs() __lowerCamelCase = processor(text=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
371
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) SCREAMING_SNAKE_CASE__ : Dict = { "configuration_falcon": ["FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP", "FalconConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Tuple = [ "FALCON_PRETRAINED_MODEL_ARCHIVE_LIST", "FalconForCausalLM", "FalconModel", "FalconPreTrainedModel", "FalconForSequenceClassification", "FalconForTokenClassification", "FalconForQuestionAnswering", ] if TYPE_CHECKING: from .configuration_falcon import FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP, FalconConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_falcon import ( FALCON_PRETRAINED_MODEL_ARCHIVE_LIST, FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, FalconPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
339
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { "facebook/xmod-base": "https://huggingface.co/facebook/xmod-base/resolve/main/config.json", "facebook/xmod-large-prenorm": "https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json", "facebook/xmod-base-13-125k": "https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json", "facebook/xmod-base-30-125k": "https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json", "facebook/xmod-base-30-195k": "https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json", "facebook/xmod-base-60-125k": "https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json", "facebook/xmod-base-60-265k": "https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json", "facebook/xmod-base-75-125k": "https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json", "facebook/xmod-base-75-269k": "https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json", } class lowerCAmelCase__ ( __lowercase ): a__ : Dict = """xmod""" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3_05_22 , SCREAMING_SNAKE_CASE__ : str=7_68 , SCREAMING_SNAKE_CASE__ : int=12 , SCREAMING_SNAKE_CASE__ : Dict=12 , SCREAMING_SNAKE_CASE__ : List[str]=30_72 , SCREAMING_SNAKE_CASE__ : List[Any]="gelu" , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : int=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=5_12 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=0.02 , SCREAMING_SNAKE_CASE__ : Optional[Any]=1e-12 , SCREAMING_SNAKE_CASE__ : List[str]=1 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0 , SCREAMING_SNAKE_CASE__ : int=2 , SCREAMING_SNAKE_CASE__ : Any="absolute" , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : Tuple=2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Dict=("en_XX",) , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , **SCREAMING_SNAKE_CASE__ : int , ) -> str: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = vocab_size __lowerCamelCase = hidden_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = hidden_act __lowerCamelCase = intermediate_size __lowerCamelCase = hidden_dropout_prob __lowerCamelCase = attention_probs_dropout_prob __lowerCamelCase = max_position_embeddings __lowerCamelCase = type_vocab_size __lowerCamelCase = initializer_range __lowerCamelCase = layer_norm_eps __lowerCamelCase = position_embedding_type __lowerCamelCase = use_cache __lowerCamelCase = classifier_dropout __lowerCamelCase = pre_norm __lowerCamelCase = adapter_reduction_factor __lowerCamelCase = adapter_layer_norm __lowerCamelCase = adapter_reuse_layer_norm __lowerCamelCase = ln_before_adapter __lowerCamelCase = list(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = default_language class lowerCAmelCase__ ( __lowercase ): @property def __A ( self : Optional[Any] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": __lowerCamelCase = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: __lowerCamelCase = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
350
def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int ) -> int: return abs(__lowerCAmelCase ) if a == 0 else greatest_common_divisor(b % a , __lowerCAmelCase ) def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int ) -> int: while y: # --> when y=0 then loop will terminate and return x as final GCD. __lowerCamelCase , __lowerCamelCase = y, x % y return abs(__lowerCAmelCase ) def __magic_name__ ( ) -> Tuple: try: __lowerCamelCase = input('''Enter two integers separated by comma (,): ''' ).split(''',''' ) __lowerCamelCase = int(nums[0] ) __lowerCamelCase = int(nums[1] ) print( f'''greatest_common_divisor({num_a}, {num_a}) = ''' f'''{greatest_common_divisor(__lowerCAmelCase , __lowerCAmelCase )}''' ) print(f'''By iterative gcd({num_a}, {num_a}) = {gcd_by_iterative(__lowerCAmelCase , __lowerCAmelCase )}''' ) except (IndexError, UnboundLocalError, ValueError): print('''Wrong input''' ) if __name__ == "__main__": main()
339
0
"""simple docstring""" SCREAMING_SNAKE_CASE__ : int = [0, 2, 4, 6, 8] SCREAMING_SNAKE_CASE__ : Dict = [1, 3, 5, 7, 9] def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int , __lowerCAmelCase : list[int] , __lowerCAmelCase : int ) -> int: if remaining_length == 0: if digits[0] == 0 or digits[-1] == 0: return 0 for i in range(length // 2 - 1 , -1 , -1 ): remainder += digits[i] + digits[length - i - 1] if remainder % 2 == 0: return 0 remainder //= 10 return 1 if remaining_length == 1: if remainder % 2 == 0: return 0 __lowerCamelCase = 0 for digit in range(10 ): __lowerCamelCase = digit result += reversible_numbers( 0 , (remainder + 2 * digit) // 10 , __lowerCAmelCase , __lowerCAmelCase ) return result __lowerCamelCase = 0 for digita in range(10 ): __lowerCamelCase = digita if (remainder + digita) % 2 == 0: __lowerCamelCase = ODD_DIGITS else: __lowerCamelCase = EVEN_DIGITS for digita in other_parity_digits: __lowerCamelCase = digita result += reversible_numbers( remaining_length - 2 , (remainder + digita + digita) // 10 , __lowerCAmelCase , __lowerCAmelCase , ) return result def __magic_name__ ( __lowerCAmelCase : int = 9 ) -> int: __lowerCamelCase = 0 for length in range(1 , max_power + 1 ): result += reversible_numbers(__lowerCAmelCase , 0 , [0] * length , __lowerCAmelCase ) return result if __name__ == "__main__": print(F'{solution() = }')
351
import unittest from transformers import is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, require_torch, slow if is_flax_available(): import optax from flax.training.common_utils import onehot from transformers import AutoTokenizer, FlaxMTaForConditionalGeneration from transformers.models.ta.modeling_flax_ta import shift_tokens_right @require_torch @require_sentencepiece @require_tokenizers @require_flax class lowerCAmelCase__ ( unittest.TestCase ): @slow def __A ( self : Optional[int] ) -> Union[str, Any]: __lowerCamelCase = FlaxMTaForConditionalGeneration.from_pretrained('''google/mt5-small''' ) __lowerCamelCase = AutoTokenizer.from_pretrained('''google/mt5-small''' ) __lowerCamelCase = tokenizer('''Hello there''' , return_tensors='''np''' ).input_ids __lowerCamelCase = tokenizer('''Hi I am''' , return_tensors='''np''' ).input_ids __lowerCamelCase = shift_tokens_right(SCREAMING_SNAKE_CASE__ , model.config.pad_token_id , model.config.decoder_start_token_id ) __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ , decoder_input_ids=SCREAMING_SNAKE_CASE__ ).logits __lowerCamelCase = optax.softmax_cross_entropy(SCREAMING_SNAKE_CASE__ , onehot(SCREAMING_SNAKE_CASE__ , logits.shape[-1] ) ).mean() __lowerCamelCase = -(labels.shape[-1] * loss.item()) __lowerCamelCase = -84.9127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1e-4 )
339
0
def __magic_name__ ( __lowerCAmelCase : Dict , __lowerCAmelCase : Any , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : Dict , __lowerCAmelCase : Optional[int] ) -> List[Any]: if index == r: for j in range(__lowerCAmelCase ): print(data[j] , end=''' ''' ) print(''' ''' ) return # When no more elements are there to put in data[] if i >= n: return # current is included, put next at next location __lowerCamelCase = arr[i] combination_util(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , index + 1 , __lowerCAmelCase , i + 1 ) # current is excluded, replace it with # next (Note that i+1 is passed, but # index is not changed) combination_util(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , i + 1 ) # The main function that prints all combinations # of size r in arr[] of size n. This function # mainly uses combinationUtil() def __magic_name__ ( __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Optional[Any] ) -> Optional[Any]: # A temporary array to store all combination one by one __lowerCamelCase = [0] * r # Print all combination using temporary array 'data[]' combination_util(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , 0 , __lowerCAmelCase , 0 ) if __name__ == "__main__": # Driver code to check the function above SCREAMING_SNAKE_CASE__ : int = [10, 20, 30, 40, 50] print_combination(arr, len(arr), 3) # This code is contributed by Ambuj sahu
352
import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer SCREAMING_SNAKE_CASE__ : Optional[int] = "bart" SCREAMING_SNAKE_CASE__ : Dict = True @st.cache(allow_output_mutation=__lowerCAmelCase ) def __magic_name__ ( ) -> str: if LOAD_DENSE_INDEX: __lowerCamelCase = AutoTokenizer.from_pretrained('''yjernite/retribert-base-uncased''' ) __lowerCamelCase = AutoModel.from_pretrained('''yjernite/retribert-base-uncased''' ).to('''cuda:0''' ) __lowerCamelCase = qar_model.eval() else: __lowerCamelCase , __lowerCamelCase = (None, None) if MODEL_TYPE == "bart": __lowerCamelCase = AutoTokenizer.from_pretrained('''yjernite/bart_eli5''' ) __lowerCamelCase = AutoModelForSeqaSeqLM.from_pretrained('''yjernite/bart_eli5''' ).to('''cuda:0''' ) __lowerCamelCase = torch.load('''seq2seq_models/eli5_bart_model_blm_2.pth''' ) sas_model.load_state_dict(save_dict['''model'''] ) __lowerCamelCase = sas_model.eval() else: __lowerCamelCase , __lowerCamelCase = make_qa_sas_model( model_name='''t5-small''' , from_file='''seq2seq_models/eli5_t5_model_1024_4.pth''' , device='''cuda:0''' ) return (qar_tokenizer, qar_model, sas_tokenizer, sas_model) @st.cache(allow_output_mutation=__lowerCAmelCase ) def __magic_name__ ( ) -> Optional[int]: if LOAD_DENSE_INDEX: __lowerCamelCase = faiss.StandardGpuResources() __lowerCamelCase = datasets.load_dataset(path='''wiki_snippets''' , name='''wiki40b_en_100_0''' )['''train'''] __lowerCamelCase = np.memmap( '''wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat''' , dtype='''float32''' , mode='''r''' , shape=(wikiaab_passages.num_rows, 128) , ) __lowerCamelCase = faiss.IndexFlatIP(128 ) __lowerCamelCase = faiss.index_cpu_to_gpu(__lowerCAmelCase , 1 , __lowerCAmelCase ) wikiaab_gpu_index_flat.add(__lowerCAmelCase ) # TODO fix for larger GPU else: __lowerCamelCase , __lowerCamelCase = (None, None) __lowerCamelCase = Elasticsearch([{'''host''': '''localhost''', '''port''': '''9200'''}] ) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=__lowerCAmelCase ) def __magic_name__ ( ) -> List[str]: __lowerCamelCase = datasets.load_dataset('''eli5''' , name='''LFQA_reddit''' ) __lowerCamelCase = elia['''train_eli5'''] __lowerCamelCase = np.memmap( '''eli5_questions_reps.dat''' , dtype='''float32''' , mode='''r''' , shape=(elia_train.num_rows, 128) ) __lowerCamelCase = faiss.IndexFlatIP(128 ) eli5_train_q_index.add(__lowerCAmelCase ) return (elia_train, eli5_train_q_index) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = load_indexes() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = load_models() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = load_train_data() def __magic_name__ ( __lowerCAmelCase : Dict , __lowerCAmelCase : List[str]=10 ) -> List[str]: __lowerCamelCase = embed_questions_for_retrieval([question] , __lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase , __lowerCamelCase = eli5_train_q_index.search(__lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase = [elia_train[int(__lowerCAmelCase )] for i in I[0]] return nn_examples def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : Dict="wiki40b" , __lowerCAmelCase : Any="dense" , __lowerCAmelCase : Dict=10 ) -> Union[str, Any]: if source == "none": __lowerCamelCase , __lowerCamelCase = (''' <P> '''.join(['''''' for _ in range(11 )] ).strip(), []) else: if method == "dense": __lowerCamelCase , __lowerCamelCase = query_qa_dense_index( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) else: __lowerCamelCase , __lowerCamelCase = query_es_index( __lowerCAmelCase , __lowerCAmelCase , index_name='''english_wiki40b_snippets_100w''' , n_results=__lowerCAmelCase , ) __lowerCamelCase = [ (res['''article_title'''], res['''section_title'''].strip(), res['''score'''], res['''passage_text''']) for res in hit_lst ] __lowerCamelCase = '''question: {} context: {}'''.format(__lowerCAmelCase , __lowerCAmelCase ) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda __lowerCAmelCase : None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda __lowerCAmelCase : None), } ) def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : Dict , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : str=64 , __lowerCAmelCase : Dict=256 , __lowerCAmelCase : Union[str, Any]=False , __lowerCAmelCase : Optional[int]=2 , __lowerCAmelCase : Optional[Any]=0.95 , __lowerCAmelCase : List[Any]=0.8 ) -> Any: with torch.no_grad(): __lowerCamelCase = qa_sas_generate( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , num_answers=1 , num_beams=__lowerCAmelCase , min_len=__lowerCAmelCase , max_len=__lowerCAmelCase , do_sample=__lowerCAmelCase , temp=__lowerCAmelCase , top_p=__lowerCAmelCase , top_k=__lowerCAmelCase , max_input_length=1024 , device='''cuda:0''' , )[0] return (answer, support_list) st.title("Long Form Question Answering with ELI5") # Start sidebar SCREAMING_SNAKE_CASE__ : List[str] = "<img src='https://huggingface.co/front/assets/huggingface_logo.svg'>" SCREAMING_SNAKE_CASE__ : Dict = "\n<html>\n <head>\n <style>\n .img-container {\n padding-left: 90px;\n padding-right: 90px;\n padding-top: 50px;\n padding-bottom: 50px;\n background-color: #f0f3f9;\n }\n </style>\n </head>\n <body>\n <span class=\"img-container\"> <!-- Inline parent element -->\n %s\n </span>\n </body>\n</html>\n" % ( header_html, ) st.sidebar.markdown( header_full, unsafe_allow_html=True, ) # Long Form QA with ELI5 and Wikipedia SCREAMING_SNAKE_CASE__ : int = "\nThis demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).\nFirst, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,\na pre-processed fixed snapshot of Wikipedia.\n" st.sidebar.markdown(description, unsafe_allow_html=True) SCREAMING_SNAKE_CASE__ : str = [ "Answer the question", "View the retrieved document only", "View the most similar ELI5 question and answer", "Show me everything, please!", ] SCREAMING_SNAKE_CASE__ : Optional[int] = st.sidebar.checkbox("Demo options") if demo_options: SCREAMING_SNAKE_CASE__ : Optional[int] = st.sidebar.selectbox( "", action_list, index=3, ) SCREAMING_SNAKE_CASE__ : Optional[Any] = action_list.index(action_st) SCREAMING_SNAKE_CASE__ : int = st.sidebar.selectbox( "", ["Show full text of passages", "Show passage section titles"], index=0, ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = show_type == "Show full text of passages" else: SCREAMING_SNAKE_CASE__ : Any = 3 SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : Union[str, Any] = st.sidebar.checkbox("Retrieval options") if retrieval_options: SCREAMING_SNAKE_CASE__ : Tuple = "\n ### Information retriever options\n\n The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding\n trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.\n The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.\n " st.sidebar.markdown(retriever_info) SCREAMING_SNAKE_CASE__ : Union[str, Any] = st.sidebar.selectbox("Which Wikipedia format should the model use?", ["wiki40b", "none"]) SCREAMING_SNAKE_CASE__ : int = st.sidebar.selectbox("Which Wikipedia indexer should the model use?", ["dense", "sparse", "mixed"]) else: SCREAMING_SNAKE_CASE__ : List[str] = "wiki40b" SCREAMING_SNAKE_CASE__ : Optional[Any] = "dense" SCREAMING_SNAKE_CASE__ : str = "beam" SCREAMING_SNAKE_CASE__ : List[Any] = 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = 64 SCREAMING_SNAKE_CASE__ : List[Any] = 256 SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : List[str] = st.sidebar.checkbox("Generation options") if generate_options: SCREAMING_SNAKE_CASE__ : Dict = "\n ### Answer generation options\n\n The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)\n weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with\n **beam** search, or **sample** from the decoder's output probabilities.\n " st.sidebar.markdown(generate_info) SCREAMING_SNAKE_CASE__ : List[str] = st.sidebar.selectbox("Would you like to use beam search or sample an answer?", ["beam", "sampled"]) SCREAMING_SNAKE_CASE__ : Any = st.sidebar.slider( "Minimum generation length", min_value=8, max_value=256, value=64, step=8, format=None, key=None ) SCREAMING_SNAKE_CASE__ : str = st.sidebar.slider( "Maximum generation length", min_value=64, max_value=512, value=256, step=16, format=None, key=None ) if sampled == "beam": SCREAMING_SNAKE_CASE__ : Union[str, Any] = st.sidebar.slider("Beam size", min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: SCREAMING_SNAKE_CASE__ : Any = st.sidebar.slider( "Nucleus sampling p", min_value=0.1, max_value=1.0, value=0.9_5, step=0.0_1, format=None, key=None ) SCREAMING_SNAKE_CASE__ : Dict = st.sidebar.slider( "Temperature", min_value=0.1, max_value=1.0, value=0.7, step=0.0_1, format=None, key=None ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = None # start main text SCREAMING_SNAKE_CASE__ : Any = [ "<MY QUESTION>", "How do people make chocolate?", "Why do we get a fever when we are sick?", "How can different animals perceive different colors?", "What is natural language processing?", "What's the best way to treat a sunburn?", "What exactly are vitamins ?", "How does nuclear energy provide electricity?", "What's the difference between viruses and bacteria?", "Why are flutes classified as woodwinds when most of them are made out of metal ?", "Why do people like drinking coffee even though it tastes so bad?", "What happens when wine ages? How does it make the wine taste better?", "If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?", "How can we set a date to the beginning or end of an artistic period? Doesn't the change happen gradually?", "How does New Zealand have so many large bird predators?", ] SCREAMING_SNAKE_CASE__ : List[str] = st.selectbox( "What would you like to ask? ---- select <MY QUESTION> to enter a new query", questions_list, index=1, ) if question_s == "<MY QUESTION>": SCREAMING_SNAKE_CASE__ : Union[str, Any] = st.text_input("Enter your question here:", "") else: SCREAMING_SNAKE_CASE__ : str = question_s if st.button("Show me!"): if action in [0, 1, 3]: if index_type == "mixed": SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = make_support(question, source=wiki_source, method="dense", n_results=10) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = make_support(question, source=wiki_source, method="sparse", n_results=10) SCREAMING_SNAKE_CASE__ : int = [] for res_d, res_s in zip(support_list_dense, support_list_sparse): if tuple(res_d) not in support_list: support_list += [tuple(res_d)] if tuple(res_s) not in support_list: support_list += [tuple(res_s)] SCREAMING_SNAKE_CASE__ : Optional[Any] = support_list[:10] SCREAMING_SNAKE_CASE__ : Tuple = "<P> " + " <P> ".join([res[-1] for res in support_list]) else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = answer_question( question_doc, sas_model, sas_tokenizer, min_len=min_len, max_len=int(max_len), sampling=(sampled == "sampled"), n_beams=n_beams, top_p=top_p, temp=temp, ) st.markdown("### The model generated answer is:") st.write(answer) if action in [0, 1, 3] and wiki_source != "none": st.markdown("--- \n ### The model is drawing information from the following Wikipedia passages:") for i, res in enumerate(support_list): SCREAMING_SNAKE_CASE__ : Optional[int] = "https://en.wikipedia.org/wiki/{}".format(res[0].replace(" ", "_")) SCREAMING_SNAKE_CASE__ : Tuple = res[1].strip() if sec_titles == "": SCREAMING_SNAKE_CASE__ : Union[str, Any] = "[{}]({})".format(res[0], wiki_url) else: SCREAMING_SNAKE_CASE__ : Dict = sec_titles.split(" & ") SCREAMING_SNAKE_CASE__ : int = " & ".join( ["[{}]({}#{})".format(sec.strip(), wiki_url, sec.strip().replace(" ", "_")) for sec in sec_list] ) st.markdown( "{0:02d} - **Article**: {1:<18} <br> _Section_: {2}".format(i + 1, res[0], sections), unsafe_allow_html=True, ) if show_passages: st.write( "> <span style=\"font-family:arial; font-size:10pt;\">" + res[-1] + "</span>", unsafe_allow_html=True ) if action in [2, 3]: SCREAMING_SNAKE_CASE__ : Any = find_nearest_training(question) SCREAMING_SNAKE_CASE__ : List[Any] = nn_train_list[0] st.markdown( "--- \n ### The most similar question in the ELI5 training set was: \n\n {}".format(train_exple["title"]) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ "{}. {}".format(i + 1, " \n".join([line.strip() for line in ans.split("\n") if line.strip() != ""])) for i, (ans, sc) in enumerate(zip(train_exple["answers"]["text"], train_exple["answers"]["score"])) if i == 0 or sc > 2 ] st.markdown("##### Its answers were: \n\n {}".format("\n".join(answers_st))) SCREAMING_SNAKE_CASE__ : List[Any] = "\n---\n\n**Disclaimer**\n\n*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.\nEvaluating biases of such a model and ensuring factual generations are still very much open research problems.\nTherefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*\n" st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
339
0
def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int ) -> str: return "\n".join( f'''{number} * {i} = {number * i}''' for i in range(1 , number_of_terms + 1 ) ) if __name__ == "__main__": print(multiplication_table(number=5, number_of_terms=10))
353
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : List[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : str = { "facebook/xmod-base": "https://huggingface.co/facebook/xmod-base/resolve/main/config.json", "facebook/xmod-large-prenorm": "https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json", "facebook/xmod-base-13-125k": "https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json", "facebook/xmod-base-30-125k": "https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json", "facebook/xmod-base-30-195k": "https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json", "facebook/xmod-base-60-125k": "https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json", "facebook/xmod-base-60-265k": "https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json", "facebook/xmod-base-75-125k": "https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json", "facebook/xmod-base-75-269k": "https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json", } class lowerCAmelCase__ ( __lowercase ): a__ : Dict = """xmod""" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3_05_22 , SCREAMING_SNAKE_CASE__ : str=7_68 , SCREAMING_SNAKE_CASE__ : int=12 , SCREAMING_SNAKE_CASE__ : Dict=12 , SCREAMING_SNAKE_CASE__ : List[str]=30_72 , SCREAMING_SNAKE_CASE__ : List[Any]="gelu" , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : int=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=5_12 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=0.02 , SCREAMING_SNAKE_CASE__ : Optional[Any]=1e-12 , SCREAMING_SNAKE_CASE__ : List[str]=1 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0 , SCREAMING_SNAKE_CASE__ : int=2 , SCREAMING_SNAKE_CASE__ : Any="absolute" , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : Tuple=2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Dict=("en_XX",) , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , **SCREAMING_SNAKE_CASE__ : int , ) -> str: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = vocab_size __lowerCamelCase = hidden_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = hidden_act __lowerCamelCase = intermediate_size __lowerCamelCase = hidden_dropout_prob __lowerCamelCase = attention_probs_dropout_prob __lowerCamelCase = max_position_embeddings __lowerCamelCase = type_vocab_size __lowerCamelCase = initializer_range __lowerCamelCase = layer_norm_eps __lowerCamelCase = position_embedding_type __lowerCamelCase = use_cache __lowerCamelCase = classifier_dropout __lowerCamelCase = pre_norm __lowerCamelCase = adapter_reduction_factor __lowerCamelCase = adapter_layer_norm __lowerCamelCase = adapter_reuse_layer_norm __lowerCamelCase = ln_before_adapter __lowerCamelCase = list(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = default_language class lowerCAmelCase__ ( __lowercase ): @property def __A ( self : Optional[Any] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": __lowerCamelCase = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: __lowerCamelCase = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
339
0
import logging import os from dataclasses import dataclass, field from functools import partial from pathlib import Path from tempfile import TemporaryDirectory from typing import List, Optional import faiss import torch from datasets import Features, Sequence, Value, load_dataset from transformers import DPRContextEncoder, DPRContextEncoderTokenizerFast, HfArgumentParser SCREAMING_SNAKE_CASE__ : Optional[Any] = logging.getLogger(__name__) torch.set_grad_enabled(False) SCREAMING_SNAKE_CASE__ : int = "cuda" if torch.cuda.is_available() else "cpu" def __magic_name__ ( __lowerCAmelCase : str , __lowerCAmelCase : Tuple=100 , __lowerCAmelCase : Optional[int]=" " ) -> List[str]: __lowerCamelCase = text.split(__lowerCAmelCase ) return [character.join(text[i : i + n] ).strip() for i in range(0 , len(__lowerCAmelCase ) , __lowerCAmelCase )] def __magic_name__ ( __lowerCAmelCase : dict ) -> dict: __lowerCamelCase , __lowerCamelCase = [], [] for title, text in zip(documents['''title'''] , documents['''text'''] ): if text is not None: for passage in split_text(__lowerCAmelCase ): titles.append(title if title is not None else '''''' ) texts.append(__lowerCAmelCase ) return {"title": titles, "text": texts} def __magic_name__ ( __lowerCAmelCase : dict , __lowerCAmelCase : DPRContextEncoder , __lowerCAmelCase : DPRContextEncoderTokenizerFast ) -> dict: __lowerCamelCase = ctx_tokenizer( documents['''title'''] , documents['''text'''] , truncation=__lowerCAmelCase , padding='''longest''' , return_tensors='''pt''' )['''input_ids'''] __lowerCamelCase = ctx_encoder(input_ids.to(device=__lowerCAmelCase ) , return_dict=__lowerCAmelCase ).pooler_output return {"embeddings": embeddings.detach().cpu().numpy()} def __magic_name__ ( __lowerCAmelCase : "RagExampleArguments" , __lowerCAmelCase : "ProcessingArguments" , __lowerCAmelCase : "IndexHnswArguments" , ) -> List[str]: ###################################### logger.info('''Step 1 - Create the dataset''' ) ###################################### # The dataset needed for RAG must have three columns: # - title (string): title of the document # - text (string): text of a passage of the document # - embeddings (array of dimension d): DPR representation of the passage # Let's say you have documents in tab-separated csv files with columns "title" and "text" assert os.path.isfile(rag_example_args.csv_path ), "Please provide a valid path to a csv file" # You can load a Dataset object this way __lowerCamelCase = load_dataset( '''csv''' , data_files=[rag_example_args.csv_path] , split='''train''' , delimiter='''\t''' , column_names=['''title''', '''text'''] ) # More info about loading csv files in the documentation: https://huggingface.co/docs/datasets/loading_datasets.html?highlight=csv#csv-files # Then split the documents into passages of 100 words __lowerCamelCase = dataset.map(__lowerCAmelCase , batched=__lowerCAmelCase , num_proc=processing_args.num_proc ) # And compute the embeddings __lowerCamelCase = DPRContextEncoder.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ).to(device=__lowerCAmelCase ) __lowerCamelCase = DPRContextEncoderTokenizerFast.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ) __lowerCamelCase = Features( {'''text''': Value('''string''' ), '''title''': Value('''string''' ), '''embeddings''': Sequence(Value('''float32''' ) )} ) # optional, save as float32 instead of float64 to save space __lowerCamelCase = dataset.map( partial(__lowerCAmelCase , ctx_encoder=__lowerCAmelCase , ctx_tokenizer=__lowerCAmelCase ) , batched=__lowerCAmelCase , batch_size=processing_args.batch_size , features=__lowerCAmelCase , ) # And finally save your dataset __lowerCamelCase = os.path.join(rag_example_args.output_dir , '''my_knowledge_dataset''' ) dataset.save_to_disk(__lowerCAmelCase ) # from datasets import load_from_disk # dataset = load_from_disk(passages_path) # to reload the dataset ###################################### logger.info('''Step 2 - Index the dataset''' ) ###################################### # Let's use the Faiss implementation of HNSW for fast approximate nearest neighbor search __lowerCamelCase = faiss.IndexHNSWFlat(index_hnsw_args.d , index_hnsw_args.m , faiss.METRIC_INNER_PRODUCT ) dataset.add_faiss_index('''embeddings''' , custom_index=__lowerCAmelCase ) # And save the index __lowerCamelCase = os.path.join(rag_example_args.output_dir , '''my_knowledge_dataset_hnsw_index.faiss''' ) dataset.get_index('''embeddings''' ).save(__lowerCAmelCase ) # dataset.load_faiss_index("embeddings", index_path) # to reload the index @dataclass class lowerCAmelCase__ : a__ : str = field( default=str(Path(__lowercase ).parent / """test_run""" / """dummy-kb""" / """my_knowledge_dataset.csv""" ) , metadata={"""help""": """Path to a tab-separated csv file with columns 'title' and 'text'"""} , ) a__ : Optional[str] = field( default=__lowercase , metadata={"""help""": """Question that is passed as input to RAG. Default is 'What does Moses' rod turn into ?'."""} , ) a__ : str = field( default="""facebook/rag-sequence-nq""" , metadata={"""help""": """The RAG model to use. Either 'facebook/rag-sequence-nq' or 'facebook/rag-token-nq'"""} , ) a__ : str = field( default="""facebook/dpr-ctx_encoder-multiset-base""" , metadata={ """help""": ( """The DPR context encoder model to use. Either 'facebook/dpr-ctx_encoder-single-nq-base' or""" """ 'facebook/dpr-ctx_encoder-multiset-base'""" ) } , ) a__ : Optional[str] = field( default=str(Path(__lowercase ).parent / """test_run""" / """dummy-kb""" ) , metadata={"""help""": """Path to a directory where the dataset passages and the index will be saved"""} , ) @dataclass class lowerCAmelCase__ : a__ : Optional[int] = field( default=__lowercase , metadata={ """help""": """The number of processes to use to split the documents into passages. Default is single process.""" } , ) a__ : int = field( default=16 , metadata={ """help""": """The batch size to use when computing the passages embeddings using the DPR context encoder.""" } , ) @dataclass class lowerCAmelCase__ : a__ : int = field( default=768 , metadata={"""help""": """The dimension of the embeddings to pass to the HNSW Faiss index."""} , ) a__ : int = field( default=128 , metadata={ """help""": ( """The number of bi-directional links created for every new element during the HNSW index construction.""" ) } , ) if __name__ == "__main__": logging.basicConfig(level=logging.WARNING) logger.setLevel(logging.INFO) SCREAMING_SNAKE_CASE__ : Any = HfArgumentParser((RagExampleArguments, ProcessingArguments, IndexHnswArguments)) SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.parse_args_into_dataclasses() with TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE__ : Union[str, Any] = rag_example_args.output_dir or tmp_dir main(rag_example_args, processing_args, index_hnsw_args)
354
from collections import namedtuple import requests from lxml import html # type: ignore SCREAMING_SNAKE_CASE__ : List[Any] = namedtuple("covid_data", "cases deaths recovered") def __magic_name__ ( __lowerCAmelCase : str = "https://www.worldometers.info/coronavirus/" ) -> covid_data: __lowerCamelCase = '''//div[@class = "maincounter-number"]/span/text()''' return covid_data(*html.fromstring(requests.get(__lowerCAmelCase ).content ).xpath(__lowerCAmelCase ) ) SCREAMING_SNAKE_CASE__ : List[str] = "Total COVID-19 cases in the world: {}\nTotal deaths due to COVID-19 in the world: {}\nTotal COVID-19 patients recovered in the world: {}" print(fmt.format(*covid_stats()))
339
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 lowerCAmelCase__ ( unittest.TestCase ): @slow def __A ( self : Any ) -> List[str]: __lowerCamelCase = TFCamembertModel.from_pretrained('''jplu/tf-camembert-base''' ) __lowerCamelCase = tf.convert_to_tensor( [[5, 1_21, 11, 6_60, 16, 7_30, 2_55_43, 1_10, 83, 6]] , dtype=tf.intaa , ) # J'aime le camembert !" __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ )['''last_hidden_state'''] __lowerCamelCase = tf.TensorShape((1, 10, 7_68) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE__ ) # compare the actual values for a slice. __lowerCamelCase = tf.convert_to_tensor( [[[-0.0254, 0.0235, 0.1027], [0.0606, -0.1811, -0.0418], [-0.1561, -0.1127, 0.2687]]] , 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 ) )
355
import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer, HfArgumentParser, MBartTokenizer, MBartTokenizerFast, set_seed, ) from transformers.trainer_utils import EvaluationStrategy, is_main_process from transformers.training_args import ParallelMode from utils import ( SeqaSeqDataCollator, SeqaSeqDataset, assert_all_frozen, build_compute_metrics_fn, check_output_dir, freeze_embeds, freeze_params, lmap, save_json, use_task_specific_params, write_txt_file, ) SCREAMING_SNAKE_CASE__ : int = logging.getLogger(__name__) @dataclass class lowerCAmelCase__ : a__ : str = field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} ) a__ : Optional[str] = field( default=__lowercase , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) a__ : Optional[str] = field( default=__lowercase , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} ) a__ : Optional[str] = field( default=__lowercase , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) a__ : bool = field(default=__lowercase , metadata={"""help""": """Whether tp freeze the encoder."""} ) a__ : bool = field(default=__lowercase , metadata={"""help""": """Whether to freeze the embeddings."""} ) @dataclass class lowerCAmelCase__ : a__ : str = field( metadata={"""help""": """The input data dir. Should contain the .tsv files (or other data files) for the task."""} ) a__ : Optional[str] = field( default="""summarization""" , metadata={"""help""": """Task name, summarization (or summarization_{dataset} for pegasus) or translation"""} , ) a__ : Optional[int] = field( default=1_024 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) a__ : Optional[int] = field( default=128 , metadata={ """help""": ( """The maximum total sequence length for target text after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) a__ : Optional[int] = field( default=142 , metadata={ """help""": ( """The maximum total sequence length for validation target text after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded. """ """This argument is also used to override the ``max_length`` param of ``model.generate``, which is used """ """during ``evaluate`` and ``predict``.""" ) } , ) a__ : Optional[int] = field( default=142 , metadata={ """help""": ( """The maximum total sequence length for test target text after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) a__ : Optional[int] = field(default=-1 , metadata={"""help""": """# training examples. -1 means use all."""} ) a__ : Optional[int] = field(default=-1 , metadata={"""help""": """# validation examples. -1 means use all."""} ) a__ : Optional[int] = field(default=-1 , metadata={"""help""": """# test examples. -1 means use all."""} ) a__ : Optional[str] = field(default=__lowercase , metadata={"""help""": """Source language id for translation."""} ) a__ : Optional[str] = field(default=__lowercase , metadata={"""help""": """Target language id for translation."""} ) a__ : Optional[int] = field(default=__lowercase , metadata={"""help""": """# num_beams to use for evaluation."""} ) a__ : bool = field( default=__lowercase , metadata={"""help""": """If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined."""} , ) def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : str , __lowerCAmelCase : int ) -> Dict: logger.info(f'''***** {split} metrics *****''' ) for key in sorted(metrics.keys() ): logger.info(f''' {key} = {metrics[key]}''' ) save_json(__lowerCAmelCase , os.path.join(__lowerCAmelCase , f'''{split}_results.json''' ) ) def __magic_name__ ( ) -> Optional[Any]: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. __lowerCamelCase = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) ) 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. __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = parser.parse_args_into_dataclasses() check_output_dir(__lowerCAmelCase ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info('''Training/evaluation parameters %s''' , __lowerCAmelCase ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __lowerCamelCase = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) __lowerCamelCase = ('''encoder_layerdrop''', '''decoder_layerdrop''', '''dropout''', '''attention_dropout''') for p in extra_model_params: if getattr(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): assert hasattr(__lowerCAmelCase , __lowerCAmelCase ), f'''({config.__class__.__name__}) doesn\'t have a `{p}` attribute''' setattr(__lowerCAmelCase , __lowerCAmelCase , getattr(__lowerCAmelCase , __lowerCAmelCase ) ) __lowerCamelCase = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) __lowerCamelCase = AutoModelForSeqaSeqLM.from_pretrained( model_args.model_name_or_path , from_tf='''.ckpt''' in model_args.model_name_or_path , config=__lowerCAmelCase , cache_dir=model_args.cache_dir , ) # use task specific params use_task_specific_params(__lowerCAmelCase , data_args.task ) # set num_beams for evaluation if data_args.eval_beams is None: __lowerCamelCase = model.config.num_beams # set decoder_start_token_id for MBart if model.config.decoder_start_token_id is None and isinstance(__lowerCAmelCase , (MBartTokenizer, MBartTokenizerFast) ): assert ( data_args.tgt_lang is not None and data_args.src_lang is not None ), "mBart requires --tgt_lang and --src_lang" if isinstance(__lowerCAmelCase , __lowerCAmelCase ): __lowerCamelCase = tokenizer.lang_code_to_id[data_args.tgt_lang] else: __lowerCamelCase = tokenizer.convert_tokens_to_ids(data_args.tgt_lang ) if model_args.freeze_embeds: freeze_embeds(__lowerCAmelCase ) if model_args.freeze_encoder: freeze_params(model.get_encoder() ) assert_all_frozen(model.get_encoder() ) __lowerCamelCase = SeqaSeqDataset # Get datasets __lowerCamelCase = ( dataset_class( __lowerCAmelCase , type_path='''train''' , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_train else None ) __lowerCamelCase = ( dataset_class( __lowerCAmelCase , type_path='''val''' , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO else None ) __lowerCamelCase = ( dataset_class( __lowerCAmelCase , type_path='''test''' , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_predict else None ) # Initialize our Trainer __lowerCamelCase = ( build_compute_metrics_fn(data_args.task , __lowerCAmelCase ) if training_args.predict_with_generate else None ) __lowerCamelCase = SeqaSeqTrainer( model=__lowerCAmelCase , args=__lowerCAmelCase , data_args=__lowerCAmelCase , train_dataset=__lowerCAmelCase , eval_dataset=__lowerCAmelCase , data_collator=SeqaSeqDataCollator( __lowerCAmelCase , __lowerCAmelCase , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=__lowerCAmelCase , tokenizer=__lowerCAmelCase , ) __lowerCamelCase = {} # Training if training_args.do_train: logger.info('''*** Train ***''' ) __lowerCamelCase = trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) __lowerCamelCase = train_result.metrics __lowerCamelCase = data_args.n_train trainer.save_model() # this also saves the tokenizer if trainer.is_world_process_zero(): handle_metrics('''train''' , __lowerCAmelCase , training_args.output_dir ) all_metrics.update(__lowerCAmelCase ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , '''trainer_state.json''' ) ) # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) tokenizer.save_pretrained(training_args.output_dir ) # Evaluation if training_args.do_eval: logger.info('''*** Evaluate ***''' ) __lowerCamelCase = trainer.evaluate(metric_key_prefix='''val''' ) __lowerCamelCase = data_args.n_val __lowerCamelCase = round(metrics['''val_loss'''] , 4 ) if trainer.is_world_process_zero(): handle_metrics('''val''' , __lowerCAmelCase , training_args.output_dir ) all_metrics.update(__lowerCAmelCase ) if training_args.do_predict: logger.info('''*** Predict ***''' ) __lowerCamelCase = trainer.predict(test_dataset=__lowerCAmelCase , metric_key_prefix='''test''' ) __lowerCamelCase = test_output.metrics __lowerCamelCase = data_args.n_test if trainer.is_world_process_zero(): __lowerCamelCase = round(metrics['''test_loss'''] , 4 ) handle_metrics('''test''' , __lowerCAmelCase , training_args.output_dir ) all_metrics.update(__lowerCAmelCase ) if training_args.predict_with_generate: __lowerCamelCase = tokenizer.batch_decode( test_output.predictions , skip_special_tokens=__lowerCAmelCase , clean_up_tokenization_spaces=__lowerCAmelCase ) __lowerCamelCase = lmap(str.strip , __lowerCAmelCase ) write_txt_file(__lowerCAmelCase , os.path.join(training_args.output_dir , '''test_generations.txt''' ) ) if trainer.is_world_process_zero(): save_json(__lowerCAmelCase , os.path.join(training_args.output_dir , '''all_results.json''' ) ) return all_metrics def __magic_name__ ( __lowerCAmelCase : List[str] ) -> Union[str, Any]: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
339
0
import math from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : int = { "facebook/data2vec-base-960h": "https://huggingface.co/facebook/data2vec-audio-base-960h/resolve/main/config.json", # See all Data2VecAudio models at https://huggingface.co/models?filter=data2vec-audio } class lowerCAmelCase__ ( __lowercase ): a__ : Tuple = """data2vec-audio""" def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=32 , SCREAMING_SNAKE_CASE__ : Optional[int]=7_68 , SCREAMING_SNAKE_CASE__ : List[str]=12 , SCREAMING_SNAKE_CASE__ : Tuple=12 , SCREAMING_SNAKE_CASE__ : List[Any]=30_72 , SCREAMING_SNAKE_CASE__ : Optional[int]="gelu" , SCREAMING_SNAKE_CASE__ : List[str]=0.1 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.1 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.1 , SCREAMING_SNAKE_CASE__ : Dict=0.0 , SCREAMING_SNAKE_CASE__ : Tuple=0.1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.02 , SCREAMING_SNAKE_CASE__ : Any=1e-5 , SCREAMING_SNAKE_CASE__ : Dict="gelu" , SCREAMING_SNAKE_CASE__ : Tuple=(5_12, 5_12, 5_12, 5_12, 5_12, 5_12, 5_12) , SCREAMING_SNAKE_CASE__ : List[Any]=(5, 2, 2, 2, 2, 2, 2) , SCREAMING_SNAKE_CASE__ : Dict=(10, 3, 3, 3, 3, 2, 2) , SCREAMING_SNAKE_CASE__ : int=False , SCREAMING_SNAKE_CASE__ : List[str]=16 , SCREAMING_SNAKE_CASE__ : Tuple=19 , SCREAMING_SNAKE_CASE__ : Optional[Any]=5 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.05 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=10 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : int=0.0 , SCREAMING_SNAKE_CASE__ : Dict=10 , SCREAMING_SNAKE_CASE__ : str=0 , SCREAMING_SNAKE_CASE__ : Optional[Any]="sum" , SCREAMING_SNAKE_CASE__ : Tuple=False , SCREAMING_SNAKE_CASE__ : str=False , SCREAMING_SNAKE_CASE__ : Optional[Any]=2_56 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=(5_12, 5_12, 5_12, 5_12, 15_00) , SCREAMING_SNAKE_CASE__ : Dict=(5, 3, 3, 1, 1) , SCREAMING_SNAKE_CASE__ : List[str]=(1, 2, 3, 1, 1) , SCREAMING_SNAKE_CASE__ : List[str]=5_12 , SCREAMING_SNAKE_CASE__ : str=0 , SCREAMING_SNAKE_CASE__ : Dict=1 , SCREAMING_SNAKE_CASE__ : int=2 , SCREAMING_SNAKE_CASE__ : Any=False , SCREAMING_SNAKE_CASE__ : Tuple=3 , SCREAMING_SNAKE_CASE__ : str=2 , SCREAMING_SNAKE_CASE__ : List[str]=3 , SCREAMING_SNAKE_CASE__ : Any=None , **SCREAMING_SNAKE_CASE__ : Any , ) -> Any: super().__init__(**SCREAMING_SNAKE_CASE__ , pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = hidden_size __lowerCamelCase = feat_extract_activation __lowerCamelCase = list(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = list(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = list(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = conv_bias __lowerCamelCase = num_conv_pos_embeddings __lowerCamelCase = num_conv_pos_embedding_groups __lowerCamelCase = conv_pos_kernel_size __lowerCamelCase = len(self.conv_dim ) __lowerCamelCase = num_hidden_layers __lowerCamelCase = intermediate_size __lowerCamelCase = hidden_act __lowerCamelCase = num_attention_heads __lowerCamelCase = hidden_dropout __lowerCamelCase = attention_dropout __lowerCamelCase = activation_dropout __lowerCamelCase = feat_proj_dropout __lowerCamelCase = final_dropout __lowerCamelCase = layerdrop __lowerCamelCase = layer_norm_eps __lowerCamelCase = initializer_range __lowerCamelCase = vocab_size __lowerCamelCase = use_weighted_layer_sum if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( '''Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==''' ''' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =''' f''' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,''' f''' `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __lowerCamelCase = mask_time_prob __lowerCamelCase = mask_time_length __lowerCamelCase = mask_time_min_masks __lowerCamelCase = mask_feature_prob __lowerCamelCase = mask_feature_length __lowerCamelCase = mask_feature_min_masks # ctc loss __lowerCamelCase = ctc_loss_reduction __lowerCamelCase = ctc_zero_infinity # adapter __lowerCamelCase = add_adapter __lowerCamelCase = adapter_kernel_size __lowerCamelCase = adapter_stride __lowerCamelCase = num_adapter_layers __lowerCamelCase = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. __lowerCamelCase = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. __lowerCamelCase = list(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = list(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = list(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = xvector_output_dim @property def __A ( self : Tuple ) -> Optional[Any]: return math.prod(self.conv_stride )
356
import unittest import numpy as np import torch from diffusers import ScoreSdeVePipeline, ScoreSdeVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class lowerCAmelCase__ ( unittest.TestCase ): @property def __A ( self : List[Any] ) -> Optional[Any]: torch.manual_seed(0 ) __lowerCamelCase = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) return model def __A ( self : Optional[int] ) -> Optional[Any]: __lowerCamelCase = self.dummy_uncond_unet __lowerCamelCase = ScoreSdeVeScheduler() __lowerCamelCase = ScoreSdeVePipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) sde_ve.to(SCREAMING_SNAKE_CASE__ ) sde_ve.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = torch.manual_seed(0 ) __lowerCamelCase = sde_ve(num_inference_steps=2 , output_type='''numpy''' , generator=SCREAMING_SNAKE_CASE__ ).images __lowerCamelCase = torch.manual_seed(0 ) __lowerCamelCase = sde_ve(num_inference_steps=2 , output_type='''numpy''' , generator=SCREAMING_SNAKE_CASE__ , return_dict=SCREAMING_SNAKE_CASE__ )[ 0 ] __lowerCamelCase = image[0, -3:, -3:, -1] __lowerCamelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __lowerCamelCase = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Tuple ) -> str: __lowerCamelCase = '''google/ncsnpp-church-256''' __lowerCamelCase = UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = ScoreSdeVeScheduler.from_pretrained(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = ScoreSdeVePipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) sde_ve.to(SCREAMING_SNAKE_CASE__ ) sde_ve.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = torch.manual_seed(0 ) __lowerCamelCase = sde_ve(num_inference_steps=10 , output_type='''numpy''' , generator=SCREAMING_SNAKE_CASE__ ).images __lowerCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 2_56, 2_56, 3) __lowerCamelCase = np.array([0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
339
0
from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Optional[int] = { "t5-small": "https://huggingface.co/t5-small/resolve/main/config.json", "t5-base": "https://huggingface.co/t5-base/resolve/main/config.json", "t5-large": "https://huggingface.co/t5-large/resolve/main/config.json", "t5-3b": "https://huggingface.co/t5-3b/resolve/main/config.json", "t5-11b": "https://huggingface.co/t5-11b/resolve/main/config.json", } class lowerCAmelCase__ ( __lowercase ): a__ : Optional[int] = """t5""" a__ : List[Any] = ["""past_key_values"""] a__ : List[str] = {"""hidden_size""": """d_model""", """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers"""} def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str]=3_21_28 , SCREAMING_SNAKE_CASE__ : Any=5_12 , SCREAMING_SNAKE_CASE__ : str=64 , SCREAMING_SNAKE_CASE__ : Dict=20_48 , SCREAMING_SNAKE_CASE__ : Optional[Any]=6 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : str=8 , SCREAMING_SNAKE_CASE__ : str=32 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_28 , SCREAMING_SNAKE_CASE__ : Any=0.1 , SCREAMING_SNAKE_CASE__ : int=1e-6 , SCREAMING_SNAKE_CASE__ : str=1.0 , SCREAMING_SNAKE_CASE__ : Optional[int]="relu" , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : List[Any]=True , SCREAMING_SNAKE_CASE__ : str=0 , SCREAMING_SNAKE_CASE__ : int=1 , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> Optional[int]: __lowerCamelCase = vocab_size __lowerCamelCase = d_model __lowerCamelCase = d_kv __lowerCamelCase = d_ff __lowerCamelCase = num_layers __lowerCamelCase = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry __lowerCamelCase = num_heads __lowerCamelCase = relative_attention_num_buckets __lowerCamelCase = relative_attention_max_distance __lowerCamelCase = dropout_rate __lowerCamelCase = layer_norm_epsilon __lowerCamelCase = initializer_factor __lowerCamelCase = feed_forward_proj __lowerCamelCase = use_cache __lowerCamelCase = self.feed_forward_proj.split('''-''' ) __lowerCamelCase = act_info[-1] __lowerCamelCase = act_info[0] == '''gated''' if len(SCREAMING_SNAKE_CASE__ ) > 1 and act_info[0] != "gated" or len(SCREAMING_SNAKE_CASE__ ) > 2: raise ValueError( f'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.''' '''Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ''' '''\'gated-gelu\' or \'relu\'''' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": __lowerCamelCase = '''gelu_new''' super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , is_encoder_decoder=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) class lowerCAmelCase__ ( __lowercase ): @property def __A ( self : List[Any] ) -> Mapping[str, Mapping[int, str]]: __lowerCamelCase = { '''input_ids''': {0: '''batch''', 1: '''encoder_sequence'''}, '''attention_mask''': {0: '''batch''', 1: '''encoder_sequence'''}, } if self.use_past: __lowerCamelCase = '''past_encoder_sequence + sequence''' __lowerCamelCase = {0: '''batch'''} __lowerCamelCase = {0: '''batch''', 1: '''past_decoder_sequence + sequence'''} else: __lowerCamelCase = {0: '''batch''', 1: '''decoder_sequence'''} __lowerCamelCase = {0: '''batch''', 1: '''decoder_sequence'''} if self.use_past: self.fill_with_past_key_values_(SCREAMING_SNAKE_CASE__ , direction='''inputs''' ) return common_inputs @property def __A ( self : int ) -> int: return 13
357
from functools import lru_cache def __magic_name__ ( __lowerCAmelCase : int ) -> set: __lowerCamelCase = 2 __lowerCamelCase = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(__lowerCAmelCase ) if n > 1: factors.add(__lowerCAmelCase ) return factors @lru_cache def __magic_name__ ( __lowerCAmelCase : int ) -> int: return len(unique_prime_factors(__lowerCAmelCase ) ) def __magic_name__ ( __lowerCAmelCase : list ) -> bool: return len(set(__lowerCAmelCase ) ) in (0, 1) def __magic_name__ ( __lowerCAmelCase : int ) -> list: __lowerCamelCase = 2 while True: # Increment each value of a generated range __lowerCamelCase = [base + i for i in range(__lowerCAmelCase )] # Run elements through out unique_prime_factors function # Append our target number to the end. __lowerCamelCase = [upf_len(__lowerCAmelCase ) for x in group] checker.append(__lowerCAmelCase ) # If all numbers in the list are equal, return the group variable. if equality(__lowerCAmelCase ): return group # Increment our base variable by 1 base += 1 def __magic_name__ ( __lowerCAmelCase : int = 4 ) -> int: __lowerCamelCase = run(__lowerCAmelCase ) return results[0] if len(__lowerCAmelCase ) else None if __name__ == "__main__": print(solution())
339
0
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Optional[int] ) -> Tuple: __lowerCamelCase = tempfile.mkdtemp() # fmt: off __lowerCamelCase = ['''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''lo''', '''l</w>''', '''w</w>''', '''r</w>''', '''t</w>''', '''low</w>''', '''er</w>''', '''lowest</w>''', '''newer</w>''', '''wider''', '''<unk>''', '''<|startoftext|>''', '''<|endoftext|>'''] # fmt: on __lowerCamelCase = dict(zip(SCREAMING_SNAKE_CASE__ , range(len(SCREAMING_SNAKE_CASE__ ) ) ) ) __lowerCamelCase = ['''#version: 0.2''', '''l o''', '''lo w</w>''', '''e r</w>''', ''''''] __lowerCamelCase = {'''unk_token''': '''<unk>'''} __lowerCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) __lowerCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE__ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = { '''do_resize''': True, '''size''': 20, '''do_center_crop''': True, '''crop_size''': 18, '''do_normalize''': True, '''image_mean''': [0.48145466, 0.4578275, 0.40821073], '''image_std''': [0.26862954, 0.26130258, 0.27577711], } __lowerCamelCase = os.path.join(self.tmpdirname , SCREAMING_SNAKE_CASE__ ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[Any] , **SCREAMING_SNAKE_CASE__ : List[str] ) -> str: return CLIPTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def __A ( self : List[Any] , **SCREAMING_SNAKE_CASE__ : List[str] ) -> Union[str, Any]: return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def __A ( self : Tuple , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Optional[int]: return CLIPImageProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def __A ( self : Tuple ) -> Tuple: shutil.rmtree(self.tmpdirname ) def __A ( self : str ) -> Dict: __lowerCamelCase = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] __lowerCamelCase = [Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def __A ( self : Optional[Any] ) -> List[Any]: __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = self.get_rust_tokenizer() __lowerCamelCase = self.get_image_processor() __lowerCamelCase = CLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) processor_slow.save_pretrained(self.tmpdirname ) __lowerCamelCase = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = CLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) processor_fast.save_pretrained(self.tmpdirname ) __lowerCamelCase = CLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor_fast.tokenizer , SCREAMING_SNAKE_CASE__ ) 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 , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor_fast.image_processor , SCREAMING_SNAKE_CASE__ ) def __A ( self : int ) -> Dict: __lowerCamelCase = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __lowerCamelCase = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __lowerCamelCase = self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) __lowerCamelCase = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , SCREAMING_SNAKE_CASE__ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def __A ( self : Any ) -> List[Any]: __lowerCamelCase = self.get_image_processor() __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = CLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.prepare_image_inputs() __lowerCamelCase = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='''np''' ) __lowerCamelCase = processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='''np''' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __A ( self : Tuple ) -> Tuple: __lowerCamelCase = self.get_image_processor() __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = CLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = '''lower newer''' __lowerCamelCase = processor(text=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = tokenizer(SCREAMING_SNAKE_CASE__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __A ( self : Dict ) -> Optional[int]: __lowerCamelCase = self.get_image_processor() __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = CLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = '''lower newer''' __lowerCamelCase = self.prepare_image_inputs() __lowerCamelCase = processor(text=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE__ ): processor() def __A ( self : Any ) -> List[str]: __lowerCamelCase = self.get_image_processor() __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = CLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __lowerCamelCase = processor.batch_decode(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : Any ) -> List[str]: __lowerCamelCase = self.get_image_processor() __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = CLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = '''lower newer''' __lowerCamelCase = self.prepare_image_inputs() __lowerCamelCase = processor(text=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
358
import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel class lowerCAmelCase__ : def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any]=99 , SCREAMING_SNAKE_CASE__ : List[Any]=13 , SCREAMING_SNAKE_CASE__ : Tuple=7 , SCREAMING_SNAKE_CASE__ : int=9 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Dict=False , SCREAMING_SNAKE_CASE__ : int=32 , SCREAMING_SNAKE_CASE__ : Tuple=5 , SCREAMING_SNAKE_CASE__ : List[str]=4 , SCREAMING_SNAKE_CASE__ : str=37 , SCREAMING_SNAKE_CASE__ : int=8 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.002 , SCREAMING_SNAKE_CASE__ : str=1 , SCREAMING_SNAKE_CASE__ : Tuple=0 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0 , SCREAMING_SNAKE_CASE__ : int=None , SCREAMING_SNAKE_CASE__ : Dict=None , ) -> Optional[Any]: __lowerCamelCase = parent __lowerCamelCase = batch_size __lowerCamelCase = encoder_seq_length __lowerCamelCase = decoder_seq_length # For common tests __lowerCamelCase = self.decoder_seq_length __lowerCamelCase = is_training __lowerCamelCase = use_attention_mask __lowerCamelCase = use_labels __lowerCamelCase = vocab_size __lowerCamelCase = hidden_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = d_ff __lowerCamelCase = relative_attention_num_buckets __lowerCamelCase = dropout_rate __lowerCamelCase = initializer_factor __lowerCamelCase = eos_token_id __lowerCamelCase = pad_token_id __lowerCamelCase = decoder_start_token_id __lowerCamelCase = None __lowerCamelCase = decoder_layers def __A ( self : Any ) -> Tuple: return TaConfig.from_pretrained('''google/umt5-base''' ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , ) -> Optional[int]: if attention_mask is None: __lowerCamelCase = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: __lowerCamelCase = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: __lowerCamelCase = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=SCREAMING_SNAKE_CASE__ ) if decoder_head_mask is None: __lowerCamelCase = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=SCREAMING_SNAKE_CASE__ ) if cross_attn_head_mask is None: __lowerCamelCase = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=SCREAMING_SNAKE_CASE__ ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } def __A ( self : List[Any] ) -> Tuple: __lowerCamelCase = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) __lowerCamelCase = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for NllbMoe the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input __lowerCamelCase = input_ids.clamp(self.pad_token_id + 1 ) __lowerCamelCase = decoder_input_ids.clamp(self.pad_token_id + 1 ) __lowerCamelCase = self.get_config() __lowerCamelCase = config.num_attention_heads __lowerCamelCase = self.prepare_inputs_dict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return config, input_dict def __A ( self : Tuple ) -> List[str]: __lowerCamelCase , __lowerCamelCase = self.prepare_config_and_inputs() return config, inputs_dict def __A ( self : Optional[Any] ) -> Any: return TaConfig( vocab_size=1_66 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def __A ( self : List[Any] ) -> Any: return TaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> int: __lowerCamelCase = UMTaModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __lowerCamelCase = model( input_ids=SCREAMING_SNAKE_CASE__ , decoder_input_ids=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , decoder_attention_mask=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = model(input_ids=SCREAMING_SNAKE_CASE__ , decoder_input_ids=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = result.last_hidden_state __lowerCamelCase = result.past_key_values __lowerCamelCase = result.encoder_last_hidden_state self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) ) self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) ) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , config.num_layers ) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0] ) , 4 ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple , ) -> Dict: __lowerCamelCase = UMTaModel(config=SCREAMING_SNAKE_CASE__ ).get_decoder().to(SCREAMING_SNAKE_CASE__ ).eval() # first forward pass __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ , use_cache=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ , use_cache=SCREAMING_SNAKE_CASE__ ) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE__ ) == len(SCREAMING_SNAKE_CASE__ ) ) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE__ ) == len(SCREAMING_SNAKE_CASE__ ) + 1 ) __lowerCamelCase , __lowerCamelCase = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids __lowerCamelCase = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and __lowerCamelCase = torch.cat([input_ids, next_tokens] , dim=-1 ) __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ )['''last_hidden_state'''] __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ , past_key_values=SCREAMING_SNAKE_CASE__ )['''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(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple , ) -> Optional[int]: __lowerCamelCase = UMTaModel(config=SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ ).half().eval() __lowerCamelCase = model(**SCREAMING_SNAKE_CASE__ )['''last_hidden_state'''] self.parent.assertFalse(torch.isnan(SCREAMING_SNAKE_CASE__ ).any().item() ) @require_torch class lowerCAmelCase__ ( __lowercase , __lowercase , __lowercase , unittest.TestCase ): a__ : List[Any] = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) a__ : Union[str, Any] = (UMTaForConditionalGeneration,) if is_torch_available() else () a__ : Tuple = ( { """conversational""": UMTaForConditionalGeneration, """feature-extraction""": UMTaModel, """summarization""": UMTaForConditionalGeneration, """text2text-generation""": UMTaForConditionalGeneration, """translation""": UMTaForConditionalGeneration, """question-answering""": UMTaForQuestionAnswering, } if is_torch_available() else {} ) a__ : int = True a__ : int = False a__ : Tuple = False a__ : Optional[int] = True a__ : Optional[int] = True # The small UMT5 model needs higher percentages for CPU/MP tests a__ : Tuple = [0.8, 0.9] def __A ( self : Tuple ) -> Tuple: __lowerCamelCase = UMTaModelTester(self ) @unittest.skip('''Test has a segmentation fault on torch 1.8.0''' ) def __A ( self : List[str] ) -> Union[str, Any]: __lowerCamelCase = self.model_tester.prepare_config_and_inputs() __lowerCamelCase = UMTaModel(config_and_inputs[0] ).to(SCREAMING_SNAKE_CASE__ ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( SCREAMING_SNAKE_CASE__ , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , f'''{tmpdirname}/t5_test.onnx''' , export_params=SCREAMING_SNAKE_CASE__ , opset_version=9 , input_names=['''input_ids''', '''decoder_input_ids'''] , ) @unittest.skipIf(torch_device == '''cpu''' , '''Cant do half precision''' ) def __A ( self : Union[str, Any] ) -> Any: __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*SCREAMING_SNAKE_CASE__ ) def __A ( self : Any ) -> Any: __lowerCamelCase = ['''encoder_attentions''', '''decoder_attentions''', '''cross_attentions'''] __lowerCamelCase = self.model_tester.prepare_config_and_inputs() __lowerCamelCase = config_and_inputs[0] __lowerCamelCase = UMTaForConditionalGeneration(SCREAMING_SNAKE_CASE__ ).eval() model.to(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = { '''head_mask''': torch.zeros(config.num_layers , config.num_heads , device=SCREAMING_SNAKE_CASE__ ), '''decoder_head_mask''': torch.zeros(config.num_decoder_layers , config.num_heads , device=SCREAMING_SNAKE_CASE__ ), '''cross_attn_head_mask''': torch.zeros(config.num_decoder_layers , config.num_heads , device=SCREAMING_SNAKE_CASE__ ), } for attn_name, (name, mask) in zip(SCREAMING_SNAKE_CASE__ , head_masking.items() ): __lowerCamelCase = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": __lowerCamelCase = torch.ones( config.num_decoder_layers , config.num_heads , device=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model.generate( config_and_inputs[1]['''input_ids'''] , num_beams=1 , max_length=3 , output_attentions=SCREAMING_SNAKE_CASE__ , return_dict_in_generate=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) # We check the state of decoder_attentions and cross_attentions just from the last step __lowerCamelCase = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 ) @unittest.skip('''Does not work on the tiny model as we keep hitting edge cases.''' ) def __A ( self : Tuple ) -> Optional[Any]: pass @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): @slow @unittest.skip( '''Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged''' ) def __A ( self : int ) -> Optional[Any]: __lowerCamelCase = UMTaForConditionalGeneration.from_pretrained('''google/umt5-small''' , return_dict=SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = AutoTokenizer.from_pretrained('''google/umt5-small''' , use_fast=SCREAMING_SNAKE_CASE__ , legacy=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = [ '''Bonjour monsieur <extra_id_0> bien <extra_id_1>.''', '''No se como puedo <extra_id_0>.''', '''This is the reason why we <extra_id_0> them.''', '''The <extra_id_0> walks in <extra_id_1>, seats''', '''A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.''', ] __lowerCamelCase = tokenizer(SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , padding=SCREAMING_SNAKE_CASE__ ).input_ids # fmt: off __lowerCamelCase = torch.tensor( [ [ 3_85_30, 21_07_03, 25_62_99, 14_10, 25_62_98, 2_74, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 8_26, 3_21, 6_71, 2_59_22, 25_62_99, 2_74, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 14_60, 3_39, 3_12, 1_90_14, 1_06_20, 7_58, 25_62_99, 23_55,2_74, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 5_17, 25_62_99, 1_48_69, 2_81, 3_01, 25_62_98, 2_75, 11_99_83,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 3_20, 25_62_99, 1_48_69, 2_81, 22_34, 2_89, 22_75, 3_33,6_13_91, 2_89, 25_62_98, 5_43, 25_62_97, 16_87_14, 3_29, 25_62_96,2_74, 1], ] ) # fmt: on torch.testing.assert_allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model.generate(input_ids.to(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = [ '''<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>''', '''<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', ] __lowerCamelCase = tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
339
0
SCREAMING_SNAKE_CASE__ : List[Any] = "0.18.2" from .configuration_utils import ConfigMixin from .utils import ( OptionalDependencyNotAvailable, is_flax_available, is_inflect_available, is_invisible_watermark_available, is_k_diffusion_available, is_k_diffusion_version, is_librosa_available, is_note_seq_available, is_onnx_available, is_scipy_available, is_torch_available, is_torchsde_available, is_transformers_available, is_transformers_version, is_unidecode_available, logging, ) try: if not is_onnx_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_onnx_objects import * # noqa F403 else: from .pipelines import OnnxRuntimeModel try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_pt_objects import * # noqa F403 else: from .models import ( AutoencoderKL, ControlNetModel, ModelMixin, PriorTransformer, TaFilmDecoder, TransformeraDModel, UNetaDModel, UNetaDConditionModel, UNetaDModel, UNetaDConditionModel, VQModel, ) from .optimization import ( get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, get_scheduler, ) from .pipelines import ( AudioPipelineOutput, ConsistencyModelPipeline, DanceDiffusionPipeline, DDIMPipeline, DDPMPipeline, DiffusionPipeline, DiTPipeline, ImagePipelineOutput, KarrasVePipeline, LDMPipeline, LDMSuperResolutionPipeline, PNDMPipeline, RePaintPipeline, ScoreSdeVePipeline, ) from .schedulers import ( CMStochasticIterativeScheduler, DDIMInverseScheduler, DDIMParallelScheduler, DDIMScheduler, DDPMParallelScheduler, DDPMScheduler, DEISMultistepScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, HeunDiscreteScheduler, IPNDMScheduler, KarrasVeScheduler, KDPMaAncestralDiscreteScheduler, KDPMaDiscreteScheduler, PNDMScheduler, RePaintScheduler, SchedulerMixin, ScoreSdeVeScheduler, UnCLIPScheduler, UniPCMultistepScheduler, VQDiffusionScheduler, ) from .training_utils import EMAModel try: if not (is_torch_available() and is_scipy_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_scipy_objects import * # noqa F403 else: from .schedulers import LMSDiscreteScheduler try: if not (is_torch_available() and is_torchsde_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_torchsde_objects import * # noqa F403 else: from .schedulers import DPMSolverSDEScheduler try: if not (is_torch_available() and is_transformers_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipelines import ( AltDiffusionImgaImgPipeline, AltDiffusionPipeline, AudioLDMPipeline, CycleDiffusionPipeline, IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ImageTextPipelineOutput, KandinskyImgaImgPipeline, KandinskyInpaintPipeline, KandinskyPipeline, KandinskyPriorPipeline, KandinskyVaaControlnetImgaImgPipeline, KandinskyVaaControlnetPipeline, KandinskyVaaImgaImgPipeline, KandinskyVaaInpaintPipeline, KandinskyVaaPipeline, KandinskyVaaPriorEmbaEmbPipeline, KandinskyVaaPriorPipeline, LDMTextToImagePipeline, PaintByExamplePipeline, SemanticStableDiffusionPipeline, ShapEImgaImgPipeline, ShapEPipeline, StableDiffusionAttendAndExcitePipeline, StableDiffusionControlNetImgaImgPipeline, StableDiffusionControlNetInpaintPipeline, StableDiffusionControlNetPipeline, StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionImageVariationPipeline, StableDiffusionImgaImgPipeline, StableDiffusionInpaintPipeline, StableDiffusionInpaintPipelineLegacy, StableDiffusionInstructPixaPixPipeline, StableDiffusionLatentUpscalePipeline, StableDiffusionLDMaDPipeline, StableDiffusionModelEditingPipeline, StableDiffusionPanoramaPipeline, StableDiffusionParadigmsPipeline, StableDiffusionPipeline, StableDiffusionPipelineSafe, StableDiffusionPixaPixZeroPipeline, StableDiffusionSAGPipeline, StableDiffusionUpscalePipeline, StableUnCLIPImgaImgPipeline, StableUnCLIPPipeline, TextToVideoSDPipeline, TextToVideoZeroPipeline, UnCLIPImageVariationPipeline, UnCLIPPipeline, UniDiffuserModel, UniDiffuserPipeline, UniDiffuserTextDecoder, VersatileDiffusionDualGuidedPipeline, VersatileDiffusionImageVariationPipeline, VersatileDiffusionPipeline, VersatileDiffusionTextToImagePipeline, VideoToVideoSDPipeline, VQDiffusionPipeline, ) try: if not (is_torch_available() and is_transformers_available() and is_invisible_watermark_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_invisible_watermark_objects import * # noqa F403 else: from .pipelines import StableDiffusionXLImgaImgPipeline, StableDiffusionXLPipeline try: if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipelines import StableDiffusionKDiffusionPipeline try: if not (is_torch_available() and is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_onnx_objects import * # noqa F403 else: from .pipelines import ( OnnxStableDiffusionImgaImgPipeline, OnnxStableDiffusionInpaintPipeline, OnnxStableDiffusionInpaintPipelineLegacy, OnnxStableDiffusionPipeline, OnnxStableDiffusionUpscalePipeline, StableDiffusionOnnxPipeline, ) try: if not (is_torch_available() and is_librosa_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_librosa_objects import * # noqa F403 else: from .pipelines import AudioDiffusionPipeline, Mel try: if not (is_transformers_available() and is_torch_available() and is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403 else: from .pipelines import SpectrogramDiffusionPipeline try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_flax_objects import * # noqa F403 else: from .models.controlnet_flax import FlaxControlNetModel from .models.modeling_flax_utils import FlaxModelMixin from .models.unet_ad_condition_flax import FlaxUNetaDConditionModel from .models.vae_flax import FlaxAutoencoderKL from .pipelines import FlaxDiffusionPipeline from .schedulers import ( FlaxDDIMScheduler, FlaxDDPMScheduler, FlaxDPMSolverMultistepScheduler, FlaxKarrasVeScheduler, FlaxLMSDiscreteScheduler, FlaxPNDMScheduler, FlaxSchedulerMixin, FlaxScoreSdeVeScheduler, ) try: if not (is_flax_available() and is_transformers_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_flax_and_transformers_objects import * # noqa F403 else: from .pipelines import ( FlaxStableDiffusionControlNetPipeline, FlaxStableDiffusionImgaImgPipeline, FlaxStableDiffusionInpaintPipeline, FlaxStableDiffusionPipeline, ) try: if not (is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_note_seq_objects import * # noqa F403 else: from .pipelines import MidiProcessor
359
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : Union[str, Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Tuple = { "s-JoL/Open-Llama-V1": "https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/config.json", } class lowerCAmelCase__ ( __lowercase ): a__ : Union[str, Any] = """open-llama""" def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Any=10_00_00 , SCREAMING_SNAKE_CASE__ : Any=40_96 , SCREAMING_SNAKE_CASE__ : Any=1_10_08 , SCREAMING_SNAKE_CASE__ : Tuple=32 , SCREAMING_SNAKE_CASE__ : str=32 , SCREAMING_SNAKE_CASE__ : Any="silu" , SCREAMING_SNAKE_CASE__ : Union[str, Any]=20_48 , SCREAMING_SNAKE_CASE__ : List[str]=0.02 , SCREAMING_SNAKE_CASE__ : List[Any]=1e-6 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Dict=0 , SCREAMING_SNAKE_CASE__ : Tuple=1 , SCREAMING_SNAKE_CASE__ : str=2 , SCREAMING_SNAKE_CASE__ : List[Any]=False , SCREAMING_SNAKE_CASE__ : Any=True , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Any=0.1 , SCREAMING_SNAKE_CASE__ : Any=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : List[str]=None , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> Dict: __lowerCamelCase = vocab_size __lowerCamelCase = max_position_embeddings __lowerCamelCase = hidden_size __lowerCamelCase = intermediate_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = hidden_act __lowerCamelCase = initializer_range __lowerCamelCase = rms_norm_eps __lowerCamelCase = use_cache __lowerCamelCase = kwargs.pop( '''use_memorry_efficient_attention''' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = hidden_dropout_prob __lowerCamelCase = attention_dropout_prob __lowerCamelCase = use_stable_embedding __lowerCamelCase = shared_input_output_embedding __lowerCamelCase = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , tie_word_embeddings=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) def __A ( self : Dict ) -> Optional[int]: if self.rope_scaling is None: return if not isinstance(self.rope_scaling , SCREAMING_SNAKE_CASE__ ) or len(self.rope_scaling ) != 2: raise ValueError( '''`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ''' f'''got {self.rope_scaling}''' ) __lowerCamelCase = self.rope_scaling.get('''type''' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.rope_scaling.get('''factor''' , SCREAMING_SNAKE_CASE__ ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' ) if rope_scaling_factor is None or not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or rope_scaling_factor <= 1.0: raise ValueError(f'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
339
0
import tempfile import unittest import numpy as np import transformers from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax import jax.numpy as jnp from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel if is_torch_available(): import torch class lowerCAmelCase__ : def __init__( self : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[int]=14 , SCREAMING_SNAKE_CASE__ : Any=7 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Any=False , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=99 , SCREAMING_SNAKE_CASE__ : Dict=32 , SCREAMING_SNAKE_CASE__ : Optional[Any]=4 , SCREAMING_SNAKE_CASE__ : Optional[Any]=4 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=4 , SCREAMING_SNAKE_CASE__ : str=37 , SCREAMING_SNAKE_CASE__ : Optional[int]="gelu" , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.1 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : List[Any]=5_12 , SCREAMING_SNAKE_CASE__ : Any=0.02 , ) -> Optional[int]: __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 = rotary_dim __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 = initializer_range __lowerCamelCase = None __lowerCamelCase = vocab_size - 1 __lowerCamelCase = vocab_size - 1 __lowerCamelCase = vocab_size - 1 def __A ( self : int ) -> Tuple: __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 = GPTJConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , use_cache=SCREAMING_SNAKE_CASE__ , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , rotary_dim=self.rotary_dim , ) return (config, input_ids, input_mask) def __A ( self : List[str] ) -> Any: __lowerCamelCase = self.prepare_config_and_inputs() __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = config_and_inputs __lowerCamelCase = {'''input_ids''': input_ids, '''attention_mask''': attention_mask} return config, inputs_dict def __A ( self : Any , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> int: __lowerCamelCase = 20 __lowerCamelCase = model_class_name(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model.init_cache(input_ids.shape[0] , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = jnp.ones((input_ids.shape[0], max_decoder_length) , dtype='''i4''' ) __lowerCamelCase = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) __lowerCamelCase = model( input_ids[:, :-1] , attention_mask=SCREAMING_SNAKE_CASE__ , past_key_values=SCREAMING_SNAKE_CASE__ , position_ids=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='''i4''' ) __lowerCamelCase = model( input_ids[:, -1:] , attention_mask=SCREAMING_SNAKE_CASE__ , past_key_values=outputs_cache.past_key_values , position_ids=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=f'''Max diff is {diff}''' ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[int]: __lowerCamelCase = 20 __lowerCamelCase = model_class_name(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = jnp.concatenate( [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]) )] , axis=-1 , ) __lowerCamelCase = model.init_cache(input_ids.shape[0] , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) __lowerCamelCase = model( input_ids[:, :-1] , attention_mask=SCREAMING_SNAKE_CASE__ , past_key_values=SCREAMING_SNAKE_CASE__ , position_ids=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='''i4''' ) __lowerCamelCase = model( input_ids[:, -1:] , past_key_values=outputs_cache.past_key_values , attention_mask=SCREAMING_SNAKE_CASE__ , position_ids=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=f'''Max diff is {diff}''' ) @require_flax class lowerCAmelCase__ ( __lowercase , __lowercase , unittest.TestCase ): a__ : Any = (FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else () a__ : Union[str, Any] = (FlaxGPTJForCausalLM,) if is_flax_available() else () def __A ( self : Optional[Any] ) -> Tuple: __lowerCamelCase = FlaxGPTJModelTester(self ) def __A ( self : Union[str, Any] ) -> Any: for model_class_name in self.all_model_classes: __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : List[str] ) -> Optional[Any]: for model_class_name in self.all_model_classes: __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward_with_attn_mask( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @tooslow def __A ( self : List[Any] ) -> Optional[Any]: __lowerCamelCase = GPTaTokenizer.from_pretrained('''gpt2''' , pad_token='''<|endoftext|>''' , padding_side='''left''' ) __lowerCamelCase = tokenizer(['''Hello this is a long string''', '''Hey'''] , return_tensors='''np''' , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = FlaxGPTJForCausalLM.from_pretrained('''EleutherAI/gpt-j-6B''' ) __lowerCamelCase = False __lowerCamelCase = model.config.eos_token_id __lowerCamelCase = jax.jit(model.generate ) __lowerCamelCase = jit_generate( inputs['''input_ids'''] , attention_mask=inputs['''attention_mask'''] , pad_token_id=tokenizer.pad_token_id ).sequences __lowerCamelCase = tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = [ '''Hello this is a long string of text.\n\nI\'m trying to get the text of the''', '''Hey, I\'m a little late to the party. I\'m going to''', ] self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @is_pt_flax_cross_test def __A ( self : Dict ) -> List[str]: __lowerCamelCase , __lowerCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs __lowerCamelCase = self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class __lowerCamelCase = model_class.__name__[4:] # Skip the "Flax" at the beginning __lowerCamelCase = getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase , __lowerCamelCase = pt_inputs['''input_ids'''].shape __lowerCamelCase = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = 0 __lowerCamelCase = 1 __lowerCamelCase = 0 __lowerCamelCase = 1 __lowerCamelCase = pt_model_class(SCREAMING_SNAKE_CASE__ ).eval() __lowerCamelCase = model_class(SCREAMING_SNAKE_CASE__ , dtype=jnp.floataa ) __lowerCamelCase = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = fx_state with torch.no_grad(): __lowerCamelCase = pt_model(**SCREAMING_SNAKE_CASE__ ).to_tuple() __lowerCamelCase = fx_model(**SCREAMING_SNAKE_CASE__ ).to_tuple() self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) , '''Output lengths differ between Flax and PyTorch''' ) for fx_output, pt_output in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4e-2 ) with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model_class.from_pretrained(SCREAMING_SNAKE_CASE__ , from_pt=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = fx_model_loaded(**SCREAMING_SNAKE_CASE__ ).to_tuple() self.assertEqual( len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) , '''Output lengths differ between Flax and PyTorch''' ) for fx_output_loaded, pt_output in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assert_almost_equals(fx_output_loaded[:, -1] , pt_output[:, -1].numpy() , 4e-2 ) @is_pt_flax_cross_test def __A ( self : str ) -> Optional[Any]: __lowerCamelCase , __lowerCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs __lowerCamelCase = self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class __lowerCamelCase = model_class.__name__[4:] # Skip the "Flax" at the beginning __lowerCamelCase = getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pt_model_class(SCREAMING_SNAKE_CASE__ ).eval() __lowerCamelCase = model_class(SCREAMING_SNAKE_CASE__ , dtype=jnp.floataa ) __lowerCamelCase = load_flax_weights_in_pytorch_model(SCREAMING_SNAKE_CASE__ , fx_model.params ) __lowerCamelCase , __lowerCamelCase = pt_inputs['''input_ids'''].shape __lowerCamelCase = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = 0 __lowerCamelCase = 1 __lowerCamelCase = 0 __lowerCamelCase = 1 # make sure weights are tied in PyTorch pt_model.tie_weights() with torch.no_grad(): __lowerCamelCase = pt_model(**SCREAMING_SNAKE_CASE__ ).to_tuple() __lowerCamelCase = fx_model(**SCREAMING_SNAKE_CASE__ ).to_tuple() self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) , '''Output lengths differ between Flax and PyTorch''' ) for fx_output, pt_output in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4e-2 ) with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pt_model_class.from_pretrained(SCREAMING_SNAKE_CASE__ , from_flax=SCREAMING_SNAKE_CASE__ ) with torch.no_grad(): __lowerCamelCase = pt_model_loaded(**SCREAMING_SNAKE_CASE__ ).to_tuple() self.assertEqual( len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) , '''Output lengths differ between Flax and PyTorch''' ) for fx_output, pt_output in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4e-2 ) @tooslow def __A ( self : Tuple ) -> Union[str, Any]: for model_class_name in self.all_model_classes: __lowerCamelCase = model_class_name.from_pretrained('''EleutherAI/gpt-j-6B''' ) __lowerCamelCase = model(np.ones((1, 1) ) ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ )
360
from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar SCREAMING_SNAKE_CASE__ : Any = TypeVar("KEY") SCREAMING_SNAKE_CASE__ : Dict = TypeVar("VAL") @dataclass(frozen=__lowercase , slots=__lowercase ) class lowerCAmelCase__ ( Generic[KEY, VAL] ): a__ : KEY a__ : VAL class lowerCAmelCase__ ( _Item ): def __init__( self : str ) -> None: super().__init__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __bool__( self : Tuple ) -> bool: return False SCREAMING_SNAKE_CASE__ : List[Any] = _DeletedItem() class lowerCAmelCase__ ( MutableMapping[KEY, VAL] ): def __init__( self : int , SCREAMING_SNAKE_CASE__ : int = 8 , SCREAMING_SNAKE_CASE__ : float = 0.75 ) -> None: __lowerCamelCase = initial_block_size __lowerCamelCase = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 __lowerCamelCase = capacity_factor __lowerCamelCase = 0 def __A ( self : Any , SCREAMING_SNAKE_CASE__ : KEY ) -> int: return hash(SCREAMING_SNAKE_CASE__ ) % len(self._buckets ) def __A ( self : Any , SCREAMING_SNAKE_CASE__ : int ) -> int: return (ind + 1) % len(self._buckets ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : KEY , SCREAMING_SNAKE_CASE__ : VAL ) -> bool: __lowerCamelCase = self._buckets[ind] if not stored: __lowerCamelCase = _Item(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self._len += 1 return True elif stored.key == key: __lowerCamelCase = _Item(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return True else: return False def __A ( self : Any ) -> bool: __lowerCamelCase = len(self._buckets ) * self._capacity_factor return len(self ) >= int(SCREAMING_SNAKE_CASE__ ) def __A ( self : List[Any] ) -> bool: if len(self._buckets ) <= self._initial_block_size: return False __lowerCamelCase = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def __A ( self : int , SCREAMING_SNAKE_CASE__ : int ) -> None: __lowerCamelCase = self._buckets __lowerCamelCase = [None] * new_size __lowerCamelCase = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def __A ( self : str ) -> None: self._resize(len(self._buckets ) * 2 ) def __A ( self : Dict ) -> None: self._resize(len(self._buckets ) // 2 ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : KEY ) -> Iterator[int]: __lowerCamelCase = self._get_bucket_index(SCREAMING_SNAKE_CASE__ ) for _ in range(len(self._buckets ) ): yield ind __lowerCamelCase = self._get_next_ind(SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : KEY , SCREAMING_SNAKE_CASE__ : VAL ) -> None: for ind in self._iterate_buckets(SCREAMING_SNAKE_CASE__ ): if self._try_set(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): break def __setitem__( self : Tuple , SCREAMING_SNAKE_CASE__ : KEY , SCREAMING_SNAKE_CASE__ : VAL ) -> None: if self._is_full(): self._size_up() self._add_item(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __delitem__( self : List[Any] , SCREAMING_SNAKE_CASE__ : KEY ) -> None: for ind in self._iterate_buckets(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = self._buckets[ind] if item is None: raise KeyError(SCREAMING_SNAKE_CASE__ ) if item is _deleted: continue if item.key == key: __lowerCamelCase = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : KEY ) -> VAL: for ind in self._iterate_buckets(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(SCREAMING_SNAKE_CASE__ ) def __len__( self : int ) -> int: return self._len def __iter__( self : Tuple ) -> Iterator[KEY]: yield from (item.key for item in self._buckets if item) def __repr__( self : Optional[Any] ) -> str: __lowerCamelCase = ''' ,'''.join( f'''{item.key}: {item.val}''' for item in self._buckets if item ) return f'''HashMap({val_string})'''
339
0
from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class lowerCAmelCase__ ( __lowercase , __lowercase ): @register_to_config def __init__( self : str , SCREAMING_SNAKE_CASE__ : int = 7_68 , ) -> Optional[Any]: super().__init__() __lowerCamelCase = nn.Parameter(torch.zeros(1 , SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = nn.Parameter(torch.ones(1 , SCREAMING_SNAKE_CASE__ ) ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Union[str, torch.device]] = None , SCREAMING_SNAKE_CASE__ : Optional[torch.dtype] = None , ) -> Dict: __lowerCamelCase = nn.Parameter(self.mean.to(SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = nn.Parameter(self.std.to(SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ ) ) return self def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] ) -> int: __lowerCamelCase = (embeds - self.mean) * 1.0 / self.std return embeds def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: __lowerCamelCase = (embeds * self.std) + self.mean return embeds
361
from datetime import datetime as dt import os from github import Github SCREAMING_SNAKE_CASE__ : Any = [ "good first issue", "good second issue", "good difficult issue", "feature request", "new model", "wip", ] def __magic_name__ ( ) -> Any: __lowerCamelCase = Github(os.environ['''GITHUB_TOKEN'''] ) __lowerCamelCase = g.get_repo('''huggingface/transformers''' ) __lowerCamelCase = repo.get_issues(state='''open''' ) for issue in open_issues: __lowerCamelCase = sorted([comment for comment in issue.get_comments()] , key=lambda __lowerCAmelCase : i.created_at , reverse=__lowerCAmelCase ) __lowerCamelCase = comments[0] if len(__lowerCAmelCase ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # print(f"Would close issue {issue.number} since it has been 7 days of inactivity since bot mention.") issue.edit(state='''closed''' ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # print(f"Would add stale comment to {issue.number}") issue.create_comment( '''This issue has been automatically marked as stale because it has not had ''' '''recent activity. If you think this still needs to be addressed ''' '''please comment on this thread.\n\nPlease note that issues that do not follow the ''' '''[contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) ''' '''are likely to be ignored.''' ) if __name__ == "__main__": main()
339
0
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : int ) -> Any: __lowerCamelCase = inspect.getfile(accelerate.test_utils ) __lowerCamelCase = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_script.py'''] ) __lowerCamelCase = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_distributed_data_loop.py'''] ) __lowerCamelCase = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_ops.py'''] ) @require_multi_gpu def __A ( self : Tuple ) -> Dict: print(f'''Found {torch.cuda.device_count()} devices.''' ) __lowerCamelCase = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(SCREAMING_SNAKE_CASE__ , env=os.environ.copy() ) @require_multi_gpu def __A ( self : Union[str, Any] ) -> str: print(f'''Found {torch.cuda.device_count()} devices.''' ) __lowerCamelCase = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', self.operation_file_path] print(f'''Command: {cmd}''' ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(SCREAMING_SNAKE_CASE__ , env=os.environ.copy() ) @require_multi_gpu def __A ( self : Optional[int] ) -> Optional[Any]: __lowerCamelCase = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(SCREAMING_SNAKE_CASE__ , env=os.environ.copy() ) @require_multi_gpu def __A ( self : List[Any] ) -> Any: print(f'''Found {torch.cuda.device_count()} devices, using 2 devices only''' ) __lowerCamelCase = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices='''0,1''' ): execute_subprocess_async(SCREAMING_SNAKE_CASE__ , env=os.environ.copy() ) if __name__ == "__main__": SCREAMING_SNAKE_CASE : int = Accelerator() SCREAMING_SNAKE_CASE : Dict = (accelerator.state.process_index + 2, 10) SCREAMING_SNAKE_CASE : Optional[int] = torch.randint(0, 10, shape).to(accelerator.device) SCREAMING_SNAKE_CASE : int = "" SCREAMING_SNAKE_CASE : Dict = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." SCREAMING_SNAKE_CASE : int = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." SCREAMING_SNAKE_CASE : Optional[int] = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
362
def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int ) -> str: if a < 0 or b < 0: raise ValueError('''the value of both inputs must be positive''' ) __lowerCamelCase = str(bin(__lowerCAmelCase ) )[2:] # remove the leading "0b" __lowerCamelCase = str(bin(__lowerCAmelCase ) )[2:] # remove the leading "0b" __lowerCamelCase = max(len(__lowerCAmelCase ) , len(__lowerCAmelCase ) ) return "0b" + "".join( str(int(char_a == '''1''' and char_b == '''1''' ) ) for char_a, char_b in zip(a_binary.zfill(__lowerCAmelCase ) , b_binary.zfill(__lowerCAmelCase ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
339
0
import unittest import numpy as np import torch from diffusers import ScoreSdeVePipeline, ScoreSdeVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class lowerCAmelCase__ ( unittest.TestCase ): @property def __A ( self : List[Any] ) -> Optional[Any]: torch.manual_seed(0 ) __lowerCamelCase = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) return model def __A ( self : Optional[int] ) -> Optional[Any]: __lowerCamelCase = self.dummy_uncond_unet __lowerCamelCase = ScoreSdeVeScheduler() __lowerCamelCase = ScoreSdeVePipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) sde_ve.to(SCREAMING_SNAKE_CASE__ ) sde_ve.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = torch.manual_seed(0 ) __lowerCamelCase = sde_ve(num_inference_steps=2 , output_type='''numpy''' , generator=SCREAMING_SNAKE_CASE__ ).images __lowerCamelCase = torch.manual_seed(0 ) __lowerCamelCase = sde_ve(num_inference_steps=2 , output_type='''numpy''' , generator=SCREAMING_SNAKE_CASE__ , return_dict=SCREAMING_SNAKE_CASE__ )[ 0 ] __lowerCamelCase = image[0, -3:, -3:, -1] __lowerCamelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __lowerCamelCase = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Tuple ) -> str: __lowerCamelCase = '''google/ncsnpp-church-256''' __lowerCamelCase = UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = ScoreSdeVeScheduler.from_pretrained(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = ScoreSdeVePipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) sde_ve.to(SCREAMING_SNAKE_CASE__ ) sde_ve.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = torch.manual_seed(0 ) __lowerCamelCase = sde_ve(num_inference_steps=10 , output_type='''numpy''' , generator=SCREAMING_SNAKE_CASE__ ).images __lowerCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 2_56, 2_56, 3) __lowerCamelCase = np.array([0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
363
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPSegProcessor, ViTImageProcessor @require_vision class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : List[str] ) -> Dict: __lowerCamelCase = tempfile.mkdtemp() # fmt: off __lowerCamelCase = ['''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''lo''', '''l</w>''', '''w</w>''', '''r</w>''', '''t</w>''', '''low</w>''', '''er</w>''', '''lowest</w>''', '''newer</w>''', '''wider''', '''<unk>''', '''<|startoftext|>''', '''<|endoftext|>'''] # fmt: on __lowerCamelCase = dict(zip(SCREAMING_SNAKE_CASE__ , range(len(SCREAMING_SNAKE_CASE__ ) ) ) ) __lowerCamelCase = ['''#version: 0.2''', '''l o''', '''lo w</w>''', '''e r</w>''', ''''''] __lowerCamelCase = {'''unk_token''': '''<unk>'''} __lowerCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) __lowerCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE__ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = { '''do_resize''': True, '''size''': 20, '''do_center_crop''': True, '''crop_size''': 18, '''do_normalize''': True, '''image_mean''': [0.48145466, 0.4578275, 0.40821073], '''image_std''': [0.26862954, 0.26130258, 0.27577711], } __lowerCamelCase = os.path.join(self.tmpdirname , SCREAMING_SNAKE_CASE__ ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : int , **SCREAMING_SNAKE_CASE__ : int ) -> Any: return CLIPTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def __A ( self : Dict , **SCREAMING_SNAKE_CASE__ : Dict ) -> Union[str, Any]: return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[int] , **SCREAMING_SNAKE_CASE__ : Any ) -> List[Any]: return ViTImageProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def __A ( self : Dict ) -> Dict: shutil.rmtree(self.tmpdirname ) def __A ( self : str ) -> Any: __lowerCamelCase = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] __lowerCamelCase = [Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def __A ( self : List[Any] ) -> List[str]: __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = self.get_rust_tokenizer() __lowerCamelCase = self.get_image_processor() __lowerCamelCase = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) processor_slow.save_pretrained(self.tmpdirname ) __lowerCamelCase = CLIPSegProcessor.from_pretrained(self.tmpdirname , use_fast=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) processor_fast.save_pretrained(self.tmpdirname ) __lowerCamelCase = 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 , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor_fast.tokenizer , SCREAMING_SNAKE_CASE__ ) 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 , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor_fast.image_processor , SCREAMING_SNAKE_CASE__ ) def __A ( self : Union[str, Any] ) -> int: __lowerCamelCase = CLIPSegProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __lowerCamelCase = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __lowerCamelCase = self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) __lowerCamelCase = CLIPSegProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , SCREAMING_SNAKE_CASE__ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[Any] ) -> Union[str, Any]: __lowerCamelCase = self.get_image_processor() __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.prepare_image_inputs() __lowerCamelCase = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='''np''' ) __lowerCamelCase = processor(images=SCREAMING_SNAKE_CASE__ , 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 __A ( self : List[Any] ) -> Optional[int]: __lowerCamelCase = self.get_image_processor() __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = '''lower newer''' __lowerCamelCase = processor(text=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = tokenizer(SCREAMING_SNAKE_CASE__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __A ( self : List[Any] ) -> Any: __lowerCamelCase = self.get_image_processor() __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = '''lower newer''' __lowerCamelCase = self.prepare_image_inputs() __lowerCamelCase = processor(text=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE__ ): processor() def __A ( self : Optional[Any] ) -> List[str]: __lowerCamelCase = self.get_image_processor() __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.prepare_image_inputs() __lowerCamelCase = self.prepare_image_inputs() __lowerCamelCase = processor(images=SCREAMING_SNAKE_CASE__ , visual_prompt=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , ['''pixel_values''', '''conditional_pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE__ ): processor() def __A ( self : List[Any] ) -> Any: __lowerCamelCase = self.get_image_processor() __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __lowerCamelCase = processor.batch_decode(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
339
0
# 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 SCREAMING_SNAKE_CASE__ : List[Any] = open # noqa: we just need to have a builtin inside this module to test it properly
364
from __future__ import annotations def __magic_name__ ( __lowerCAmelCase : list , __lowerCAmelCase : int | None = None , __lowerCAmelCase : int | None = None ) -> None: if start is None: __lowerCamelCase = 0 if end is None: __lowerCamelCase = len(__lowerCAmelCase ) - 1 if start >= end: return __lowerCamelCase = (start + end) // 2 slowsort(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) slowsort(__lowerCAmelCase , mid + 1 , __lowerCAmelCase ) if sequence[end] < sequence[mid]: __lowerCamelCase , __lowerCamelCase = sequence[mid], sequence[end] slowsort(__lowerCAmelCase , __lowerCAmelCase , end - 1 ) if __name__ == "__main__": from doctest import testmod testmod()
339
0
import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_nllb import NllbTokenizer else: SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : Optional[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Any = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"} SCREAMING_SNAKE_CASE__ : str = { "vocab_file": { "facebook/nllb-200-distilled-600M": ( "https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/sentencepiece.bpe.model" ), }, "tokenizer_file": { "facebook/nllb-200-distilled-600M": ( "https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/tokenizer.json" ), }, } SCREAMING_SNAKE_CASE__ : str = { "facebook/nllb-large-en-ro": 1_024, "facebook/nllb-200-distilled-600M": 1_024, } # fmt: off SCREAMING_SNAKE_CASE__ : str = ["ace_Arab", "ace_Latn", "acm_Arab", "acq_Arab", "aeb_Arab", "afr_Latn", "ajp_Arab", "aka_Latn", "amh_Ethi", "apc_Arab", "arb_Arab", "ars_Arab", "ary_Arab", "arz_Arab", "asm_Beng", "ast_Latn", "awa_Deva", "ayr_Latn", "azb_Arab", "azj_Latn", "bak_Cyrl", "bam_Latn", "ban_Latn", "bel_Cyrl", "bem_Latn", "ben_Beng", "bho_Deva", "bjn_Arab", "bjn_Latn", "bod_Tibt", "bos_Latn", "bug_Latn", "bul_Cyrl", "cat_Latn", "ceb_Latn", "ces_Latn", "cjk_Latn", "ckb_Arab", "crh_Latn", "cym_Latn", "dan_Latn", "deu_Latn", "dik_Latn", "dyu_Latn", "dzo_Tibt", "ell_Grek", "eng_Latn", "epo_Latn", "est_Latn", "eus_Latn", "ewe_Latn", "fao_Latn", "pes_Arab", "fij_Latn", "fin_Latn", "fon_Latn", "fra_Latn", "fur_Latn", "fuv_Latn", "gla_Latn", "gle_Latn", "glg_Latn", "grn_Latn", "guj_Gujr", "hat_Latn", "hau_Latn", "heb_Hebr", "hin_Deva", "hne_Deva", "hrv_Latn", "hun_Latn", "hye_Armn", "ibo_Latn", "ilo_Latn", "ind_Latn", "isl_Latn", "ita_Latn", "jav_Latn", "jpn_Jpan", "kab_Latn", "kac_Latn", "kam_Latn", "kan_Knda", "kas_Arab", "kas_Deva", "kat_Geor", "knc_Arab", "knc_Latn", "kaz_Cyrl", "kbp_Latn", "kea_Latn", "khm_Khmr", "kik_Latn", "kin_Latn", "kir_Cyrl", "kmb_Latn", "kon_Latn", "kor_Hang", "kmr_Latn", "lao_Laoo", "lvs_Latn", "lij_Latn", "lim_Latn", "lin_Latn", "lit_Latn", "lmo_Latn", "ltg_Latn", "ltz_Latn", "lua_Latn", "lug_Latn", "luo_Latn", "lus_Latn", "mag_Deva", "mai_Deva", "mal_Mlym", "mar_Deva", "min_Latn", "mkd_Cyrl", "plt_Latn", "mlt_Latn", "mni_Beng", "khk_Cyrl", "mos_Latn", "mri_Latn", "zsm_Latn", "mya_Mymr", "nld_Latn", "nno_Latn", "nob_Latn", "npi_Deva", "nso_Latn", "nus_Latn", "nya_Latn", "oci_Latn", "gaz_Latn", "ory_Orya", "pag_Latn", "pan_Guru", "pap_Latn", "pol_Latn", "por_Latn", "prs_Arab", "pbt_Arab", "quy_Latn", "ron_Latn", "run_Latn", "rus_Cyrl", "sag_Latn", "san_Deva", "sat_Beng", "scn_Latn", "shn_Mymr", "sin_Sinh", "slk_Latn", "slv_Latn", "smo_Latn", "sna_Latn", "snd_Arab", "som_Latn", "sot_Latn", "spa_Latn", "als_Latn", "srd_Latn", "srp_Cyrl", "ssw_Latn", "sun_Latn", "swe_Latn", "swh_Latn", "szl_Latn", "tam_Taml", "tat_Cyrl", "tel_Telu", "tgk_Cyrl", "tgl_Latn", "tha_Thai", "tir_Ethi", "taq_Latn", "taq_Tfng", "tpi_Latn", "tsn_Latn", "tso_Latn", "tuk_Latn", "tum_Latn", "tur_Latn", "twi_Latn", "tzm_Tfng", "uig_Arab", "ukr_Cyrl", "umb_Latn", "urd_Arab", "uzn_Latn", "vec_Latn", "vie_Latn", "war_Latn", "wol_Latn", "xho_Latn", "ydd_Hebr", "yor_Latn", "yue_Hant", "zho_Hans", "zho_Hant", "zul_Latn"] class lowerCAmelCase__ ( __lowercase ): a__ : List[Any] = VOCAB_FILES_NAMES a__ : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ : List[str] = PRETRAINED_VOCAB_FILES_MAP a__ : int = ["""input_ids""", """attention_mask"""] a__ : List[str] = NllbTokenizer a__ : List[int] = [] a__ : List[int] = [] def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : int="<s>" , SCREAMING_SNAKE_CASE__ : int="</s>" , SCREAMING_SNAKE_CASE__ : List[Any]="</s>" , SCREAMING_SNAKE_CASE__ : Dict="<s>" , SCREAMING_SNAKE_CASE__ : List[str]="<unk>" , SCREAMING_SNAKE_CASE__ : Any="<pad>" , SCREAMING_SNAKE_CASE__ : List[Any]="<mask>" , SCREAMING_SNAKE_CASE__ : Tuple=None , SCREAMING_SNAKE_CASE__ : int=None , SCREAMING_SNAKE_CASE__ : List[str]=None , SCREAMING_SNAKE_CASE__ : str=False , **SCREAMING_SNAKE_CASE__ : Optional[int] , ) -> List[str]: # Mask token behave like a normal word, i.e. include the space before it __lowerCamelCase = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else mask_token __lowerCamelCase = legacy_behaviour super().__init__( vocab_file=SCREAMING_SNAKE_CASE__ , tokenizer_file=SCREAMING_SNAKE_CASE__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , src_lang=SCREAMING_SNAKE_CASE__ , tgt_lang=SCREAMING_SNAKE_CASE__ , additional_special_tokens=SCREAMING_SNAKE_CASE__ , legacy_behaviour=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = vocab_file __lowerCamelCase = False if not self.vocab_file else True __lowerCamelCase = FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({'''additional_special_tokens''': _additional_special_tokens} ) __lowerCamelCase = { lang_code: self.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) for lang_code in FAIRSEQ_LANGUAGE_CODES } __lowerCamelCase = src_lang if src_lang is not None else '''eng_Latn''' __lowerCamelCase = self.convert_tokens_to_ids(self._src_lang ) __lowerCamelCase = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def __A ( self : int ) -> str: return self._src_lang @src_lang.setter def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str ) -> None: __lowerCamelCase = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def __A ( self : int , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: __lowerCamelCase = [self.sep_token_id] __lowerCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] , SCREAMING_SNAKE_CASE__ : Optional[str] , **SCREAMING_SNAKE_CASE__ : Any ) -> List[Any]: if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) __lowerCamelCase = src_lang __lowerCamelCase = self(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = tgt_lang_id return inputs def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str = "eng_Latn" , SCREAMING_SNAKE_CASE__ : Optional[List[str]] = None , SCREAMING_SNAKE_CASE__ : str = "fra_Latn" , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> BatchEncoding: __lowerCamelCase = src_lang __lowerCamelCase = tgt_lang return super().prepare_seqaseq_batch(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[Any] ) -> List[str]: return self.set_src_lang_special_tokens(self.src_lang ) def __A ( self : Union[str, Any] ) -> Tuple: return self.set_tgt_lang_special_tokens(self.tgt_lang ) def __A ( self : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> None: __lowerCamelCase = self.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) if self.legacy_behaviour: __lowerCamelCase = [] __lowerCamelCase = [self.eos_token_id, self.cur_lang_code] else: __lowerCamelCase = [self.cur_lang_code] __lowerCamelCase = [self.eos_token_id] __lowerCamelCase = self.convert_ids_to_tokens(self.prefix_tokens ) __lowerCamelCase = self.convert_ids_to_tokens(self.suffix_tokens ) __lowerCamelCase = processors.TemplateProcessing( single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str , pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def __A ( self : int , SCREAMING_SNAKE_CASE__ : str ) -> None: __lowerCamelCase = self.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) if self.legacy_behaviour: __lowerCamelCase = [] __lowerCamelCase = [self.eos_token_id, self.cur_lang_code] else: __lowerCamelCase = [self.cur_lang_code] __lowerCamelCase = [self.eos_token_id] __lowerCamelCase = self.convert_ids_to_tokens(self.prefix_tokens ) __lowerCamelCase = self.convert_ids_to_tokens(self.suffix_tokens ) __lowerCamelCase = processors.TemplateProcessing( single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str , pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not self.can_save_slow_tokenizer: raise ValueError( '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ''' '''tokenizer.''' ) if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory.''' ) return __lowerCamelCase = 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__ ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
365
import json import os from typing import Dict, List, Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE__ : Any = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Optional[Any] = { "vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_config_file": "tokenizer_config.json", } SCREAMING_SNAKE_CASE__ : str = { "vocab_file": { "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json" }, "merges_file": { "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt" }, "tokenizer_config_file": { "facebook/blenderbot_small-90M": ( "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json" ) }, } SCREAMING_SNAKE_CASE__ : int = {"facebook/blenderbot_small-90M": 512} def __magic_name__ ( __lowerCAmelCase : List[str] ) -> Tuple: __lowerCamelCase = set() __lowerCamelCase = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __lowerCamelCase = char __lowerCamelCase = set(__lowerCAmelCase ) return pairs class lowerCAmelCase__ ( __lowercase ): a__ : List[Any] = VOCAB_FILES_NAMES a__ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP a__ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ : Dict = ["""input_ids""", """attention_mask"""] def __init__( self : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple="__start__" , SCREAMING_SNAKE_CASE__ : Tuple="__end__" , SCREAMING_SNAKE_CASE__ : List[str]="__unk__" , SCREAMING_SNAKE_CASE__ : str="__null__" , **SCREAMING_SNAKE_CASE__ : Optional[Any] , ) -> Optional[Any]: super().__init__(unk_token=SCREAMING_SNAKE_CASE__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) with open(SCREAMING_SNAKE_CASE__ , encoding='''utf-8''' ) as vocab_handle: __lowerCamelCase = json.load(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = {v: k for k, v in self.encoder.items()} with open(SCREAMING_SNAKE_CASE__ , encoding='''utf-8''' ) as merges_handle: __lowerCamelCase = merges_handle.read().split('''\n''' )[1:-1] __lowerCamelCase = [tuple(merge.split() ) for merge in merges] __lowerCamelCase = dict(zip(SCREAMING_SNAKE_CASE__ , range(len(SCREAMING_SNAKE_CASE__ ) ) ) ) __lowerCamelCase = {} @property def __A ( self : Dict ) -> int: return len(self.encoder ) def __A ( self : str ) -> Dict: return dict(self.encoder , **self.added_tokens_encoder ) def __A ( self : Any , SCREAMING_SNAKE_CASE__ : str ) -> str: if token in self.cache: return self.cache[token] __lowerCamelCase = re.sub('''([.,!?()])''' , R''' \1''' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = re.sub('''(\')''' , R''' \1 ''' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = re.sub(R'''\s{2,}''' , ''' ''' , SCREAMING_SNAKE_CASE__ ) if "\n" in token: __lowerCamelCase = token.replace('''\n''' , ''' __newln__''' ) __lowerCamelCase = token.split(''' ''' ) __lowerCamelCase = [] for token in tokens: if not len(SCREAMING_SNAKE_CASE__ ): continue __lowerCamelCase = token.lower() __lowerCamelCase = tuple(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = tuple(list(word[:-1] ) + [word[-1] + '''</w>'''] ) __lowerCamelCase = get_pairs(SCREAMING_SNAKE_CASE__ ) if not pairs: words.append(SCREAMING_SNAKE_CASE__ ) continue while True: __lowerCamelCase = min(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : self.bpe_ranks.get(SCREAMING_SNAKE_CASE__ , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break __lowerCamelCase , __lowerCamelCase = bigram __lowerCamelCase = [] __lowerCamelCase = 0 while i < len(SCREAMING_SNAKE_CASE__ ): try: __lowerCamelCase = word.index(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) new_word.extend(word[i:j] ) __lowerCamelCase = j except ValueError: new_word.extend(word[i:] ) break if word[i] == first and i < len(SCREAMING_SNAKE_CASE__ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 __lowerCamelCase = tuple(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = new_word if len(SCREAMING_SNAKE_CASE__ ) == 1: break else: __lowerCamelCase = get_pairs(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = '''@@ '''.join(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = word[:-4] __lowerCamelCase = word words.append(SCREAMING_SNAKE_CASE__ ) return " ".join(SCREAMING_SNAKE_CASE__ ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: __lowerCamelCase = [] __lowerCamelCase = re.findall(R'''\S+\n?''' , SCREAMING_SNAKE_CASE__ ) for token in words: split_tokens.extend(list(self.bpe(SCREAMING_SNAKE_CASE__ ).split(''' ''' ) ) ) return split_tokens def __A ( self : str , SCREAMING_SNAKE_CASE__ : str ) -> int: __lowerCamelCase = token.lower() return self.encoder.get(SCREAMING_SNAKE_CASE__ , self.encoder.get(self.unk_token ) ) def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : int ) -> str: return self.decoder.get(SCREAMING_SNAKE_CASE__ , self.unk_token ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] ) -> str: __lowerCamelCase = ''' '''.join(SCREAMING_SNAKE_CASE__ ).replace('''@@ ''' , '''''' ).strip() return out_string def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __lowerCamelCase = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) __lowerCamelCase = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(SCREAMING_SNAKE_CASE__ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=SCREAMING_SNAKE_CASE__ , ensure_ascii=SCREAMING_SNAKE_CASE__ ) + '''\n''' ) __lowerCamelCase = 0 with open(SCREAMING_SNAKE_CASE__ , '''w''' , encoding='''utf-8''' ) as writer: writer.write('''#version: 0.2\n''' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda SCREAMING_SNAKE_CASE__ : kv[1] ): if index != token_index: logger.warning( f'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.''' ''' Please check that the tokenizer is not corrupted!''' ) __lowerCamelCase = token_index writer.write(''' '''.join(SCREAMING_SNAKE_CASE__ ) + '''\n''' ) index += 1 return vocab_file, merge_file
339
0
from functools import lru_cache def __magic_name__ ( __lowerCAmelCase : int ) -> set: __lowerCamelCase = 2 __lowerCamelCase = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(__lowerCAmelCase ) if n > 1: factors.add(__lowerCAmelCase ) return factors @lru_cache def __magic_name__ ( __lowerCAmelCase : int ) -> int: return len(unique_prime_factors(__lowerCAmelCase ) ) def __magic_name__ ( __lowerCAmelCase : list ) -> bool: return len(set(__lowerCAmelCase ) ) in (0, 1) def __magic_name__ ( __lowerCAmelCase : int ) -> list: __lowerCamelCase = 2 while True: # Increment each value of a generated range __lowerCamelCase = [base + i for i in range(__lowerCAmelCase )] # Run elements through out unique_prime_factors function # Append our target number to the end. __lowerCamelCase = [upf_len(__lowerCAmelCase ) for x in group] checker.append(__lowerCAmelCase ) # If all numbers in the list are equal, return the group variable. if equality(__lowerCAmelCase ): return group # Increment our base variable by 1 base += 1 def __magic_name__ ( __lowerCAmelCase : int = 4 ) -> int: __lowerCamelCase = run(__lowerCAmelCase ) return results[0] if len(__lowerCAmelCase ) else None if __name__ == "__main__": print(solution())
366
import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class lowerCAmelCase__ ( __lowercase , unittest.TestCase ): a__ : str = ShapEImgaImgPipeline a__ : Union[str, Any] = ["""image"""] a__ : Optional[int] = ["""image"""] a__ : Union[str, Any] = [ """num_images_per_prompt""", """num_inference_steps""", """generator""", """latents""", """guidance_scale""", """frame_size""", """output_type""", """return_dict""", ] a__ : List[str] = False @property def __A ( self : Dict ) -> Optional[Any]: return 32 @property def __A ( self : Optional[int] ) -> Optional[int]: return 32 @property def __A ( self : Optional[int] ) -> List[Any]: return self.time_input_dim * 4 @property def __A ( self : str ) -> List[Any]: return 8 @property def __A ( self : Optional[Any] ) -> Union[str, Any]: torch.manual_seed(0 ) __lowerCamelCase = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) __lowerCamelCase = CLIPVisionModel(SCREAMING_SNAKE_CASE__ ) return model @property def __A ( self : Union[str, Any] ) -> Union[str, Any]: __lowerCamelCase = CLIPImageProcessor( crop_size=2_24 , do_center_crop=SCREAMING_SNAKE_CASE__ , do_normalize=SCREAMING_SNAKE_CASE__ , do_resize=SCREAMING_SNAKE_CASE__ , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=2_24 , ) return image_processor @property def __A ( self : Dict ) -> int: torch.manual_seed(0 ) __lowerCamelCase = { '''num_attention_heads''': 2, '''attention_head_dim''': 16, '''embedding_dim''': self.time_input_dim, '''num_embeddings''': 32, '''embedding_proj_dim''': self.text_embedder_hidden_size, '''time_embed_dim''': self.time_embed_dim, '''num_layers''': 1, '''clip_embed_dim''': self.time_input_dim * 2, '''additional_embeddings''': 0, '''time_embed_act_fn''': '''gelu''', '''norm_in_type''': '''layer''', '''embedding_proj_norm_type''': '''layer''', '''encoder_hid_proj_type''': None, '''added_emb_type''': None, } __lowerCamelCase = PriorTransformer(**SCREAMING_SNAKE_CASE__ ) return model @property def __A ( self : Tuple ) -> Dict: torch.manual_seed(0 ) __lowerCamelCase = { '''param_shapes''': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), '''d_latent''': self.time_input_dim, '''d_hidden''': self.renderer_dim, '''n_output''': 12, '''background''': ( 0.1, 0.1, 0.1, ), } __lowerCamelCase = ShapERenderer(**SCREAMING_SNAKE_CASE__ ) return model def __A ( self : Optional[int] ) -> List[str]: __lowerCamelCase = self.dummy_prior __lowerCamelCase = self.dummy_image_encoder __lowerCamelCase = self.dummy_image_processor __lowerCamelCase = self.dummy_renderer __lowerCamelCase = HeunDiscreteScheduler( beta_schedule='''exp''' , num_train_timesteps=10_24 , prediction_type='''sample''' , use_karras_sigmas=SCREAMING_SNAKE_CASE__ , clip_sample=SCREAMING_SNAKE_CASE__ , clip_sample_range=1.0 , ) __lowerCamelCase = { '''prior''': prior, '''image_encoder''': image_encoder, '''image_processor''': image_processor, '''renderer''': renderer, '''scheduler''': scheduler, } return components def __A ( self : str , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any=0 ) -> int: __lowerCamelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) if str(SCREAMING_SNAKE_CASE__ ).startswith('''mps''' ): __lowerCamelCase = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: __lowerCamelCase = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = { '''image''': input_image, '''generator''': generator, '''num_inference_steps''': 1, '''frame_size''': 32, '''output_type''': '''np''', } return inputs def __A ( self : Union[str, Any] ) -> Dict: __lowerCamelCase = '''cpu''' __lowerCamelCase = self.get_dummy_components() __lowerCamelCase = self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe(**self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = output.images[0] __lowerCamelCase = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __lowerCamelCase = np.array( [ 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __A ( self : str ) -> Tuple: # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def __A ( self : Optional[Any] ) -> str: __lowerCamelCase = torch_device == '''cpu''' __lowerCamelCase = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=SCREAMING_SNAKE_CASE__ , relax_max_difference=SCREAMING_SNAKE_CASE__ , ) def __A ( self : Dict ) -> Optional[int]: __lowerCamelCase = self.get_dummy_components() __lowerCamelCase = self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = 1 __lowerCamelCase = 2 __lowerCamelCase = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) for key in inputs.keys(): if key in self.batch_params: __lowerCamelCase = batch_size * [inputs[key]] __lowerCamelCase = pipe(**SCREAMING_SNAKE_CASE__ , num_images_per_prompt=SCREAMING_SNAKE_CASE__ )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : str ) -> Union[str, Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self : str ) -> Union[str, Any]: __lowerCamelCase = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/corgi.png''' ) __lowerCamelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/test_shap_e_img2img_out.npy''' ) __lowerCamelCase = ShapEImgaImgPipeline.from_pretrained('''openai/shap-e-img2img''' ) __lowerCamelCase = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(0 ) __lowerCamelCase = pipe( SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type='''np''' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
339
0
import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer SCREAMING_SNAKE_CASE__ : Optional[int] = "bart" SCREAMING_SNAKE_CASE__ : Dict = True @st.cache(allow_output_mutation=__lowerCAmelCase ) def __magic_name__ ( ) -> str: if LOAD_DENSE_INDEX: __lowerCamelCase = AutoTokenizer.from_pretrained('''yjernite/retribert-base-uncased''' ) __lowerCamelCase = AutoModel.from_pretrained('''yjernite/retribert-base-uncased''' ).to('''cuda:0''' ) __lowerCamelCase = qar_model.eval() else: __lowerCamelCase , __lowerCamelCase = (None, None) if MODEL_TYPE == "bart": __lowerCamelCase = AutoTokenizer.from_pretrained('''yjernite/bart_eli5''' ) __lowerCamelCase = AutoModelForSeqaSeqLM.from_pretrained('''yjernite/bart_eli5''' ).to('''cuda:0''' ) __lowerCamelCase = torch.load('''seq2seq_models/eli5_bart_model_blm_2.pth''' ) sas_model.load_state_dict(save_dict['''model'''] ) __lowerCamelCase = sas_model.eval() else: __lowerCamelCase , __lowerCamelCase = make_qa_sas_model( model_name='''t5-small''' , from_file='''seq2seq_models/eli5_t5_model_1024_4.pth''' , device='''cuda:0''' ) return (qar_tokenizer, qar_model, sas_tokenizer, sas_model) @st.cache(allow_output_mutation=__lowerCAmelCase ) def __magic_name__ ( ) -> Optional[int]: if LOAD_DENSE_INDEX: __lowerCamelCase = faiss.StandardGpuResources() __lowerCamelCase = datasets.load_dataset(path='''wiki_snippets''' , name='''wiki40b_en_100_0''' )['''train'''] __lowerCamelCase = np.memmap( '''wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat''' , dtype='''float32''' , mode='''r''' , shape=(wikiaab_passages.num_rows, 128) , ) __lowerCamelCase = faiss.IndexFlatIP(128 ) __lowerCamelCase = faiss.index_cpu_to_gpu(__lowerCAmelCase , 1 , __lowerCAmelCase ) wikiaab_gpu_index_flat.add(__lowerCAmelCase ) # TODO fix for larger GPU else: __lowerCamelCase , __lowerCamelCase = (None, None) __lowerCamelCase = Elasticsearch([{'''host''': '''localhost''', '''port''': '''9200'''}] ) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=__lowerCAmelCase ) def __magic_name__ ( ) -> List[str]: __lowerCamelCase = datasets.load_dataset('''eli5''' , name='''LFQA_reddit''' ) __lowerCamelCase = elia['''train_eli5'''] __lowerCamelCase = np.memmap( '''eli5_questions_reps.dat''' , dtype='''float32''' , mode='''r''' , shape=(elia_train.num_rows, 128) ) __lowerCamelCase = faiss.IndexFlatIP(128 ) eli5_train_q_index.add(__lowerCAmelCase ) return (elia_train, eli5_train_q_index) SCREAMING_SNAKE_CASE__ : int = load_indexes() SCREAMING_SNAKE_CASE__ : List[Any] = load_models() SCREAMING_SNAKE_CASE__ : int = load_train_data() def __magic_name__ ( __lowerCAmelCase : Dict , __lowerCAmelCase : List[str]=10 ) -> List[str]: __lowerCamelCase = embed_questions_for_retrieval([question] , __lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase , __lowerCamelCase = eli5_train_q_index.search(__lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase = [elia_train[int(__lowerCAmelCase )] for i in I[0]] return nn_examples def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : Dict="wiki40b" , __lowerCAmelCase : Any="dense" , __lowerCAmelCase : Dict=10 ) -> Union[str, Any]: if source == "none": __lowerCamelCase , __lowerCamelCase = (''' <P> '''.join(['''''' for _ in range(11 )] ).strip(), []) else: if method == "dense": __lowerCamelCase , __lowerCamelCase = query_qa_dense_index( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) else: __lowerCamelCase , __lowerCamelCase = query_es_index( __lowerCAmelCase , __lowerCAmelCase , index_name='''english_wiki40b_snippets_100w''' , n_results=__lowerCAmelCase , ) __lowerCamelCase = [ (res['''article_title'''], res['''section_title'''].strip(), res['''score'''], res['''passage_text''']) for res in hit_lst ] __lowerCamelCase = '''question: {} context: {}'''.format(__lowerCAmelCase , __lowerCAmelCase ) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda __lowerCAmelCase : None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda __lowerCAmelCase : None), } ) def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : Dict , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : str=64 , __lowerCAmelCase : Dict=256 , __lowerCAmelCase : Union[str, Any]=False , __lowerCAmelCase : Optional[int]=2 , __lowerCAmelCase : Optional[Any]=0.95 , __lowerCAmelCase : List[Any]=0.8 ) -> Any: with torch.no_grad(): __lowerCamelCase = qa_sas_generate( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , num_answers=1 , num_beams=__lowerCAmelCase , min_len=__lowerCAmelCase , max_len=__lowerCAmelCase , do_sample=__lowerCAmelCase , temp=__lowerCAmelCase , top_p=__lowerCAmelCase , top_k=__lowerCAmelCase , max_input_length=1024 , device='''cuda:0''' , )[0] return (answer, support_list) st.title("Long Form Question Answering with ELI5") # Start sidebar SCREAMING_SNAKE_CASE__ : List[str] = "<img src='https://huggingface.co/front/assets/huggingface_logo.svg'>" SCREAMING_SNAKE_CASE__ : Dict = "\n<html>\n <head>\n <style>\n .img-container {\n padding-left: 90px;\n padding-right: 90px;\n padding-top: 50px;\n padding-bottom: 50px;\n background-color: #f0f3f9;\n }\n </style>\n </head>\n <body>\n <span class=\"img-container\"> <!-- Inline parent element -->\n %s\n </span>\n </body>\n</html>\n" % ( header_html, ) st.sidebar.markdown( header_full, unsafe_allow_html=True, ) # Long Form QA with ELI5 and Wikipedia SCREAMING_SNAKE_CASE__ : int = "\nThis demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).\nFirst, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,\na pre-processed fixed snapshot of Wikipedia.\n" st.sidebar.markdown(description, unsafe_allow_html=True) SCREAMING_SNAKE_CASE__ : str = [ "Answer the question", "View the retrieved document only", "View the most similar ELI5 question and answer", "Show me everything, please!", ] SCREAMING_SNAKE_CASE__ : Optional[int] = st.sidebar.checkbox("Demo options") if demo_options: SCREAMING_SNAKE_CASE__ : Optional[int] = st.sidebar.selectbox( "", action_list, index=3, ) SCREAMING_SNAKE_CASE__ : Optional[Any] = action_list.index(action_st) SCREAMING_SNAKE_CASE__ : int = st.sidebar.selectbox( "", ["Show full text of passages", "Show passage section titles"], index=0, ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = show_type == "Show full text of passages" else: SCREAMING_SNAKE_CASE__ : Any = 3 SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : Union[str, Any] = st.sidebar.checkbox("Retrieval options") if retrieval_options: SCREAMING_SNAKE_CASE__ : Tuple = "\n ### Information retriever options\n\n The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding\n trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.\n The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.\n " st.sidebar.markdown(retriever_info) SCREAMING_SNAKE_CASE__ : Union[str, Any] = st.sidebar.selectbox("Which Wikipedia format should the model use?", ["wiki40b", "none"]) SCREAMING_SNAKE_CASE__ : int = st.sidebar.selectbox("Which Wikipedia indexer should the model use?", ["dense", "sparse", "mixed"]) else: SCREAMING_SNAKE_CASE__ : List[str] = "wiki40b" SCREAMING_SNAKE_CASE__ : Optional[Any] = "dense" SCREAMING_SNAKE_CASE__ : str = "beam" SCREAMING_SNAKE_CASE__ : List[Any] = 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = 64 SCREAMING_SNAKE_CASE__ : List[Any] = 256 SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : List[str] = st.sidebar.checkbox("Generation options") if generate_options: SCREAMING_SNAKE_CASE__ : Dict = "\n ### Answer generation options\n\n The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)\n weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with\n **beam** search, or **sample** from the decoder's output probabilities.\n " st.sidebar.markdown(generate_info) SCREAMING_SNAKE_CASE__ : List[str] = st.sidebar.selectbox("Would you like to use beam search or sample an answer?", ["beam", "sampled"]) SCREAMING_SNAKE_CASE__ : Any = st.sidebar.slider( "Minimum generation length", min_value=8, max_value=256, value=64, step=8, format=None, key=None ) SCREAMING_SNAKE_CASE__ : str = st.sidebar.slider( "Maximum generation length", min_value=64, max_value=512, value=256, step=16, format=None, key=None ) if sampled == "beam": SCREAMING_SNAKE_CASE__ : Union[str, Any] = st.sidebar.slider("Beam size", min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: SCREAMING_SNAKE_CASE__ : Any = st.sidebar.slider( "Nucleus sampling p", min_value=0.1, max_value=1.0, value=0.9_5, step=0.0_1, format=None, key=None ) SCREAMING_SNAKE_CASE__ : Dict = st.sidebar.slider( "Temperature", min_value=0.1, max_value=1.0, value=0.7, step=0.0_1, format=None, key=None ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = None # start main text SCREAMING_SNAKE_CASE__ : Any = [ "<MY QUESTION>", "How do people make chocolate?", "Why do we get a fever when we are sick?", "How can different animals perceive different colors?", "What is natural language processing?", "What's the best way to treat a sunburn?", "What exactly are vitamins ?", "How does nuclear energy provide electricity?", "What's the difference between viruses and bacteria?", "Why are flutes classified as woodwinds when most of them are made out of metal ?", "Why do people like drinking coffee even though it tastes so bad?", "What happens when wine ages? How does it make the wine taste better?", "If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?", "How can we set a date to the beginning or end of an artistic period? Doesn't the change happen gradually?", "How does New Zealand have so many large bird predators?", ] SCREAMING_SNAKE_CASE__ : List[str] = st.selectbox( "What would you like to ask? ---- select <MY QUESTION> to enter a new query", questions_list, index=1, ) if question_s == "<MY QUESTION>": SCREAMING_SNAKE_CASE__ : Union[str, Any] = st.text_input("Enter your question here:", "") else: SCREAMING_SNAKE_CASE__ : str = question_s if st.button("Show me!"): if action in [0, 1, 3]: if index_type == "mixed": SCREAMING_SNAKE_CASE__ : Union[str, Any] = make_support(question, source=wiki_source, method="dense", n_results=10) SCREAMING_SNAKE_CASE__ : str = make_support(question, source=wiki_source, method="sparse", n_results=10) SCREAMING_SNAKE_CASE__ : int = [] for res_d, res_s in zip(support_list_dense, support_list_sparse): if tuple(res_d) not in support_list: support_list += [tuple(res_d)] if tuple(res_s) not in support_list: support_list += [tuple(res_s)] SCREAMING_SNAKE_CASE__ : Optional[Any] = support_list[:10] SCREAMING_SNAKE_CASE__ : Tuple = "<P> " + " <P> ".join([res[-1] for res in support_list]) else: SCREAMING_SNAKE_CASE__ : Optional[int] = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: SCREAMING_SNAKE_CASE__ : Optional[Any] = answer_question( question_doc, sas_model, sas_tokenizer, min_len=min_len, max_len=int(max_len), sampling=(sampled == "sampled"), n_beams=n_beams, top_p=top_p, temp=temp, ) st.markdown("### The model generated answer is:") st.write(answer) if action in [0, 1, 3] and wiki_source != "none": st.markdown("--- \n ### The model is drawing information from the following Wikipedia passages:") for i, res in enumerate(support_list): SCREAMING_SNAKE_CASE__ : Optional[int] = "https://en.wikipedia.org/wiki/{}".format(res[0].replace(" ", "_")) SCREAMING_SNAKE_CASE__ : Tuple = res[1].strip() if sec_titles == "": SCREAMING_SNAKE_CASE__ : Union[str, Any] = "[{}]({})".format(res[0], wiki_url) else: SCREAMING_SNAKE_CASE__ : Dict = sec_titles.split(" & ") SCREAMING_SNAKE_CASE__ : int = " & ".join( ["[{}]({}#{})".format(sec.strip(), wiki_url, sec.strip().replace(" ", "_")) for sec in sec_list] ) st.markdown( "{0:02d} - **Article**: {1:<18} <br> _Section_: {2}".format(i + 1, res[0], sections), unsafe_allow_html=True, ) if show_passages: st.write( "> <span style=\"font-family:arial; font-size:10pt;\">" + res[-1] + "</span>", unsafe_allow_html=True ) if action in [2, 3]: SCREAMING_SNAKE_CASE__ : Any = find_nearest_training(question) SCREAMING_SNAKE_CASE__ : List[Any] = nn_train_list[0] st.markdown( "--- \n ### The most similar question in the ELI5 training set was: \n\n {}".format(train_exple["title"]) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ "{}. {}".format(i + 1, " \n".join([line.strip() for line in ans.split("\n") if line.strip() != ""])) for i, (ans, sc) in enumerate(zip(train_exple["answers"]["text"], train_exple["answers"]["score"])) if i == 0 or sc > 2 ] st.markdown("##### Its answers were: \n\n {}".format("\n".join(answers_st))) SCREAMING_SNAKE_CASE__ : List[Any] = "\n---\n\n**Disclaimer**\n\n*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.\nEvaluating biases of such a model and ensuring factual generations are still very much open research problems.\nTherefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*\n" st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
367
import glob import os import random from string import ascii_lowercase, digits import cva SCREAMING_SNAKE_CASE__ : str = "" SCREAMING_SNAKE_CASE__ : Any = "" SCREAMING_SNAKE_CASE__ : Optional[Any] = "" SCREAMING_SNAKE_CASE__ : Optional[Any] = 1 # (0 is vertical, 1 is horizontal) def __magic_name__ ( ) -> None: __lowerCamelCase , __lowerCamelCase = get_dataset(__lowerCAmelCase , __lowerCAmelCase ) print('''Processing...''' ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = update_image_and_anno(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) for index, image in enumerate(__lowerCAmelCase ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' __lowerCamelCase = random_chars(32 ) __lowerCamelCase = paths[index].split(os.sep )[-1].rsplit('''.''' , 1 )[0] __lowerCamelCase = f'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(f'''/{file_root}.jpg''' , __lowerCAmelCase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(f'''Success {index+1}/{len(__lowerCAmelCase )} with {file_name}''' ) __lowerCamelCase = [] for anno in new_annos[index]: __lowerCamelCase = f'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(__lowerCAmelCase ) with open(f'''/{file_root}.txt''' , '''w''' ) as outfile: outfile.write('''\n'''.join(line for line in annos_list ) ) def __magic_name__ ( __lowerCAmelCase : str , __lowerCAmelCase : str ) -> tuple[list, list]: __lowerCamelCase = [] __lowerCamelCase = [] for label_file in glob.glob(os.path.join(__lowerCAmelCase , '''*.txt''' ) ): __lowerCamelCase = label_file.split(os.sep )[-1].rsplit('''.''' , 1 )[0] with open(__lowerCAmelCase ) as in_file: __lowerCamelCase = in_file.readlines() __lowerCamelCase = os.path.join(__lowerCAmelCase , f'''{label_name}.jpg''' ) __lowerCamelCase = [] for obj_list in obj_lists: __lowerCamelCase = obj_list.rstrip('''\n''' ).split(''' ''' ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(__lowerCAmelCase ) labels.append(__lowerCAmelCase ) return img_paths, labels def __magic_name__ ( __lowerCAmelCase : list , __lowerCAmelCase : list , __lowerCAmelCase : int = 1 ) -> tuple[list, list, list]: __lowerCamelCase = [] __lowerCamelCase = [] __lowerCamelCase = [] for idx in range(len(__lowerCAmelCase ) ): __lowerCamelCase = [] __lowerCamelCase = img_list[idx] path_list.append(__lowerCAmelCase ) __lowerCamelCase = anno_list[idx] __lowerCamelCase = cva.imread(__lowerCAmelCase ) if flip_type == 1: __lowerCamelCase = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: __lowerCamelCase = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: __lowerCamelCase = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: __lowerCamelCase = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(__lowerCAmelCase ) new_imgs_list.append(__lowerCAmelCase ) return new_imgs_list, new_annos_lists, path_list def __magic_name__ ( __lowerCAmelCase : int = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" __lowerCamelCase = ascii_lowercase + digits return "".join(random.choice(__lowerCAmelCase ) for _ in range(__lowerCAmelCase ) ) if __name__ == "__main__": main() print("DONE ✅")
339
0
import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMInverseScheduler, DDIMScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, StableDiffusionDiffEditPipeline, UNetaDConditionModel, ) from diffusers.utils import load_image, slow from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( __lowercase , __lowercase , unittest.TestCase ): a__ : Dict = StableDiffusionDiffEditPipeline a__ : Tuple = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"""height""", """width""", """image"""} | {"""image_latents"""} a__ : int = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {"""image"""} | {"""image_latents"""} a__ : int = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess a__ : Tuple = frozenset([] ) def __A ( self : List[str] ) -> Any: torch.manual_seed(0 ) __lowerCamelCase = 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 , attention_head_dim=(2, 4) , use_linear_projection=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule='''scaled_linear''' , clip_sample=SCREAMING_SNAKE_CASE__ , set_alpha_to_one=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = DDIMInverseScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule='''scaled_linear''' , clip_sample=SCREAMING_SNAKE_CASE__ , set_alpha_to_zero=SCREAMING_SNAKE_CASE__ , ) torch.manual_seed(0 ) __lowerCamelCase = 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 , sample_size=1_28 , ) torch.manual_seed(0 ) __lowerCamelCase = 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=10_00 , hidden_act='''gelu''' , projection_dim=5_12 , ) __lowerCamelCase = CLIPTextModel(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) __lowerCamelCase = { '''unet''': unet, '''scheduler''': scheduler, '''inverse_scheduler''': inverse_scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def __A ( self : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : str=0 ) -> Dict: __lowerCamelCase = floats_tensor((1, 16, 16) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = floats_tensor((1, 2, 4, 16, 16) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) if str(SCREAMING_SNAKE_CASE__ ).startswith('''mps''' ): __lowerCamelCase = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: __lowerCamelCase = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = { '''prompt''': '''a dog and a newt''', '''mask_image''': mask, '''image_latents''': latents, '''generator''': generator, '''num_inference_steps''': 2, '''inpaint_strength''': 1.0, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', } return inputs def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple=0 ) -> Dict: __lowerCamelCase = floats_tensor((1, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = image.cpu().permute(0 , 2 , 3 , 1 )[0] __lowerCamelCase = Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE__ ) ).convert('''RGB''' ) if str(SCREAMING_SNAKE_CASE__ ).startswith('''mps''' ): __lowerCamelCase = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: __lowerCamelCase = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = { '''image''': image, '''source_prompt''': '''a cat and a frog''', '''target_prompt''': '''a dog and a newt''', '''generator''': generator, '''num_inference_steps''': 2, '''num_maps_per_mask''': 2, '''mask_encode_strength''': 1.0, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', } return inputs def __A ( self : str , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int=0 ) -> Union[str, Any]: __lowerCamelCase = floats_tensor((1, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = image.cpu().permute(0 , 2 , 3 , 1 )[0] __lowerCamelCase = Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE__ ) ).convert('''RGB''' ) if str(SCREAMING_SNAKE_CASE__ ).startswith('''mps''' ): __lowerCamelCase = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: __lowerCamelCase = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = { '''image''': image, '''prompt''': '''a cat and a frog''', '''generator''': generator, '''num_inference_steps''': 2, '''inpaint_strength''': 1.0, '''guidance_scale''': 6.0, '''decode_latents''': True, '''output_type''': '''numpy''', } return inputs def __A ( self : str ) -> Union[str, Any]: if not hasattr(self.pipeline_class , '''_optional_components''' ): return __lowerCamelCase = self.get_dummy_components() __lowerCamelCase = self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) # set all optional components to None and update pipeline config accordingly for optional_component in pipe._optional_components: setattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components} ) __lowerCamelCase = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe(**SCREAMING_SNAKE_CASE__ )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.pipeline_class.from_pretrained(SCREAMING_SNAKE_CASE__ ) pipe_loaded.to(SCREAMING_SNAKE_CASE__ ) pipe_loaded.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) for optional_component in pipe._optional_components: self.assertTrue( getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) is None , f'''`{optional_component}` did not stay set to None after loading.''' , ) __lowerCamelCase = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe_loaded(**SCREAMING_SNAKE_CASE__ )[0] __lowerCamelCase = np.abs(output - output_loaded ).max() self.assertLess(SCREAMING_SNAKE_CASE__ , 1e-4 ) def __A ( self : List[Any] ) -> List[str]: __lowerCamelCase = '''cpu''' __lowerCamelCase = self.get_dummy_components() __lowerCamelCase = self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_dummy_mask_inputs(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe.generate_mask(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = mask[0, -3:, -3:] self.assertEqual(mask.shape , (1, 16, 16) ) __lowerCamelCase = np.array([0] * 9 ) __lowerCamelCase = np.abs(mask_slice.flatten() - expected_slice ).max() self.assertLessEqual(SCREAMING_SNAKE_CASE__ , 1e-3 ) self.assertEqual(mask[0, -3, -4] , 0 ) def __A ( self : Tuple ) -> List[str]: __lowerCamelCase = '''cpu''' __lowerCamelCase = self.get_dummy_components() __lowerCamelCase = self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_dummy_inversion_inputs(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe.invert(**SCREAMING_SNAKE_CASE__ ).images __lowerCamelCase = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3) ) __lowerCamelCase = np.array( [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.51050, 0.5015, 0.4407, 0.4799] , ) __lowerCamelCase = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(SCREAMING_SNAKE_CASE__ , 1e-3 ) def __A ( self : List[Any] ) -> Optional[Any]: super().test_inference_batch_single_identical(expected_max_diff=5e-3 ) def __A ( self : Tuple ) -> Any: __lowerCamelCase = '''cpu''' __lowerCamelCase = self.get_dummy_components() __lowerCamelCase = {'''beta_start''': 0.00085, '''beta_end''': 0.012, '''beta_schedule''': '''scaled_linear'''} __lowerCamelCase = DPMSolverMultistepScheduler(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = DPMSolverMultistepInverseScheduler(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_dummy_inversion_inputs(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe.invert(**SCREAMING_SNAKE_CASE__ ).images __lowerCamelCase = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3) ) __lowerCamelCase = np.array( [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.51050, 0.5015, 0.4407, 0.4799] , ) __lowerCamelCase = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(SCREAMING_SNAKE_CASE__ , 1e-3 ) @require_torch_gpu @slow class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Optional[Any] ) -> List[Any]: super().tearDown() gc.collect() torch.cuda.empty_cache() @classmethod def __A ( cls : Tuple ) -> List[str]: __lowerCamelCase = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png''' ) __lowerCamelCase = raw_image.convert('''RGB''' ).resize((7_68, 7_68) ) __lowerCamelCase = raw_image def __A ( self : Optional[Any] ) -> Optional[int]: __lowerCamelCase = torch.manual_seed(0 ) __lowerCamelCase = StableDiffusionDiffEditPipeline.from_pretrained( '''stabilityai/stable-diffusion-2-1''' , safety_checker=SCREAMING_SNAKE_CASE__ , torch_dtype=torch.floataa ) __lowerCamelCase = DDIMScheduler.from_config(pipe.scheduler.config ) __lowerCamelCase = DDIMInverseScheduler.from_config(pipe.scheduler.config ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = '''a bowl of fruit''' __lowerCamelCase = '''a bowl of pears''' __lowerCamelCase = pipe.generate_mask( image=self.raw_image , source_prompt=SCREAMING_SNAKE_CASE__ , target_prompt=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = pipe.invert( prompt=SCREAMING_SNAKE_CASE__ , image=self.raw_image , inpaint_strength=0.7 , generator=SCREAMING_SNAKE_CASE__ ).latents __lowerCamelCase = pipe( prompt=SCREAMING_SNAKE_CASE__ , mask_image=SCREAMING_SNAKE_CASE__ , image_latents=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , negative_prompt=SCREAMING_SNAKE_CASE__ , inpaint_strength=0.7 , output_type='''numpy''' , ).images[0] __lowerCamelCase = ( np.array( load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/diffedit/pears.png''' ).resize((7_68, 7_68) ) ) / 2_55 ) assert np.abs((expected_image - image).max() ) < 5e-1 def __A ( self : Any ) -> str: __lowerCamelCase = torch.manual_seed(0 ) __lowerCamelCase = StableDiffusionDiffEditPipeline.from_pretrained( '''stabilityai/stable-diffusion-2-1''' , safety_checker=SCREAMING_SNAKE_CASE__ , torch_dtype=torch.floataa ) __lowerCamelCase = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) __lowerCamelCase = DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = '''a bowl of fruit''' __lowerCamelCase = '''a bowl of pears''' __lowerCamelCase = pipe.generate_mask( image=self.raw_image , source_prompt=SCREAMING_SNAKE_CASE__ , target_prompt=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = pipe.invert( prompt=SCREAMING_SNAKE_CASE__ , image=self.raw_image , inpaint_strength=0.7 , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=25 , ).latents __lowerCamelCase = pipe( prompt=SCREAMING_SNAKE_CASE__ , mask_image=SCREAMING_SNAKE_CASE__ , image_latents=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , negative_prompt=SCREAMING_SNAKE_CASE__ , inpaint_strength=0.7 , num_inference_steps=25 , output_type='''numpy''' , ).images[0] __lowerCamelCase = ( np.array( load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/diffedit/pears.png''' ).resize((7_68, 7_68) ) ) / 2_55 ) assert np.abs((expected_image - image).max() ) < 5e-1
368
import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated SCREAMING_SNAKE_CASE__ : Tuple = collections.namedtuple("_Datasets", ["train", "validation", "test"]) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ SCREAMING_SNAKE_CASE__ : List[str] = "https://storage.googleapis.com/cvdf-datasets/mnist/" def __magic_name__ ( __lowerCAmelCase : Any ) -> int: __lowerCamelCase = numpy.dtype(numpy.uintaa ).newbyteorder('''>''' ) return numpy.frombuffer(bytestream.read(4 ) , dtype=__lowerCAmelCase )[0] @deprecated(__lowerCAmelCase , '''Please use tf.data to implement this functionality.''' ) def __magic_name__ ( __lowerCAmelCase : List[Any] ) -> str: print('''Extracting''' , f.name ) with gzip.GzipFile(fileobj=__lowerCAmelCase ) as bytestream: __lowerCamelCase = _readaa(__lowerCAmelCase ) if magic != 2051: raise ValueError( '''Invalid magic number %d in MNIST image file: %s''' % (magic, f.name) ) __lowerCamelCase = _readaa(__lowerCAmelCase ) __lowerCamelCase = _readaa(__lowerCAmelCase ) __lowerCamelCase = _readaa(__lowerCAmelCase ) __lowerCamelCase = bytestream.read(rows * cols * num_images ) __lowerCamelCase = numpy.frombuffer(__lowerCAmelCase , dtype=numpy.uinta ) __lowerCamelCase = data.reshape(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , 1 ) return data @deprecated(__lowerCAmelCase , '''Please use tf.one_hot on tensors.''' ) def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : List[Any] ) -> Dict: __lowerCamelCase = labels_dense.shape[0] __lowerCamelCase = numpy.arange(__lowerCAmelCase ) * num_classes __lowerCamelCase = numpy.zeros((num_labels, num_classes) ) __lowerCamelCase = 1 return labels_one_hot @deprecated(__lowerCAmelCase , '''Please use tf.data to implement this functionality.''' ) def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : str=False , __lowerCAmelCase : List[str]=10 ) -> List[str]: print('''Extracting''' , f.name ) with gzip.GzipFile(fileobj=__lowerCAmelCase ) as bytestream: __lowerCamelCase = _readaa(__lowerCAmelCase ) if magic != 2049: raise ValueError( '''Invalid magic number %d in MNIST label file: %s''' % (magic, f.name) ) __lowerCamelCase = _readaa(__lowerCAmelCase ) __lowerCamelCase = bytestream.read(__lowerCAmelCase ) __lowerCamelCase = numpy.frombuffer(__lowerCAmelCase , dtype=numpy.uinta ) if one_hot: return _dense_to_one_hot(__lowerCAmelCase , __lowerCAmelCase ) return labels class lowerCAmelCase__ : @deprecated( SCREAMING_SNAKE_CASE__ , '''Please use alternatives such as official/mnist/_DataSet.py''' ''' from tensorflow/models.''' , ) def __init__( self : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : List[str]=False , SCREAMING_SNAKE_CASE__ : str=dtypes.floataa , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : str=None , ) -> Optional[int]: __lowerCamelCase , __lowerCamelCase = random_seed.get_seed(SCREAMING_SNAKE_CASE__ ) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seeda if seed is None else seeda ) __lowerCamelCase = dtypes.as_dtype(SCREAMING_SNAKE_CASE__ ).base_dtype if dtype not in (dtypes.uinta, dtypes.floataa): raise TypeError('''Invalid image dtype %r, expected uint8 or float32''' % dtype ) if fake_data: __lowerCamelCase = 1_00_00 __lowerCamelCase = one_hot else: assert ( images.shape[0] == labels.shape[0] ), f'''images.shape: {images.shape} labels.shape: {labels.shape}''' __lowerCamelCase = images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 __lowerCamelCase = images.reshape( images.shape[0] , images.shape[1] * images.shape[2] ) if dtype == dtypes.floataa: # Convert from [0, 255] -> [0.0, 1.0]. __lowerCamelCase = images.astype(numpy.floataa ) __lowerCamelCase = numpy.multiply(SCREAMING_SNAKE_CASE__ , 1.0 / 255.0 ) __lowerCamelCase = images __lowerCamelCase = labels __lowerCamelCase = 0 __lowerCamelCase = 0 @property def __A ( self : str ) -> Optional[int]: return self._images @property def __A ( self : Any ) -> Dict: return self._labels @property def __A ( self : List[Any] ) -> int: return self._num_examples @property def __A ( self : str ) -> Any: return self._epochs_completed def __A ( self : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : str=True ) -> str: if fake_data: __lowerCamelCase = [1] * 7_84 __lowerCamelCase = [1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(SCREAMING_SNAKE_CASE__ )], [fake_label for _ in range(SCREAMING_SNAKE_CASE__ )], ) __lowerCamelCase = self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: __lowerCamelCase = numpy.arange(self._num_examples ) numpy.random.shuffle(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.images[perma] __lowerCamelCase = self.labels[perma] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch __lowerCamelCase = self._num_examples - start __lowerCamelCase = self._images[start : self._num_examples] __lowerCamelCase = self._labels[start : self._num_examples] # Shuffle the data if shuffle: __lowerCamelCase = numpy.arange(self._num_examples ) numpy.random.shuffle(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.images[perm] __lowerCamelCase = self.labels[perm] # Start next epoch __lowerCamelCase = 0 __lowerCamelCase = batch_size - rest_num_examples __lowerCamelCase = self._index_in_epoch __lowerCamelCase = self._images[start:end] __lowerCamelCase = self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part) , axis=0 ), numpy.concatenate((labels_rest_part, labels_new_part) , axis=0 ), ) else: self._index_in_epoch += batch_size __lowerCamelCase = self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(__lowerCAmelCase , '''Please write your own downloading logic.''' ) def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int , __lowerCAmelCase : Union[str, Any] ) -> List[Any]: if not gfile.Exists(__lowerCAmelCase ): gfile.MakeDirs(__lowerCAmelCase ) __lowerCamelCase = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) if not gfile.Exists(__lowerCAmelCase ): urllib.request.urlretrieve(__lowerCAmelCase , __lowerCAmelCase ) # noqa: S310 with gfile.GFile(__lowerCAmelCase ) as f: __lowerCamelCase = f.size() print('''Successfully downloaded''' , __lowerCAmelCase , __lowerCAmelCase , '''bytes.''' ) return filepath @deprecated( __lowerCAmelCase , '''Please use alternatives such as:''' ''' tensorflow_datasets.load(\'mnist\')''' ) def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[Any]=False , __lowerCAmelCase : Dict=False , __lowerCAmelCase : List[str]=dtypes.floataa , __lowerCAmelCase : Union[str, Any]=True , __lowerCAmelCase : int=5000 , __lowerCAmelCase : Any=None , __lowerCAmelCase : List[str]=DEFAULT_SOURCE_URL , ) -> Optional[Any]: if fake_data: def fake(): return _DataSet( [] , [] , fake_data=__lowerCAmelCase , one_hot=__lowerCAmelCase , dtype=__lowerCAmelCase , seed=__lowerCAmelCase ) __lowerCamelCase = fake() __lowerCamelCase = fake() __lowerCamelCase = fake() return _Datasets(train=__lowerCAmelCase , validation=__lowerCAmelCase , test=__lowerCAmelCase ) if not source_url: # empty string check __lowerCamelCase = DEFAULT_SOURCE_URL __lowerCamelCase = '''train-images-idx3-ubyte.gz''' __lowerCamelCase = '''train-labels-idx1-ubyte.gz''' __lowerCamelCase = '''t10k-images-idx3-ubyte.gz''' __lowerCamelCase = '''t10k-labels-idx1-ubyte.gz''' __lowerCamelCase = _maybe_download( __lowerCAmelCase , __lowerCAmelCase , source_url + train_images_file ) with gfile.Open(__lowerCAmelCase , '''rb''' ) as f: __lowerCamelCase = _extract_images(__lowerCAmelCase ) __lowerCamelCase = _maybe_download( __lowerCAmelCase , __lowerCAmelCase , source_url + train_labels_file ) with gfile.Open(__lowerCAmelCase , '''rb''' ) as f: __lowerCamelCase = _extract_labels(__lowerCAmelCase , one_hot=__lowerCAmelCase ) __lowerCamelCase = _maybe_download( __lowerCAmelCase , __lowerCAmelCase , source_url + test_images_file ) with gfile.Open(__lowerCAmelCase , '''rb''' ) as f: __lowerCamelCase = _extract_images(__lowerCAmelCase ) __lowerCamelCase = _maybe_download( __lowerCAmelCase , __lowerCAmelCase , source_url + test_labels_file ) with gfile.Open(__lowerCAmelCase , '''rb''' ) as f: __lowerCamelCase = _extract_labels(__lowerCAmelCase , one_hot=__lowerCAmelCase ) if not 0 <= validation_size <= len(__lowerCAmelCase ): __lowerCamelCase = ( '''Validation size should be between 0 and ''' f'''{len(__lowerCAmelCase )}. Received: {validation_size}.''' ) raise ValueError(__lowerCAmelCase ) __lowerCamelCase = train_images[:validation_size] __lowerCamelCase = train_labels[:validation_size] __lowerCamelCase = train_images[validation_size:] __lowerCamelCase = train_labels[validation_size:] __lowerCamelCase = {'''dtype''': dtype, '''reshape''': reshape, '''seed''': seed} __lowerCamelCase = _DataSet(__lowerCAmelCase , __lowerCAmelCase , **__lowerCAmelCase ) __lowerCamelCase = _DataSet(__lowerCAmelCase , __lowerCAmelCase , **__lowerCAmelCase ) __lowerCamelCase = _DataSet(__lowerCAmelCase , __lowerCAmelCase , **__lowerCAmelCase ) return _Datasets(train=__lowerCAmelCase , validation=__lowerCAmelCase , test=__lowerCAmelCase )
339
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_squeezebert import SqueezeBertTokenizer SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Dict = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "vocab_file": { "squeezebert/squeezebert-uncased": ( "https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt" ), "squeezebert/squeezebert-mnli": "https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt", "squeezebert/squeezebert-mnli-headless": ( "https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt" ), }, "tokenizer_file": { "squeezebert/squeezebert-uncased": ( "https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/tokenizer.json" ), "squeezebert/squeezebert-mnli": ( "https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/tokenizer.json" ), "squeezebert/squeezebert-mnli-headless": ( "https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/tokenizer.json" ), }, } SCREAMING_SNAKE_CASE__ : List[Any] = { "squeezebert/squeezebert-uncased": 512, "squeezebert/squeezebert-mnli": 512, "squeezebert/squeezebert-mnli-headless": 512, } SCREAMING_SNAKE_CASE__ : Dict = { "squeezebert/squeezebert-uncased": {"do_lower_case": True}, "squeezebert/squeezebert-mnli": {"do_lower_case": True}, "squeezebert/squeezebert-mnli-headless": {"do_lower_case": True}, } class lowerCAmelCase__ ( __lowercase ): a__ : Optional[int] = VOCAB_FILES_NAMES a__ : Any = PRETRAINED_VOCAB_FILES_MAP a__ : Union[str, Any] = PRETRAINED_INIT_CONFIGURATION a__ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ : Optional[Any] = SqueezeBertTokenizer def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[UNK]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[PAD]" , SCREAMING_SNAKE_CASE__ : Tuple="[CLS]" , SCREAMING_SNAKE_CASE__ : str="[MASK]" , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : int=None , **SCREAMING_SNAKE_CASE__ : Dict , ) -> Optional[Any]: super().__init__( SCREAMING_SNAKE_CASE__ , tokenizer_file=SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , tokenize_chinese_chars=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = 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 ): __lowerCamelCase = getattr(SCREAMING_SNAKE_CASE__ , normalizer_state.pop('''type''' ) ) __lowerCamelCase = do_lower_case __lowerCamelCase = strip_accents __lowerCamelCase = tokenize_chinese_chars __lowerCamelCase = normalizer_class(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = do_lower_case def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[str]=None ) -> str: __lowerCamelCase = [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 : Tuple , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: __lowerCamelCase = [self.sep_token_id] __lowerCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __A ( self : int , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: __lowerCamelCase = self._tokenizer.model.save(SCREAMING_SNAKE_CASE__ , name=SCREAMING_SNAKE_CASE__ ) return tuple(SCREAMING_SNAKE_CASE__ )
369
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_squeezebert import SqueezeBertTokenizer SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Dict = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "vocab_file": { "squeezebert/squeezebert-uncased": ( "https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt" ), "squeezebert/squeezebert-mnli": "https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt", "squeezebert/squeezebert-mnli-headless": ( "https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt" ), }, "tokenizer_file": { "squeezebert/squeezebert-uncased": ( "https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/tokenizer.json" ), "squeezebert/squeezebert-mnli": ( "https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/tokenizer.json" ), "squeezebert/squeezebert-mnli-headless": ( "https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/tokenizer.json" ), }, } SCREAMING_SNAKE_CASE__ : List[Any] = { "squeezebert/squeezebert-uncased": 512, "squeezebert/squeezebert-mnli": 512, "squeezebert/squeezebert-mnli-headless": 512, } SCREAMING_SNAKE_CASE__ : Dict = { "squeezebert/squeezebert-uncased": {"do_lower_case": True}, "squeezebert/squeezebert-mnli": {"do_lower_case": True}, "squeezebert/squeezebert-mnli-headless": {"do_lower_case": True}, } class lowerCAmelCase__ ( __lowercase ): a__ : Optional[int] = VOCAB_FILES_NAMES a__ : Any = PRETRAINED_VOCAB_FILES_MAP a__ : Union[str, Any] = PRETRAINED_INIT_CONFIGURATION a__ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ : Optional[Any] = SqueezeBertTokenizer def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[UNK]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[PAD]" , SCREAMING_SNAKE_CASE__ : Tuple="[CLS]" , SCREAMING_SNAKE_CASE__ : str="[MASK]" , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : int=None , **SCREAMING_SNAKE_CASE__ : Dict , ) -> Optional[Any]: super().__init__( SCREAMING_SNAKE_CASE__ , tokenizer_file=SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , tokenize_chinese_chars=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = 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 ): __lowerCamelCase = getattr(SCREAMING_SNAKE_CASE__ , normalizer_state.pop('''type''' ) ) __lowerCamelCase = do_lower_case __lowerCamelCase = strip_accents __lowerCamelCase = tokenize_chinese_chars __lowerCamelCase = normalizer_class(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = do_lower_case def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[str]=None ) -> str: __lowerCamelCase = [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 : Tuple , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: __lowerCamelCase = [self.sep_token_id] __lowerCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __A ( self : int , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: __lowerCamelCase = self._tokenizer.model.save(SCREAMING_SNAKE_CASE__ , name=SCREAMING_SNAKE_CASE__ ) return tuple(SCREAMING_SNAKE_CASE__ )
339
0
from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class lowerCAmelCase__ ( __lowercase , __lowercase , __lowercase ): a__ : Optional[Any] = [r"""h\.\d+\.attn\.bias""", r"""h\.\d+\.attn\.masked_bias"""] @register_to_config def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : int = 5_02_57 , SCREAMING_SNAKE_CASE__ : int = 10_24 , SCREAMING_SNAKE_CASE__ : int = 7_68 , SCREAMING_SNAKE_CASE__ : int = 12 , SCREAMING_SNAKE_CASE__ : int = 12 , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : str = "gelu_new" , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 1e-5 , SCREAMING_SNAKE_CASE__ : float = 0.02 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , ) -> List[Any]: super().__init__() __lowerCamelCase = prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( f'''`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and''' f''' `n_embd`: {n_embd} are not equal.''' ) __lowerCamelCase = prefix_inner_dim __lowerCamelCase = prefix_hidden_dim __lowerCamelCase = ( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) __lowerCamelCase = ( nn.Linear(self.prefix_hidden_dim , SCREAMING_SNAKE_CASE__ ) if self.prefix_hidden_dim is not None else nn.Identity() ) __lowerCamelCase = GPTaConfig( vocab_size=SCREAMING_SNAKE_CASE__ , n_positions=SCREAMING_SNAKE_CASE__ , n_embd=SCREAMING_SNAKE_CASE__ , n_layer=SCREAMING_SNAKE_CASE__ , n_head=SCREAMING_SNAKE_CASE__ , n_inner=SCREAMING_SNAKE_CASE__ , activation_function=SCREAMING_SNAKE_CASE__ , resid_pdrop=SCREAMING_SNAKE_CASE__ , embd_pdrop=SCREAMING_SNAKE_CASE__ , attn_pdrop=SCREAMING_SNAKE_CASE__ , layer_norm_epsilon=SCREAMING_SNAKE_CASE__ , initializer_range=SCREAMING_SNAKE_CASE__ , scale_attn_weights=SCREAMING_SNAKE_CASE__ , use_cache=SCREAMING_SNAKE_CASE__ , scale_attn_by_inverse_layer_idx=SCREAMING_SNAKE_CASE__ , reorder_and_upcast_attn=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = GPTaLMHeadModel(SCREAMING_SNAKE_CASE__ ) def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : torch.Tensor , SCREAMING_SNAKE_CASE__ : torch.Tensor , SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None , SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None , ) -> Optional[Any]: __lowerCamelCase = self.transformer.transformer.wte(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.encode_prefix(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.decode_prefix(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: __lowerCamelCase = self.get_dummy_token(input_ids.shape[0] , input_ids.device ) __lowerCamelCase = torch.cat((dummy_token, input_ids) , dim=1 ) __lowerCamelCase = self.transformer(inputs_embeds=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def __A ( self : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : torch.device ) -> torch.Tensor: return torch.zeros(SCREAMING_SNAKE_CASE__ , self.prefix_length , dtype=torch.intaa , device=SCREAMING_SNAKE_CASE__ ) def __A ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Tuple: return self.encode_prefix(SCREAMING_SNAKE_CASE__ ) @torch.no_grad() def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> int: __lowerCamelCase = torch.split(SCREAMING_SNAKE_CASE__ , 1 , dim=0 ) __lowerCamelCase = [] __lowerCamelCase = [] for feature in features: __lowerCamelCase = self.decode_prefix(feature.to(SCREAMING_SNAKE_CASE__ ) ) # back to the clip feature # Only support beam search for now __lowerCamelCase , __lowerCamelCase = self.generate_beam( input_embeds=SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) __lowerCamelCase = torch.stack(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = torch.stack(SCREAMING_SNAKE_CASE__ ) return generated_tokens, generated_seq_lengths @torch.no_grad() def __A ( self : str , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : Tuple=None , SCREAMING_SNAKE_CASE__ : int = 5 , SCREAMING_SNAKE_CASE__ : int = 67 , SCREAMING_SNAKE_CASE__ : float = 1.0 , SCREAMING_SNAKE_CASE__ : Optional[int] = None , ) -> Union[str, Any]: __lowerCamelCase = eos_token_id __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = torch.ones(SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , dtype=torch.int ) __lowerCamelCase = torch.zeros(SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , dtype=torch.bool ) if input_embeds is not None: __lowerCamelCase = input_embeds else: __lowerCamelCase = self.transformer.transformer.wte(SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = self.transformer(inputs_embeds=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = outputs.logits __lowerCamelCase = logits[:, -1, :] / (temperature if temperature > 0 else 1.0) __lowerCamelCase = logits.softmax(-1 ).log() if scores is None: __lowerCamelCase , __lowerCamelCase = logits.topk(SCREAMING_SNAKE_CASE__ , -1 ) __lowerCamelCase = generated.expand(SCREAMING_SNAKE_CASE__ , *generated.shape[1:] ) __lowerCamelCase , __lowerCamelCase = next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: __lowerCamelCase = next_tokens else: __lowerCamelCase = tokens.expand(SCREAMING_SNAKE_CASE__ , *tokens.shape[1:] ) __lowerCamelCase = torch.cat((tokens, next_tokens) , dim=1 ) else: __lowerCamelCase = -float(np.inf ) __lowerCamelCase = 0 __lowerCamelCase = scores[:, None] + logits seq_lengths[~is_stopped] += 1 __lowerCamelCase = scores_sum / seq_lengths[:, None] __lowerCamelCase , __lowerCamelCase = scores_sum_average.view(-1 ).topk(SCREAMING_SNAKE_CASE__ , -1 ) __lowerCamelCase = next_tokens // scores_sum.shape[1] __lowerCamelCase = seq_lengths[next_tokens_source] __lowerCamelCase = next_tokens % scores_sum.shape[1] __lowerCamelCase = next_tokens.unsqueeze(1 ) __lowerCamelCase = tokens[next_tokens_source] __lowerCamelCase = torch.cat((tokens, next_tokens) , dim=1 ) __lowerCamelCase = generated[next_tokens_source] __lowerCamelCase = scores_sum_average * seq_lengths __lowerCamelCase = is_stopped[next_tokens_source] __lowerCamelCase = self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) __lowerCamelCase = torch.cat((generated, next_token_embed) , dim=1 ) __lowerCamelCase = is_stopped + next_tokens.eq(SCREAMING_SNAKE_CASE__ ).squeeze() if is_stopped.all(): break __lowerCamelCase = scores / seq_lengths __lowerCamelCase = scores.argsort(descending=SCREAMING_SNAKE_CASE__ ) # tokens tensors are already padded to max_seq_length __lowerCamelCase = [tokens[i] for i in order] __lowerCamelCase = torch.stack(SCREAMING_SNAKE_CASE__ , dim=0 ) __lowerCamelCase = torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
370
from __future__ import annotations def __magic_name__ ( __lowerCAmelCase : list[int] ) -> bool: return len(set(__lowerCAmelCase ) ) == len(__lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
339
0
def __magic_name__ ( __lowerCAmelCase : int ) -> int: if divisor % 5 == 0 or divisor % 2 == 0: return 0 __lowerCamelCase = 1 __lowerCamelCase = 1 while repunit: __lowerCamelCase = (10 * repunit + 1) % divisor repunit_index += 1 return repunit_index def __magic_name__ ( __lowerCAmelCase : int = 100_0000 ) -> int: __lowerCamelCase = limit - 1 if divisor % 2 == 0: divisor += 1 while least_divisible_repunit(__lowerCAmelCase ) <= limit: divisor += 2 return divisor if __name__ == "__main__": print(F'{solution() = }')
371
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) SCREAMING_SNAKE_CASE__ : Dict = { "configuration_falcon": ["FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP", "FalconConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Tuple = [ "FALCON_PRETRAINED_MODEL_ARCHIVE_LIST", "FalconForCausalLM", "FalconModel", "FalconPreTrainedModel", "FalconForSequenceClassification", "FalconForTokenClassification", "FalconForQuestionAnswering", ] if TYPE_CHECKING: from .configuration_falcon import FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP, FalconConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_falcon import ( FALCON_PRETRAINED_MODEL_ARCHIVE_LIST, FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, FalconPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
339
0
from collections import namedtuple import requests from lxml import html # type: ignore SCREAMING_SNAKE_CASE__ = namedtuple("covid_data", "cases deaths recovered") def __magic_name__ ( __lowerCAmelCase : str = "https://www.worldometers.info/coronavirus/" ) -> covid_data: __lowerCamelCase = '''//div[@class = "maincounter-number"]/span/text()''' return covid_data(*html.fromstring(requests.get(__lowerCAmelCase ).content ).xpath(__lowerCAmelCase ) ) SCREAMING_SNAKE_CASE__ = "Total COVID-19 cases in the world: {}\nTotal deaths due to COVID-19 in the world: {}\nTotal COVID-19 patients recovered in the world: {}" print(fmt.format(*covid_stats()))
350
def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int ) -> int: return abs(__lowerCAmelCase ) if a == 0 else greatest_common_divisor(b % a , __lowerCAmelCase ) def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int ) -> int: while y: # --> when y=0 then loop will terminate and return x as final GCD. __lowerCamelCase , __lowerCamelCase = y, x % y return abs(__lowerCAmelCase ) def __magic_name__ ( ) -> Tuple: try: __lowerCamelCase = input('''Enter two integers separated by comma (,): ''' ).split(''',''' ) __lowerCamelCase = int(nums[0] ) __lowerCamelCase = int(nums[1] ) print( f'''greatest_common_divisor({num_a}, {num_a}) = ''' f'''{greatest_common_divisor(__lowerCAmelCase , __lowerCAmelCase )}''' ) print(f'''By iterative gcd({num_a}, {num_a}) = {gcd_by_iterative(__lowerCAmelCase , __lowerCAmelCase )}''' ) except (IndexError, UnboundLocalError, ValueError): print('''Wrong input''' ) if __name__ == "__main__": main()
339
0
"""simple docstring""" SCREAMING_SNAKE_CASE__ : str = { "Pillow": "Pillow", "accelerate": "accelerate>=0.11.0", "compel": "compel==0.1.8", "black": "black~=23.1", "datasets": "datasets", "filelock": "filelock", "flax": "flax>=0.4.1", "hf-doc-builder": "hf-doc-builder>=0.3.0", "huggingface-hub": "huggingface-hub>=0.13.2", "requests-mock": "requests-mock==1.10.0", "importlib_metadata": "importlib_metadata", "invisible-watermark": "invisible-watermark", "isort": "isort>=5.5.4", "jax": "jax>=0.2.8,!=0.3.2", "jaxlib": "jaxlib>=0.1.65", "Jinja2": "Jinja2", "k-diffusion": "k-diffusion>=0.0.12", "torchsde": "torchsde", "note_seq": "note_seq", "librosa": "librosa", "numpy": "numpy", "omegaconf": "omegaconf", "parameterized": "parameterized", "protobuf": "protobuf>=3.20.3,<4", "pytest": "pytest", "pytest-timeout": "pytest-timeout", "pytest-xdist": "pytest-xdist", "ruff": "ruff>=0.0.241", "safetensors": "safetensors", "sentencepiece": "sentencepiece>=0.1.91,!=0.1.92", "scipy": "scipy", "onnx": "onnx", "regex": "regex!=2019.12.17", "requests": "requests", "tensorboard": "tensorboard", "torch": "torch>=1.4", "torchvision": "torchvision", "transformers": "transformers>=4.25.1", "urllib3": "urllib3<=2.0.0", }
351
import unittest from transformers import is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, require_torch, slow if is_flax_available(): import optax from flax.training.common_utils import onehot from transformers import AutoTokenizer, FlaxMTaForConditionalGeneration from transformers.models.ta.modeling_flax_ta import shift_tokens_right @require_torch @require_sentencepiece @require_tokenizers @require_flax class lowerCAmelCase__ ( unittest.TestCase ): @slow def __A ( self : Optional[int] ) -> Union[str, Any]: __lowerCamelCase = FlaxMTaForConditionalGeneration.from_pretrained('''google/mt5-small''' ) __lowerCamelCase = AutoTokenizer.from_pretrained('''google/mt5-small''' ) __lowerCamelCase = tokenizer('''Hello there''' , return_tensors='''np''' ).input_ids __lowerCamelCase = tokenizer('''Hi I am''' , return_tensors='''np''' ).input_ids __lowerCamelCase = shift_tokens_right(SCREAMING_SNAKE_CASE__ , model.config.pad_token_id , model.config.decoder_start_token_id ) __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ , decoder_input_ids=SCREAMING_SNAKE_CASE__ ).logits __lowerCamelCase = optax.softmax_cross_entropy(SCREAMING_SNAKE_CASE__ , onehot(SCREAMING_SNAKE_CASE__ , logits.shape[-1] ) ).mean() __lowerCamelCase = -(labels.shape[-1] * loss.item()) __lowerCamelCase = -84.9127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1e-4 )
339
0
import shutil import tempfile import unittest from unittest.mock import patch from transformers import ( DefaultFlowCallback, IntervalStrategy, PrinterCallback, ProgressCallback, Trainer, TrainerCallback, TrainingArguments, is_torch_available, ) from transformers.testing_utils import require_torch if is_torch_available(): from transformers.trainer import DEFAULT_CALLBACKS from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel class lowerCAmelCase__ ( __lowercase ): def __init__( self : str ) -> List[str]: __lowerCamelCase = [] def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : str ) -> Optional[int]: self.events.append('''on_init_end''' ) def __A ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : Tuple ) -> Dict: self.events.append('''on_train_begin''' ) def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict , **SCREAMING_SNAKE_CASE__ : Dict ) -> Union[str, Any]: self.events.append('''on_train_end''' ) def __A ( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : int ) -> Tuple: self.events.append('''on_epoch_begin''' ) def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , **SCREAMING_SNAKE_CASE__ : Dict ) -> Optional[int]: self.events.append('''on_epoch_end''' ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Dict , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Optional[Any]: self.events.append('''on_step_begin''' ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : str ) -> List[str]: self.events.append('''on_step_end''' ) def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Dict: self.events.append('''on_evaluate''' ) def __A ( self : Any , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: self.events.append('''on_predict''' ) def __A ( self : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : int ) -> Tuple: self.events.append('''on_save''' ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Any , **SCREAMING_SNAKE_CASE__ : int ) -> List[Any]: self.events.append('''on_log''' ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Union[str, Any]: self.events.append('''on_prediction_step''' ) @require_torch class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Dict ) -> int: __lowerCamelCase = tempfile.mkdtemp() def __A ( self : Tuple ) -> List[Any]: shutil.rmtree(self.output_dir ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : str=0 , SCREAMING_SNAKE_CASE__ : Dict=0 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=64 , SCREAMING_SNAKE_CASE__ : Optional[Any]=64 , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : int=False , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[Any]: # disable_tqdm in TrainingArguments has a flaky default since it depends on the level of logging. We make sure # its set to False since the tests later on depend on its value. __lowerCamelCase = RegressionDataset(length=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = RegressionDataset(length=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = RegressionModelConfig(a=SCREAMING_SNAKE_CASE__ , b=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = RegressionPreTrainedModel(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = TrainingArguments(self.output_dir , disable_tqdm=SCREAMING_SNAKE_CASE__ , report_to=[] , **SCREAMING_SNAKE_CASE__ ) return Trainer( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , train_dataset=SCREAMING_SNAKE_CASE__ , eval_dataset=SCREAMING_SNAKE_CASE__ , callbacks=SCREAMING_SNAKE_CASE__ , ) def __A ( self : Any , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict ) -> Any: self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) ) # Order doesn't matter __lowerCamelCase = sorted(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : cb.__name__ if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cb.__class__.__name__ ) __lowerCamelCase = sorted(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : cb.__name__ if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cb.__class__.__name__ ) for cba, cba in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(SCREAMING_SNAKE_CASE__ , cba.__class__ ) elif not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(cba.__class__ , SCREAMING_SNAKE_CASE__ ) else: self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[str]: __lowerCamelCase = ['''on_init_end''', '''on_train_begin'''] __lowerCamelCase = 0 __lowerCamelCase = len(trainer.get_eval_dataloader() ) __lowerCamelCase = ['''on_prediction_step'''] * len(trainer.get_eval_dataloader() ) + ['''on_log''', '''on_evaluate'''] for _ in range(trainer.state.num_train_epochs ): expected_events.append('''on_epoch_begin''' ) for _ in range(SCREAMING_SNAKE_CASE__ ): step += 1 expected_events += ["on_step_begin", "on_step_end"] if step % trainer.args.logging_steps == 0: expected_events.append('''on_log''' ) if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0: expected_events += evaluation_events.copy() if step % trainer.args.save_steps == 0: expected_events.append('''on_save''' ) expected_events.append('''on_epoch_end''' ) if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH: expected_events += evaluation_events.copy() expected_events += ["on_log", "on_train_end"] return expected_events def __A ( self : List[str] ) -> str: __lowerCamelCase = self.get_trainer() __lowerCamelCase = DEFAULT_CALLBACKS.copy() + [ProgressCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) # Callbacks passed at init are added to the default callbacks __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] ) expected_callbacks.append(SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback __lowerCamelCase = self.get_trainer(disable_tqdm=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = DEFAULT_CALLBACKS.copy() + [PrinterCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) def __A ( self : str ) -> Optional[Any]: __lowerCamelCase = DEFAULT_CALLBACKS.copy() + [ProgressCallback] __lowerCamelCase = self.get_trainer() # We can add, pop, or remove by class name trainer.remove_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.remove(SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_trainer() __lowerCamelCase = trainer.pop_callback(SCREAMING_SNAKE_CASE__ ) self.assertEqual(cb.__class__ , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) trainer.add_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.insert(0 , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) # We can also add, pop, or remove by instance __lowerCamelCase = self.get_trainer() __lowerCamelCase = trainer.callback_handler.callbacks[0] trainer.remove_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.remove(SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_trainer() __lowerCamelCase = trainer.callback_handler.callbacks[0] __lowerCamelCase = trainer.pop_callback(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) trainer.add_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.insert(0 , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) def __A ( self : List[str] ) -> Optional[int]: import warnings # XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested warnings.simplefilter(action='''ignore''' , category=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) # Independent log/save/eval __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , logging_steps=5 ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , save_steps=5 ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , eval_steps=5 , evaluation_strategy='''steps''' ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , evaluation_strategy='''epoch''' ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) # A bit of everything __lowerCamelCase = self.get_trainer( callbacks=[MyTestTrainerCallback] , logging_steps=3 , save_steps=10 , eval_steps=5 , evaluation_strategy='''steps''' , ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) # warning should be emitted for duplicated callbacks with patch('''transformers.trainer_callback.logger.warning''' ) as warn_mock: __lowerCamelCase = self.get_trainer( callbacks=[MyTestTrainerCallback, MyTestTrainerCallback] , ) assert str(SCREAMING_SNAKE_CASE__ ) in warn_mock.call_args[0][0]
352
import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer SCREAMING_SNAKE_CASE__ : Optional[int] = "bart" SCREAMING_SNAKE_CASE__ : Dict = True @st.cache(allow_output_mutation=__lowerCAmelCase ) def __magic_name__ ( ) -> str: if LOAD_DENSE_INDEX: __lowerCamelCase = AutoTokenizer.from_pretrained('''yjernite/retribert-base-uncased''' ) __lowerCamelCase = AutoModel.from_pretrained('''yjernite/retribert-base-uncased''' ).to('''cuda:0''' ) __lowerCamelCase = qar_model.eval() else: __lowerCamelCase , __lowerCamelCase = (None, None) if MODEL_TYPE == "bart": __lowerCamelCase = AutoTokenizer.from_pretrained('''yjernite/bart_eli5''' ) __lowerCamelCase = AutoModelForSeqaSeqLM.from_pretrained('''yjernite/bart_eli5''' ).to('''cuda:0''' ) __lowerCamelCase = torch.load('''seq2seq_models/eli5_bart_model_blm_2.pth''' ) sas_model.load_state_dict(save_dict['''model'''] ) __lowerCamelCase = sas_model.eval() else: __lowerCamelCase , __lowerCamelCase = make_qa_sas_model( model_name='''t5-small''' , from_file='''seq2seq_models/eli5_t5_model_1024_4.pth''' , device='''cuda:0''' ) return (qar_tokenizer, qar_model, sas_tokenizer, sas_model) @st.cache(allow_output_mutation=__lowerCAmelCase ) def __magic_name__ ( ) -> Optional[int]: if LOAD_DENSE_INDEX: __lowerCamelCase = faiss.StandardGpuResources() __lowerCamelCase = datasets.load_dataset(path='''wiki_snippets''' , name='''wiki40b_en_100_0''' )['''train'''] __lowerCamelCase = np.memmap( '''wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat''' , dtype='''float32''' , mode='''r''' , shape=(wikiaab_passages.num_rows, 128) , ) __lowerCamelCase = faiss.IndexFlatIP(128 ) __lowerCamelCase = faiss.index_cpu_to_gpu(__lowerCAmelCase , 1 , __lowerCAmelCase ) wikiaab_gpu_index_flat.add(__lowerCAmelCase ) # TODO fix for larger GPU else: __lowerCamelCase , __lowerCamelCase = (None, None) __lowerCamelCase = Elasticsearch([{'''host''': '''localhost''', '''port''': '''9200'''}] ) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=__lowerCAmelCase ) def __magic_name__ ( ) -> List[str]: __lowerCamelCase = datasets.load_dataset('''eli5''' , name='''LFQA_reddit''' ) __lowerCamelCase = elia['''train_eli5'''] __lowerCamelCase = np.memmap( '''eli5_questions_reps.dat''' , dtype='''float32''' , mode='''r''' , shape=(elia_train.num_rows, 128) ) __lowerCamelCase = faiss.IndexFlatIP(128 ) eli5_train_q_index.add(__lowerCAmelCase ) return (elia_train, eli5_train_q_index) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = load_indexes() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = load_models() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = load_train_data() def __magic_name__ ( __lowerCAmelCase : Dict , __lowerCAmelCase : List[str]=10 ) -> List[str]: __lowerCamelCase = embed_questions_for_retrieval([question] , __lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase , __lowerCamelCase = eli5_train_q_index.search(__lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase = [elia_train[int(__lowerCAmelCase )] for i in I[0]] return nn_examples def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : Dict="wiki40b" , __lowerCAmelCase : Any="dense" , __lowerCAmelCase : Dict=10 ) -> Union[str, Any]: if source == "none": __lowerCamelCase , __lowerCamelCase = (''' <P> '''.join(['''''' for _ in range(11 )] ).strip(), []) else: if method == "dense": __lowerCamelCase , __lowerCamelCase = query_qa_dense_index( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) else: __lowerCamelCase , __lowerCamelCase = query_es_index( __lowerCAmelCase , __lowerCAmelCase , index_name='''english_wiki40b_snippets_100w''' , n_results=__lowerCAmelCase , ) __lowerCamelCase = [ (res['''article_title'''], res['''section_title'''].strip(), res['''score'''], res['''passage_text''']) for res in hit_lst ] __lowerCamelCase = '''question: {} context: {}'''.format(__lowerCAmelCase , __lowerCAmelCase ) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda __lowerCAmelCase : None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda __lowerCAmelCase : None), } ) def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : Dict , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : str=64 , __lowerCAmelCase : Dict=256 , __lowerCAmelCase : Union[str, Any]=False , __lowerCAmelCase : Optional[int]=2 , __lowerCAmelCase : Optional[Any]=0.95 , __lowerCAmelCase : List[Any]=0.8 ) -> Any: with torch.no_grad(): __lowerCamelCase = qa_sas_generate( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , num_answers=1 , num_beams=__lowerCAmelCase , min_len=__lowerCAmelCase , max_len=__lowerCAmelCase , do_sample=__lowerCAmelCase , temp=__lowerCAmelCase , top_p=__lowerCAmelCase , top_k=__lowerCAmelCase , max_input_length=1024 , device='''cuda:0''' , )[0] return (answer, support_list) st.title("Long Form Question Answering with ELI5") # Start sidebar SCREAMING_SNAKE_CASE__ : List[str] = "<img src='https://huggingface.co/front/assets/huggingface_logo.svg'>" SCREAMING_SNAKE_CASE__ : Dict = "\n<html>\n <head>\n <style>\n .img-container {\n padding-left: 90px;\n padding-right: 90px;\n padding-top: 50px;\n padding-bottom: 50px;\n background-color: #f0f3f9;\n }\n </style>\n </head>\n <body>\n <span class=\"img-container\"> <!-- Inline parent element -->\n %s\n </span>\n </body>\n</html>\n" % ( header_html, ) st.sidebar.markdown( header_full, unsafe_allow_html=True, ) # Long Form QA with ELI5 and Wikipedia SCREAMING_SNAKE_CASE__ : int = "\nThis demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).\nFirst, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,\na pre-processed fixed snapshot of Wikipedia.\n" st.sidebar.markdown(description, unsafe_allow_html=True) SCREAMING_SNAKE_CASE__ : str = [ "Answer the question", "View the retrieved document only", "View the most similar ELI5 question and answer", "Show me everything, please!", ] SCREAMING_SNAKE_CASE__ : Optional[int] = st.sidebar.checkbox("Demo options") if demo_options: SCREAMING_SNAKE_CASE__ : Optional[int] = st.sidebar.selectbox( "", action_list, index=3, ) SCREAMING_SNAKE_CASE__ : Optional[Any] = action_list.index(action_st) SCREAMING_SNAKE_CASE__ : int = st.sidebar.selectbox( "", ["Show full text of passages", "Show passage section titles"], index=0, ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = show_type == "Show full text of passages" else: SCREAMING_SNAKE_CASE__ : Any = 3 SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : Union[str, Any] = st.sidebar.checkbox("Retrieval options") if retrieval_options: SCREAMING_SNAKE_CASE__ : Tuple = "\n ### Information retriever options\n\n The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding\n trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.\n The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.\n " st.sidebar.markdown(retriever_info) SCREAMING_SNAKE_CASE__ : Union[str, Any] = st.sidebar.selectbox("Which Wikipedia format should the model use?", ["wiki40b", "none"]) SCREAMING_SNAKE_CASE__ : int = st.sidebar.selectbox("Which Wikipedia indexer should the model use?", ["dense", "sparse", "mixed"]) else: SCREAMING_SNAKE_CASE__ : List[str] = "wiki40b" SCREAMING_SNAKE_CASE__ : Optional[Any] = "dense" SCREAMING_SNAKE_CASE__ : str = "beam" SCREAMING_SNAKE_CASE__ : List[Any] = 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = 64 SCREAMING_SNAKE_CASE__ : List[Any] = 256 SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : List[str] = st.sidebar.checkbox("Generation options") if generate_options: SCREAMING_SNAKE_CASE__ : Dict = "\n ### Answer generation options\n\n The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)\n weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with\n **beam** search, or **sample** from the decoder's output probabilities.\n " st.sidebar.markdown(generate_info) SCREAMING_SNAKE_CASE__ : List[str] = st.sidebar.selectbox("Would you like to use beam search or sample an answer?", ["beam", "sampled"]) SCREAMING_SNAKE_CASE__ : Any = st.sidebar.slider( "Minimum generation length", min_value=8, max_value=256, value=64, step=8, format=None, key=None ) SCREAMING_SNAKE_CASE__ : str = st.sidebar.slider( "Maximum generation length", min_value=64, max_value=512, value=256, step=16, format=None, key=None ) if sampled == "beam": SCREAMING_SNAKE_CASE__ : Union[str, Any] = st.sidebar.slider("Beam size", min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: SCREAMING_SNAKE_CASE__ : Any = st.sidebar.slider( "Nucleus sampling p", min_value=0.1, max_value=1.0, value=0.9_5, step=0.0_1, format=None, key=None ) SCREAMING_SNAKE_CASE__ : Dict = st.sidebar.slider( "Temperature", min_value=0.1, max_value=1.0, value=0.7, step=0.0_1, format=None, key=None ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = None # start main text SCREAMING_SNAKE_CASE__ : Any = [ "<MY QUESTION>", "How do people make chocolate?", "Why do we get a fever when we are sick?", "How can different animals perceive different colors?", "What is natural language processing?", "What's the best way to treat a sunburn?", "What exactly are vitamins ?", "How does nuclear energy provide electricity?", "What's the difference between viruses and bacteria?", "Why are flutes classified as woodwinds when most of them are made out of metal ?", "Why do people like drinking coffee even though it tastes so bad?", "What happens when wine ages? How does it make the wine taste better?", "If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?", "How can we set a date to the beginning or end of an artistic period? Doesn't the change happen gradually?", "How does New Zealand have so many large bird predators?", ] SCREAMING_SNAKE_CASE__ : List[str] = st.selectbox( "What would you like to ask? ---- select <MY QUESTION> to enter a new query", questions_list, index=1, ) if question_s == "<MY QUESTION>": SCREAMING_SNAKE_CASE__ : Union[str, Any] = st.text_input("Enter your question here:", "") else: SCREAMING_SNAKE_CASE__ : str = question_s if st.button("Show me!"): if action in [0, 1, 3]: if index_type == "mixed": SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = make_support(question, source=wiki_source, method="dense", n_results=10) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = make_support(question, source=wiki_source, method="sparse", n_results=10) SCREAMING_SNAKE_CASE__ : int = [] for res_d, res_s in zip(support_list_dense, support_list_sparse): if tuple(res_d) not in support_list: support_list += [tuple(res_d)] if tuple(res_s) not in support_list: support_list += [tuple(res_s)] SCREAMING_SNAKE_CASE__ : Optional[Any] = support_list[:10] SCREAMING_SNAKE_CASE__ : Tuple = "<P> " + " <P> ".join([res[-1] for res in support_list]) else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = answer_question( question_doc, sas_model, sas_tokenizer, min_len=min_len, max_len=int(max_len), sampling=(sampled == "sampled"), n_beams=n_beams, top_p=top_p, temp=temp, ) st.markdown("### The model generated answer is:") st.write(answer) if action in [0, 1, 3] and wiki_source != "none": st.markdown("--- \n ### The model is drawing information from the following Wikipedia passages:") for i, res in enumerate(support_list): SCREAMING_SNAKE_CASE__ : Optional[int] = "https://en.wikipedia.org/wiki/{}".format(res[0].replace(" ", "_")) SCREAMING_SNAKE_CASE__ : Tuple = res[1].strip() if sec_titles == "": SCREAMING_SNAKE_CASE__ : Union[str, Any] = "[{}]({})".format(res[0], wiki_url) else: SCREAMING_SNAKE_CASE__ : Dict = sec_titles.split(" & ") SCREAMING_SNAKE_CASE__ : int = " & ".join( ["[{}]({}#{})".format(sec.strip(), wiki_url, sec.strip().replace(" ", "_")) for sec in sec_list] ) st.markdown( "{0:02d} - **Article**: {1:<18} <br> _Section_: {2}".format(i + 1, res[0], sections), unsafe_allow_html=True, ) if show_passages: st.write( "> <span style=\"font-family:arial; font-size:10pt;\">" + res[-1] + "</span>", unsafe_allow_html=True ) if action in [2, 3]: SCREAMING_SNAKE_CASE__ : Any = find_nearest_training(question) SCREAMING_SNAKE_CASE__ : List[Any] = nn_train_list[0] st.markdown( "--- \n ### The most similar question in the ELI5 training set was: \n\n {}".format(train_exple["title"]) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ "{}. {}".format(i + 1, " \n".join([line.strip() for line in ans.split("\n") if line.strip() != ""])) for i, (ans, sc) in enumerate(zip(train_exple["answers"]["text"], train_exple["answers"]["score"])) if i == 0 or sc > 2 ] st.markdown("##### Its answers were: \n\n {}".format("\n".join(answers_st))) SCREAMING_SNAKE_CASE__ : List[Any] = "\n---\n\n**Disclaimer**\n\n*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.\nEvaluating biases of such a model and ensuring factual generations are still very much open research problems.\nTherefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*\n" st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
339
0
import math import unittest def __magic_name__ ( __lowerCAmelCase : int ) -> bool: assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and ( number >= 0 ), "'number' must been an int and positive" 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(math.sqrt(__lowerCAmelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Optional[int] ) -> Tuple: self.assertTrue(is_prime(2 ) ) self.assertTrue(is_prime(3 ) ) self.assertTrue(is_prime(5 ) ) self.assertTrue(is_prime(7 ) ) self.assertTrue(is_prime(11 ) ) self.assertTrue(is_prime(13 ) ) self.assertTrue(is_prime(17 ) ) self.assertTrue(is_prime(19 ) ) self.assertTrue(is_prime(23 ) ) self.assertTrue(is_prime(29 ) ) def __A ( self : List[str] ) -> Dict: with self.assertRaises(SCREAMING_SNAKE_CASE__ ): is_prime(-19 ) self.assertFalse( is_prime(0 ) , '''Zero doesn\'t have any positive factors, primes must have exactly two.''' , ) self.assertFalse( is_prime(1 ) , '''One only has 1 positive factor, primes must have exactly two.''' , ) self.assertFalse(is_prime(2 * 2 ) ) self.assertFalse(is_prime(2 * 3 ) ) self.assertFalse(is_prime(3 * 3 ) ) self.assertFalse(is_prime(3 * 5 ) ) self.assertFalse(is_prime(3 * 5 * 7 ) ) if __name__ == "__main__": unittest.main()
353
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : List[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : str = { "facebook/xmod-base": "https://huggingface.co/facebook/xmod-base/resolve/main/config.json", "facebook/xmod-large-prenorm": "https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json", "facebook/xmod-base-13-125k": "https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json", "facebook/xmod-base-30-125k": "https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json", "facebook/xmod-base-30-195k": "https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json", "facebook/xmod-base-60-125k": "https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json", "facebook/xmod-base-60-265k": "https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json", "facebook/xmod-base-75-125k": "https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json", "facebook/xmod-base-75-269k": "https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json", } class lowerCAmelCase__ ( __lowercase ): a__ : Dict = """xmod""" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3_05_22 , SCREAMING_SNAKE_CASE__ : str=7_68 , SCREAMING_SNAKE_CASE__ : int=12 , SCREAMING_SNAKE_CASE__ : Dict=12 , SCREAMING_SNAKE_CASE__ : List[str]=30_72 , SCREAMING_SNAKE_CASE__ : List[Any]="gelu" , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : int=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=5_12 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=0.02 , SCREAMING_SNAKE_CASE__ : Optional[Any]=1e-12 , SCREAMING_SNAKE_CASE__ : List[str]=1 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0 , SCREAMING_SNAKE_CASE__ : int=2 , SCREAMING_SNAKE_CASE__ : Any="absolute" , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : Tuple=2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Dict=("en_XX",) , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , **SCREAMING_SNAKE_CASE__ : int , ) -> str: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = vocab_size __lowerCamelCase = hidden_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = hidden_act __lowerCamelCase = intermediate_size __lowerCamelCase = hidden_dropout_prob __lowerCamelCase = attention_probs_dropout_prob __lowerCamelCase = max_position_embeddings __lowerCamelCase = type_vocab_size __lowerCamelCase = initializer_range __lowerCamelCase = layer_norm_eps __lowerCamelCase = position_embedding_type __lowerCamelCase = use_cache __lowerCamelCase = classifier_dropout __lowerCamelCase = pre_norm __lowerCamelCase = adapter_reduction_factor __lowerCamelCase = adapter_layer_norm __lowerCamelCase = adapter_reuse_layer_norm __lowerCamelCase = ln_before_adapter __lowerCamelCase = list(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = default_language class lowerCAmelCase__ ( __lowercase ): @property def __A ( self : Optional[Any] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": __lowerCamelCase = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: __lowerCamelCase = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
339
0
from itertools import product from cva import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import dot, exp, mgrid, pi, ravel, square, uinta, zeros def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : Union[str, Any] ) -> Union[str, Any]: __lowerCamelCase = k_size // 2 __lowerCamelCase , __lowerCamelCase = mgrid[0 - center : k_size - center, 0 - center : k_size - center] __lowerCamelCase = 1 / (2 * pi * sigma) * exp(-(square(__lowerCAmelCase ) + square(__lowerCAmelCase )) / (2 * square(__lowerCAmelCase )) ) return g def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : int ) -> List[str]: __lowerCamelCase , __lowerCamelCase = image.shape[0], image.shape[1] # dst image height and width __lowerCamelCase = height - k_size + 1 __lowerCamelCase = width - k_size + 1 # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows __lowerCamelCase = zeros((dst_height * dst_width, k_size * k_size) ) __lowerCamelCase = 0 for i, j in product(range(__lowerCAmelCase ) , range(__lowerCAmelCase ) ): __lowerCamelCase = ravel(image[i : i + k_size, j : j + k_size] ) __lowerCamelCase = window row += 1 # turn the kernel into shape(k*k, 1) __lowerCamelCase = gen_gaussian_kernel(__lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase = ravel(__lowerCAmelCase ) # reshape and get the dst image __lowerCamelCase = dot(__lowerCAmelCase , __lowerCAmelCase ).reshape(__lowerCAmelCase , __lowerCAmelCase ).astype(__lowerCAmelCase ) return dst if __name__ == "__main__": # read original image SCREAMING_SNAKE_CASE__ : Optional[Any] = imread(r"../image_data/lena.jpg") # turn image in gray scale value SCREAMING_SNAKE_CASE__ : int = cvtColor(img, COLOR_BGR2GRAY) # get values with two different mask size SCREAMING_SNAKE_CASE__ : Optional[Any] = gaussian_filter(gray, 3, sigma=1) SCREAMING_SNAKE_CASE__ : str = gaussian_filter(gray, 5, sigma=0.8) # show result images imshow("gaussian filter with 3x3 mask", gaussianaxa) imshow("gaussian filter with 5x5 mask", gaussianaxa) waitKey()
354
from collections import namedtuple import requests from lxml import html # type: ignore SCREAMING_SNAKE_CASE__ : List[Any] = namedtuple("covid_data", "cases deaths recovered") def __magic_name__ ( __lowerCAmelCase : str = "https://www.worldometers.info/coronavirus/" ) -> covid_data: __lowerCamelCase = '''//div[@class = "maincounter-number"]/span/text()''' return covid_data(*html.fromstring(requests.get(__lowerCAmelCase ).content ).xpath(__lowerCAmelCase ) ) SCREAMING_SNAKE_CASE__ : List[str] = "Total COVID-19 cases in the world: {}\nTotal deaths due to COVID-19 in the world: {}\nTotal COVID-19 patients recovered in the world: {}" print(fmt.format(*covid_stats()))
339
0
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pathlib import Path import torch from ...utils import is_npu_available, is_xpu_available from .config_args import ClusterConfig, default_json_config_file from .config_utils import SubcommandHelpFormatter SCREAMING_SNAKE_CASE__ : Union[str, Any] = "Create a default config file for Accelerate with only a few flags set." def __magic_name__ ( __lowerCAmelCase : int="no" , __lowerCAmelCase : str = default_json_config_file , __lowerCAmelCase : bool = False ) -> int: __lowerCamelCase = Path(__lowerCAmelCase ) path.parent.mkdir(parents=__lowerCAmelCase , exist_ok=__lowerCAmelCase ) if path.exists(): print( f'''Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.''' ) return False __lowerCamelCase = mixed_precision.lower() if mixed_precision not in ["no", "fp16", "bf16", "fp8"]: raise ValueError( f'''`mixed_precision` should be one of \'no\', \'fp16\', \'bf16\', or \'fp8\'. Received {mixed_precision}''' ) __lowerCamelCase = { '''compute_environment''': '''LOCAL_MACHINE''', '''mixed_precision''': mixed_precision, } if torch.cuda.is_available(): __lowerCamelCase = torch.cuda.device_count() __lowerCamelCase = num_gpus __lowerCamelCase = False if num_gpus > 1: __lowerCamelCase = '''MULTI_GPU''' else: __lowerCamelCase = '''NO''' elif is_xpu_available() and use_xpu: __lowerCamelCase = torch.xpu.device_count() __lowerCamelCase = num_xpus __lowerCamelCase = False if num_xpus > 1: __lowerCamelCase = '''MULTI_XPU''' else: __lowerCamelCase = '''NO''' elif is_npu_available(): __lowerCamelCase = torch.npu.device_count() __lowerCamelCase = num_npus __lowerCamelCase = False if num_npus > 1: __lowerCamelCase = '''MULTI_NPU''' else: __lowerCamelCase = '''NO''' else: __lowerCamelCase = 0 __lowerCamelCase = True __lowerCamelCase = 1 __lowerCamelCase = '''NO''' __lowerCamelCase = ClusterConfig(**__lowerCAmelCase ) config.to_json_file(__lowerCAmelCase ) return path def __magic_name__ ( __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[int] ) -> Optional[int]: __lowerCamelCase = parser.add_parser('''default''' , parents=__lowerCAmelCase , help=__lowerCAmelCase , formatter_class=__lowerCAmelCase ) parser.add_argument( '''--config_file''' , default=__lowerCAmelCase , help=( '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache ''' '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ''' '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ''' '''with \'huggingface\'.''' ) , dest='''save_location''' , ) parser.add_argument( '''--mixed_precision''' , choices=['''no''', '''fp16''', '''bf16'''] , type=__lowerCAmelCase , help='''Whether or not to use mixed precision training. ''' '''Choose between FP16 and BF16 (bfloat16) training. ''' '''BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.''' , default='''no''' , ) parser.set_defaults(func=__lowerCAmelCase ) return parser def __magic_name__ ( __lowerCAmelCase : List[Any] ) -> List[str]: __lowerCamelCase = write_basic_config(args.mixed_precision , args.save_location ) if config_file: print(f'''accelerate configuration saved at {config_file}''' )
355
import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer, HfArgumentParser, MBartTokenizer, MBartTokenizerFast, set_seed, ) from transformers.trainer_utils import EvaluationStrategy, is_main_process from transformers.training_args import ParallelMode from utils import ( SeqaSeqDataCollator, SeqaSeqDataset, assert_all_frozen, build_compute_metrics_fn, check_output_dir, freeze_embeds, freeze_params, lmap, save_json, use_task_specific_params, write_txt_file, ) SCREAMING_SNAKE_CASE__ : int = logging.getLogger(__name__) @dataclass class lowerCAmelCase__ : a__ : str = field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} ) a__ : Optional[str] = field( default=__lowercase , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) a__ : Optional[str] = field( default=__lowercase , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} ) a__ : Optional[str] = field( default=__lowercase , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) a__ : bool = field(default=__lowercase , metadata={"""help""": """Whether tp freeze the encoder."""} ) a__ : bool = field(default=__lowercase , metadata={"""help""": """Whether to freeze the embeddings."""} ) @dataclass class lowerCAmelCase__ : a__ : str = field( metadata={"""help""": """The input data dir. Should contain the .tsv files (or other data files) for the task."""} ) a__ : Optional[str] = field( default="""summarization""" , metadata={"""help""": """Task name, summarization (or summarization_{dataset} for pegasus) or translation"""} , ) a__ : Optional[int] = field( default=1_024 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) a__ : Optional[int] = field( default=128 , metadata={ """help""": ( """The maximum total sequence length for target text after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) a__ : Optional[int] = field( default=142 , metadata={ """help""": ( """The maximum total sequence length for validation target text after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded. """ """This argument is also used to override the ``max_length`` param of ``model.generate``, which is used """ """during ``evaluate`` and ``predict``.""" ) } , ) a__ : Optional[int] = field( default=142 , metadata={ """help""": ( """The maximum total sequence length for test target text after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) a__ : Optional[int] = field(default=-1 , metadata={"""help""": """# training examples. -1 means use all."""} ) a__ : Optional[int] = field(default=-1 , metadata={"""help""": """# validation examples. -1 means use all."""} ) a__ : Optional[int] = field(default=-1 , metadata={"""help""": """# test examples. -1 means use all."""} ) a__ : Optional[str] = field(default=__lowercase , metadata={"""help""": """Source language id for translation."""} ) a__ : Optional[str] = field(default=__lowercase , metadata={"""help""": """Target language id for translation."""} ) a__ : Optional[int] = field(default=__lowercase , metadata={"""help""": """# num_beams to use for evaluation."""} ) a__ : bool = field( default=__lowercase , metadata={"""help""": """If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined."""} , ) def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : str , __lowerCAmelCase : int ) -> Dict: logger.info(f'''***** {split} metrics *****''' ) for key in sorted(metrics.keys() ): logger.info(f''' {key} = {metrics[key]}''' ) save_json(__lowerCAmelCase , os.path.join(__lowerCAmelCase , f'''{split}_results.json''' ) ) def __magic_name__ ( ) -> Optional[Any]: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. __lowerCamelCase = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) ) 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. __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = parser.parse_args_into_dataclasses() check_output_dir(__lowerCAmelCase ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info('''Training/evaluation parameters %s''' , __lowerCAmelCase ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __lowerCamelCase = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) __lowerCamelCase = ('''encoder_layerdrop''', '''decoder_layerdrop''', '''dropout''', '''attention_dropout''') for p in extra_model_params: if getattr(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): assert hasattr(__lowerCAmelCase , __lowerCAmelCase ), f'''({config.__class__.__name__}) doesn\'t have a `{p}` attribute''' setattr(__lowerCAmelCase , __lowerCAmelCase , getattr(__lowerCAmelCase , __lowerCAmelCase ) ) __lowerCamelCase = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) __lowerCamelCase = AutoModelForSeqaSeqLM.from_pretrained( model_args.model_name_or_path , from_tf='''.ckpt''' in model_args.model_name_or_path , config=__lowerCAmelCase , cache_dir=model_args.cache_dir , ) # use task specific params use_task_specific_params(__lowerCAmelCase , data_args.task ) # set num_beams for evaluation if data_args.eval_beams is None: __lowerCamelCase = model.config.num_beams # set decoder_start_token_id for MBart if model.config.decoder_start_token_id is None and isinstance(__lowerCAmelCase , (MBartTokenizer, MBartTokenizerFast) ): assert ( data_args.tgt_lang is not None and data_args.src_lang is not None ), "mBart requires --tgt_lang and --src_lang" if isinstance(__lowerCAmelCase , __lowerCAmelCase ): __lowerCamelCase = tokenizer.lang_code_to_id[data_args.tgt_lang] else: __lowerCamelCase = tokenizer.convert_tokens_to_ids(data_args.tgt_lang ) if model_args.freeze_embeds: freeze_embeds(__lowerCAmelCase ) if model_args.freeze_encoder: freeze_params(model.get_encoder() ) assert_all_frozen(model.get_encoder() ) __lowerCamelCase = SeqaSeqDataset # Get datasets __lowerCamelCase = ( dataset_class( __lowerCAmelCase , type_path='''train''' , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_train else None ) __lowerCamelCase = ( dataset_class( __lowerCAmelCase , type_path='''val''' , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO else None ) __lowerCamelCase = ( dataset_class( __lowerCAmelCase , type_path='''test''' , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_predict else None ) # Initialize our Trainer __lowerCamelCase = ( build_compute_metrics_fn(data_args.task , __lowerCAmelCase ) if training_args.predict_with_generate else None ) __lowerCamelCase = SeqaSeqTrainer( model=__lowerCAmelCase , args=__lowerCAmelCase , data_args=__lowerCAmelCase , train_dataset=__lowerCAmelCase , eval_dataset=__lowerCAmelCase , data_collator=SeqaSeqDataCollator( __lowerCAmelCase , __lowerCAmelCase , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=__lowerCAmelCase , tokenizer=__lowerCAmelCase , ) __lowerCamelCase = {} # Training if training_args.do_train: logger.info('''*** Train ***''' ) __lowerCamelCase = trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) __lowerCamelCase = train_result.metrics __lowerCamelCase = data_args.n_train trainer.save_model() # this also saves the tokenizer if trainer.is_world_process_zero(): handle_metrics('''train''' , __lowerCAmelCase , training_args.output_dir ) all_metrics.update(__lowerCAmelCase ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , '''trainer_state.json''' ) ) # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) tokenizer.save_pretrained(training_args.output_dir ) # Evaluation if training_args.do_eval: logger.info('''*** Evaluate ***''' ) __lowerCamelCase = trainer.evaluate(metric_key_prefix='''val''' ) __lowerCamelCase = data_args.n_val __lowerCamelCase = round(metrics['''val_loss'''] , 4 ) if trainer.is_world_process_zero(): handle_metrics('''val''' , __lowerCAmelCase , training_args.output_dir ) all_metrics.update(__lowerCAmelCase ) if training_args.do_predict: logger.info('''*** Predict ***''' ) __lowerCamelCase = trainer.predict(test_dataset=__lowerCAmelCase , metric_key_prefix='''test''' ) __lowerCamelCase = test_output.metrics __lowerCamelCase = data_args.n_test if trainer.is_world_process_zero(): __lowerCamelCase = round(metrics['''test_loss'''] , 4 ) handle_metrics('''test''' , __lowerCAmelCase , training_args.output_dir ) all_metrics.update(__lowerCAmelCase ) if training_args.predict_with_generate: __lowerCamelCase = tokenizer.batch_decode( test_output.predictions , skip_special_tokens=__lowerCAmelCase , clean_up_tokenization_spaces=__lowerCAmelCase ) __lowerCamelCase = lmap(str.strip , __lowerCAmelCase ) write_txt_file(__lowerCAmelCase , os.path.join(training_args.output_dir , '''test_generations.txt''' ) ) if trainer.is_world_process_zero(): save_json(__lowerCAmelCase , os.path.join(training_args.output_dir , '''all_results.json''' ) ) return all_metrics def __magic_name__ ( __lowerCAmelCase : List[str] ) -> Union[str, Any]: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
339
0
from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
356
import unittest import numpy as np import torch from diffusers import ScoreSdeVePipeline, ScoreSdeVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class lowerCAmelCase__ ( unittest.TestCase ): @property def __A ( self : List[Any] ) -> Optional[Any]: torch.manual_seed(0 ) __lowerCamelCase = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) return model def __A ( self : Optional[int] ) -> Optional[Any]: __lowerCamelCase = self.dummy_uncond_unet __lowerCamelCase = ScoreSdeVeScheduler() __lowerCamelCase = ScoreSdeVePipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) sde_ve.to(SCREAMING_SNAKE_CASE__ ) sde_ve.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = torch.manual_seed(0 ) __lowerCamelCase = sde_ve(num_inference_steps=2 , output_type='''numpy''' , generator=SCREAMING_SNAKE_CASE__ ).images __lowerCamelCase = torch.manual_seed(0 ) __lowerCamelCase = sde_ve(num_inference_steps=2 , output_type='''numpy''' , generator=SCREAMING_SNAKE_CASE__ , return_dict=SCREAMING_SNAKE_CASE__ )[ 0 ] __lowerCamelCase = image[0, -3:, -3:, -1] __lowerCamelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __lowerCamelCase = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Tuple ) -> str: __lowerCamelCase = '''google/ncsnpp-church-256''' __lowerCamelCase = UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = ScoreSdeVeScheduler.from_pretrained(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = ScoreSdeVePipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) sde_ve.to(SCREAMING_SNAKE_CASE__ ) sde_ve.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = torch.manual_seed(0 ) __lowerCamelCase = sde_ve(num_inference_steps=10 , output_type='''numpy''' , generator=SCREAMING_SNAKE_CASE__ ).images __lowerCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 2_56, 2_56, 3) __lowerCamelCase = np.array([0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
339
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available SCREAMING_SNAKE_CASE__ : int = { "configuration_chinese_clip": [ "CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "ChineseCLIPConfig", "ChineseCLIPOnnxConfig", "ChineseCLIPTextConfig", "ChineseCLIPVisionConfig", ], "processing_chinese_clip": ["ChineseCLIPProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = ["ChineseCLIPFeatureExtractor"] SCREAMING_SNAKE_CASE__ : int = ["ChineseCLIPImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "ChineseCLIPModel", "ChineseCLIPPreTrainedModel", "ChineseCLIPTextModel", "ChineseCLIPVisionModel", ] if TYPE_CHECKING: from .configuration_chinese_clip import ( CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, ChineseCLIPConfig, ChineseCLIPOnnxConfig, ChineseCLIPTextConfig, ChineseCLIPVisionConfig, ) from .processing_chinese_clip import ChineseCLIPProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_chinese_clip import ChineseCLIPFeatureExtractor, ChineseCLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_chinese_clip import ( CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, ChineseCLIPModel, ChineseCLIPPreTrainedModel, ChineseCLIPTextModel, ChineseCLIPVisionModel, ) else: import sys SCREAMING_SNAKE_CASE__ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
357
from functools import lru_cache def __magic_name__ ( __lowerCAmelCase : int ) -> set: __lowerCamelCase = 2 __lowerCamelCase = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(__lowerCAmelCase ) if n > 1: factors.add(__lowerCAmelCase ) return factors @lru_cache def __magic_name__ ( __lowerCAmelCase : int ) -> int: return len(unique_prime_factors(__lowerCAmelCase ) ) def __magic_name__ ( __lowerCAmelCase : list ) -> bool: return len(set(__lowerCAmelCase ) ) in (0, 1) def __magic_name__ ( __lowerCAmelCase : int ) -> list: __lowerCamelCase = 2 while True: # Increment each value of a generated range __lowerCamelCase = [base + i for i in range(__lowerCAmelCase )] # Run elements through out unique_prime_factors function # Append our target number to the end. __lowerCamelCase = [upf_len(__lowerCAmelCase ) for x in group] checker.append(__lowerCAmelCase ) # If all numbers in the list are equal, return the group variable. if equality(__lowerCAmelCase ): return group # Increment our base variable by 1 base += 1 def __magic_name__ ( __lowerCAmelCase : int = 4 ) -> int: __lowerCamelCase = run(__lowerCAmelCase ) return results[0] if len(__lowerCAmelCase ) else None if __name__ == "__main__": print(solution())
339
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : int = { "YituTech/conv-bert-base": "https://huggingface.co/YituTech/conv-bert-base/resolve/main/config.json", "YituTech/conv-bert-medium-small": ( "https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/config.json" ), "YituTech/conv-bert-small": "https://huggingface.co/YituTech/conv-bert-small/resolve/main/config.json", # See all ConvBERT models at https://huggingface.co/models?filter=convbert } class lowerCAmelCase__ ( __lowercase ): a__ : str = """convbert""" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int=3_05_22 , SCREAMING_SNAKE_CASE__ : Optional[int]=7_68 , SCREAMING_SNAKE_CASE__ : Tuple=12 , SCREAMING_SNAKE_CASE__ : str=12 , SCREAMING_SNAKE_CASE__ : List[str]=30_72 , SCREAMING_SNAKE_CASE__ : Optional[Any]="gelu" , SCREAMING_SNAKE_CASE__ : int=0.1 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.1 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=5_12 , SCREAMING_SNAKE_CASE__ : List[str]=2 , SCREAMING_SNAKE_CASE__ : str=0.02 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1e-12 , SCREAMING_SNAKE_CASE__ : Tuple=1 , SCREAMING_SNAKE_CASE__ : str=0 , SCREAMING_SNAKE_CASE__ : str=2 , SCREAMING_SNAKE_CASE__ : Any=7_68 , SCREAMING_SNAKE_CASE__ : str=2 , SCREAMING_SNAKE_CASE__ : Tuple=9 , SCREAMING_SNAKE_CASE__ : Dict=1 , SCREAMING_SNAKE_CASE__ : List[Any]=None , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> Optional[Any]: super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) __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 = initializer_range __lowerCamelCase = layer_norm_eps __lowerCamelCase = embedding_size __lowerCamelCase = head_ratio __lowerCamelCase = conv_kernel_size __lowerCamelCase = num_groups __lowerCamelCase = classifier_dropout class lowerCAmelCase__ ( __lowercase ): @property def __A ( self : Dict ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": __lowerCamelCase = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: __lowerCamelCase = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ] )
358
import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel class lowerCAmelCase__ : def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any]=99 , SCREAMING_SNAKE_CASE__ : List[Any]=13 , SCREAMING_SNAKE_CASE__ : Tuple=7 , SCREAMING_SNAKE_CASE__ : int=9 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Dict=False , SCREAMING_SNAKE_CASE__ : int=32 , SCREAMING_SNAKE_CASE__ : Tuple=5 , SCREAMING_SNAKE_CASE__ : List[str]=4 , SCREAMING_SNAKE_CASE__ : str=37 , SCREAMING_SNAKE_CASE__ : int=8 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.002 , SCREAMING_SNAKE_CASE__ : str=1 , SCREAMING_SNAKE_CASE__ : Tuple=0 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0 , SCREAMING_SNAKE_CASE__ : int=None , SCREAMING_SNAKE_CASE__ : Dict=None , ) -> Optional[Any]: __lowerCamelCase = parent __lowerCamelCase = batch_size __lowerCamelCase = encoder_seq_length __lowerCamelCase = decoder_seq_length # For common tests __lowerCamelCase = self.decoder_seq_length __lowerCamelCase = is_training __lowerCamelCase = use_attention_mask __lowerCamelCase = use_labels __lowerCamelCase = vocab_size __lowerCamelCase = hidden_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = d_ff __lowerCamelCase = relative_attention_num_buckets __lowerCamelCase = dropout_rate __lowerCamelCase = initializer_factor __lowerCamelCase = eos_token_id __lowerCamelCase = pad_token_id __lowerCamelCase = decoder_start_token_id __lowerCamelCase = None __lowerCamelCase = decoder_layers def __A ( self : Any ) -> Tuple: return TaConfig.from_pretrained('''google/umt5-base''' ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , ) -> Optional[int]: if attention_mask is None: __lowerCamelCase = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: __lowerCamelCase = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: __lowerCamelCase = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=SCREAMING_SNAKE_CASE__ ) if decoder_head_mask is None: __lowerCamelCase = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=SCREAMING_SNAKE_CASE__ ) if cross_attn_head_mask is None: __lowerCamelCase = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=SCREAMING_SNAKE_CASE__ ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } def __A ( self : List[Any] ) -> Tuple: __lowerCamelCase = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) __lowerCamelCase = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for NllbMoe the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input __lowerCamelCase = input_ids.clamp(self.pad_token_id + 1 ) __lowerCamelCase = decoder_input_ids.clamp(self.pad_token_id + 1 ) __lowerCamelCase = self.get_config() __lowerCamelCase = config.num_attention_heads __lowerCamelCase = self.prepare_inputs_dict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return config, input_dict def __A ( self : Tuple ) -> List[str]: __lowerCamelCase , __lowerCamelCase = self.prepare_config_and_inputs() return config, inputs_dict def __A ( self : Optional[Any] ) -> Any: return TaConfig( vocab_size=1_66 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def __A ( self : List[Any] ) -> Any: return TaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> int: __lowerCamelCase = UMTaModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __lowerCamelCase = model( input_ids=SCREAMING_SNAKE_CASE__ , decoder_input_ids=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , decoder_attention_mask=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = model(input_ids=SCREAMING_SNAKE_CASE__ , decoder_input_ids=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = result.last_hidden_state __lowerCamelCase = result.past_key_values __lowerCamelCase = result.encoder_last_hidden_state self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) ) self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) ) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , config.num_layers ) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0] ) , 4 ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple , ) -> Dict: __lowerCamelCase = UMTaModel(config=SCREAMING_SNAKE_CASE__ ).get_decoder().to(SCREAMING_SNAKE_CASE__ ).eval() # first forward pass __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ , use_cache=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ , use_cache=SCREAMING_SNAKE_CASE__ ) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE__ ) == len(SCREAMING_SNAKE_CASE__ ) ) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE__ ) == len(SCREAMING_SNAKE_CASE__ ) + 1 ) __lowerCamelCase , __lowerCamelCase = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids __lowerCamelCase = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and __lowerCamelCase = torch.cat([input_ids, next_tokens] , dim=-1 ) __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ )['''last_hidden_state'''] __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ , past_key_values=SCREAMING_SNAKE_CASE__ )['''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(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple , ) -> Optional[int]: __lowerCamelCase = UMTaModel(config=SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ ).half().eval() __lowerCamelCase = model(**SCREAMING_SNAKE_CASE__ )['''last_hidden_state'''] self.parent.assertFalse(torch.isnan(SCREAMING_SNAKE_CASE__ ).any().item() ) @require_torch class lowerCAmelCase__ ( __lowercase , __lowercase , __lowercase , unittest.TestCase ): a__ : List[Any] = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) a__ : Union[str, Any] = (UMTaForConditionalGeneration,) if is_torch_available() else () a__ : Tuple = ( { """conversational""": UMTaForConditionalGeneration, """feature-extraction""": UMTaModel, """summarization""": UMTaForConditionalGeneration, """text2text-generation""": UMTaForConditionalGeneration, """translation""": UMTaForConditionalGeneration, """question-answering""": UMTaForQuestionAnswering, } if is_torch_available() else {} ) a__ : int = True a__ : int = False a__ : Tuple = False a__ : Optional[int] = True a__ : Optional[int] = True # The small UMT5 model needs higher percentages for CPU/MP tests a__ : Tuple = [0.8, 0.9] def __A ( self : Tuple ) -> Tuple: __lowerCamelCase = UMTaModelTester(self ) @unittest.skip('''Test has a segmentation fault on torch 1.8.0''' ) def __A ( self : List[str] ) -> Union[str, Any]: __lowerCamelCase = self.model_tester.prepare_config_and_inputs() __lowerCamelCase = UMTaModel(config_and_inputs[0] ).to(SCREAMING_SNAKE_CASE__ ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( SCREAMING_SNAKE_CASE__ , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , f'''{tmpdirname}/t5_test.onnx''' , export_params=SCREAMING_SNAKE_CASE__ , opset_version=9 , input_names=['''input_ids''', '''decoder_input_ids'''] , ) @unittest.skipIf(torch_device == '''cpu''' , '''Cant do half precision''' ) def __A ( self : Union[str, Any] ) -> Any: __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*SCREAMING_SNAKE_CASE__ ) def __A ( self : Any ) -> Any: __lowerCamelCase = ['''encoder_attentions''', '''decoder_attentions''', '''cross_attentions'''] __lowerCamelCase = self.model_tester.prepare_config_and_inputs() __lowerCamelCase = config_and_inputs[0] __lowerCamelCase = UMTaForConditionalGeneration(SCREAMING_SNAKE_CASE__ ).eval() model.to(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = { '''head_mask''': torch.zeros(config.num_layers , config.num_heads , device=SCREAMING_SNAKE_CASE__ ), '''decoder_head_mask''': torch.zeros(config.num_decoder_layers , config.num_heads , device=SCREAMING_SNAKE_CASE__ ), '''cross_attn_head_mask''': torch.zeros(config.num_decoder_layers , config.num_heads , device=SCREAMING_SNAKE_CASE__ ), } for attn_name, (name, mask) in zip(SCREAMING_SNAKE_CASE__ , head_masking.items() ): __lowerCamelCase = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": __lowerCamelCase = torch.ones( config.num_decoder_layers , config.num_heads , device=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model.generate( config_and_inputs[1]['''input_ids'''] , num_beams=1 , max_length=3 , output_attentions=SCREAMING_SNAKE_CASE__ , return_dict_in_generate=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) # We check the state of decoder_attentions and cross_attentions just from the last step __lowerCamelCase = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 ) @unittest.skip('''Does not work on the tiny model as we keep hitting edge cases.''' ) def __A ( self : Tuple ) -> Optional[Any]: pass @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): @slow @unittest.skip( '''Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged''' ) def __A ( self : int ) -> Optional[Any]: __lowerCamelCase = UMTaForConditionalGeneration.from_pretrained('''google/umt5-small''' , return_dict=SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = AutoTokenizer.from_pretrained('''google/umt5-small''' , use_fast=SCREAMING_SNAKE_CASE__ , legacy=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = [ '''Bonjour monsieur <extra_id_0> bien <extra_id_1>.''', '''No se como puedo <extra_id_0>.''', '''This is the reason why we <extra_id_0> them.''', '''The <extra_id_0> walks in <extra_id_1>, seats''', '''A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.''', ] __lowerCamelCase = tokenizer(SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , padding=SCREAMING_SNAKE_CASE__ ).input_ids # fmt: off __lowerCamelCase = torch.tensor( [ [ 3_85_30, 21_07_03, 25_62_99, 14_10, 25_62_98, 2_74, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 8_26, 3_21, 6_71, 2_59_22, 25_62_99, 2_74, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 14_60, 3_39, 3_12, 1_90_14, 1_06_20, 7_58, 25_62_99, 23_55,2_74, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 5_17, 25_62_99, 1_48_69, 2_81, 3_01, 25_62_98, 2_75, 11_99_83,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 3_20, 25_62_99, 1_48_69, 2_81, 22_34, 2_89, 22_75, 3_33,6_13_91, 2_89, 25_62_98, 5_43, 25_62_97, 16_87_14, 3_29, 25_62_96,2_74, 1], ] ) # fmt: on torch.testing.assert_allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model.generate(input_ids.to(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = [ '''<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>''', '''<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', ] __lowerCamelCase = tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
339
0
def __magic_name__ ( __lowerCAmelCase : int = 50 ) -> int: __lowerCamelCase = [[0] * 3 for _ in range(length + 1 )] for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length] ) if __name__ == "__main__": print(F'{solution() = }')
359
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : Union[str, Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Tuple = { "s-JoL/Open-Llama-V1": "https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/config.json", } class lowerCAmelCase__ ( __lowercase ): a__ : Union[str, Any] = """open-llama""" def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Any=10_00_00 , SCREAMING_SNAKE_CASE__ : Any=40_96 , SCREAMING_SNAKE_CASE__ : Any=1_10_08 , SCREAMING_SNAKE_CASE__ : Tuple=32 , SCREAMING_SNAKE_CASE__ : str=32 , SCREAMING_SNAKE_CASE__ : Any="silu" , SCREAMING_SNAKE_CASE__ : Union[str, Any]=20_48 , SCREAMING_SNAKE_CASE__ : List[str]=0.02 , SCREAMING_SNAKE_CASE__ : List[Any]=1e-6 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Dict=0 , SCREAMING_SNAKE_CASE__ : Tuple=1 , SCREAMING_SNAKE_CASE__ : str=2 , SCREAMING_SNAKE_CASE__ : List[Any]=False , SCREAMING_SNAKE_CASE__ : Any=True , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Any=0.1 , SCREAMING_SNAKE_CASE__ : Any=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : List[str]=None , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> Dict: __lowerCamelCase = vocab_size __lowerCamelCase = max_position_embeddings __lowerCamelCase = hidden_size __lowerCamelCase = intermediate_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = hidden_act __lowerCamelCase = initializer_range __lowerCamelCase = rms_norm_eps __lowerCamelCase = use_cache __lowerCamelCase = kwargs.pop( '''use_memorry_efficient_attention''' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = hidden_dropout_prob __lowerCamelCase = attention_dropout_prob __lowerCamelCase = use_stable_embedding __lowerCamelCase = shared_input_output_embedding __lowerCamelCase = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , tie_word_embeddings=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) def __A ( self : Dict ) -> Optional[int]: if self.rope_scaling is None: return if not isinstance(self.rope_scaling , SCREAMING_SNAKE_CASE__ ) or len(self.rope_scaling ) != 2: raise ValueError( '''`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ''' f'''got {self.rope_scaling}''' ) __lowerCamelCase = self.rope_scaling.get('''type''' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.rope_scaling.get('''factor''' , SCREAMING_SNAKE_CASE__ ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' ) if rope_scaling_factor is None or not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or rope_scaling_factor <= 1.0: raise ValueError(f'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
339
0
def __magic_name__ ( __lowerCAmelCase : int ) -> bool: return str(__lowerCAmelCase ) == str(__lowerCAmelCase )[::-1] def __magic_name__ ( __lowerCAmelCase : int ) -> int: return int(__lowerCAmelCase ) + int(str(__lowerCAmelCase )[::-1] ) def __magic_name__ ( __lowerCAmelCase : int = 1_0000 ) -> int: __lowerCamelCase = [] for num in range(1 , __lowerCAmelCase ): __lowerCamelCase = 0 __lowerCamelCase = num while iterations < 50: __lowerCamelCase = sum_reverse(__lowerCAmelCase ) iterations += 1 if is_palindrome(__lowerCAmelCase ): break else: lychrel_nums.append(__lowerCAmelCase ) return len(__lowerCAmelCase ) if __name__ == "__main__": print(F'{solution() = }')
360
from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar SCREAMING_SNAKE_CASE__ : Any = TypeVar("KEY") SCREAMING_SNAKE_CASE__ : Dict = TypeVar("VAL") @dataclass(frozen=__lowercase , slots=__lowercase ) class lowerCAmelCase__ ( Generic[KEY, VAL] ): a__ : KEY a__ : VAL class lowerCAmelCase__ ( _Item ): def __init__( self : str ) -> None: super().__init__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __bool__( self : Tuple ) -> bool: return False SCREAMING_SNAKE_CASE__ : List[Any] = _DeletedItem() class lowerCAmelCase__ ( MutableMapping[KEY, VAL] ): def __init__( self : int , SCREAMING_SNAKE_CASE__ : int = 8 , SCREAMING_SNAKE_CASE__ : float = 0.75 ) -> None: __lowerCamelCase = initial_block_size __lowerCamelCase = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 __lowerCamelCase = capacity_factor __lowerCamelCase = 0 def __A ( self : Any , SCREAMING_SNAKE_CASE__ : KEY ) -> int: return hash(SCREAMING_SNAKE_CASE__ ) % len(self._buckets ) def __A ( self : Any , SCREAMING_SNAKE_CASE__ : int ) -> int: return (ind + 1) % len(self._buckets ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : KEY , SCREAMING_SNAKE_CASE__ : VAL ) -> bool: __lowerCamelCase = self._buckets[ind] if not stored: __lowerCamelCase = _Item(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self._len += 1 return True elif stored.key == key: __lowerCamelCase = _Item(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return True else: return False def __A ( self : Any ) -> bool: __lowerCamelCase = len(self._buckets ) * self._capacity_factor return len(self ) >= int(SCREAMING_SNAKE_CASE__ ) def __A ( self : List[Any] ) -> bool: if len(self._buckets ) <= self._initial_block_size: return False __lowerCamelCase = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def __A ( self : int , SCREAMING_SNAKE_CASE__ : int ) -> None: __lowerCamelCase = self._buckets __lowerCamelCase = [None] * new_size __lowerCamelCase = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def __A ( self : str ) -> None: self._resize(len(self._buckets ) * 2 ) def __A ( self : Dict ) -> None: self._resize(len(self._buckets ) // 2 ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : KEY ) -> Iterator[int]: __lowerCamelCase = self._get_bucket_index(SCREAMING_SNAKE_CASE__ ) for _ in range(len(self._buckets ) ): yield ind __lowerCamelCase = self._get_next_ind(SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : KEY , SCREAMING_SNAKE_CASE__ : VAL ) -> None: for ind in self._iterate_buckets(SCREAMING_SNAKE_CASE__ ): if self._try_set(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): break def __setitem__( self : Tuple , SCREAMING_SNAKE_CASE__ : KEY , SCREAMING_SNAKE_CASE__ : VAL ) -> None: if self._is_full(): self._size_up() self._add_item(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __delitem__( self : List[Any] , SCREAMING_SNAKE_CASE__ : KEY ) -> None: for ind in self._iterate_buckets(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = self._buckets[ind] if item is None: raise KeyError(SCREAMING_SNAKE_CASE__ ) if item is _deleted: continue if item.key == key: __lowerCamelCase = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : KEY ) -> VAL: for ind in self._iterate_buckets(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(SCREAMING_SNAKE_CASE__ ) def __len__( self : int ) -> int: return self._len def __iter__( self : Tuple ) -> Iterator[KEY]: yield from (item.key for item in self._buckets if item) def __repr__( self : Optional[Any] ) -> str: __lowerCamelCase = ''' ,'''.join( f'''{item.key}: {item.val}''' for item in self._buckets if item ) return f'''HashMap({val_string})'''
339
0
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, TensorType SCREAMING_SNAKE_CASE__ : Any = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : int = { "openai/imagegpt-small": "", "openai/imagegpt-medium": "", "openai/imagegpt-large": "", } class lowerCAmelCase__ ( __lowercase ): a__ : Tuple = """imagegpt""" a__ : Dict = ["""past_key_values"""] a__ : int = { """hidden_size""": """n_embd""", """max_position_embeddings""": """n_positions""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int]=5_12 + 1 , SCREAMING_SNAKE_CASE__ : Dict=32 * 32 , SCREAMING_SNAKE_CASE__ : Dict=5_12 , SCREAMING_SNAKE_CASE__ : str=24 , SCREAMING_SNAKE_CASE__ : str=8 , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : int="quick_gelu" , SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Tuple=0.1 , SCREAMING_SNAKE_CASE__ : Dict=1e-5 , SCREAMING_SNAKE_CASE__ : Dict=0.02 , SCREAMING_SNAKE_CASE__ : Any=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Tuple=False , SCREAMING_SNAKE_CASE__ : Dict=False , SCREAMING_SNAKE_CASE__ : Any=False , **SCREAMING_SNAKE_CASE__ : Optional[Any] , ) -> Dict: __lowerCamelCase = vocab_size __lowerCamelCase = n_positions __lowerCamelCase = n_embd __lowerCamelCase = n_layer __lowerCamelCase = n_head __lowerCamelCase = n_inner __lowerCamelCase = activation_function __lowerCamelCase = resid_pdrop __lowerCamelCase = embd_pdrop __lowerCamelCase = attn_pdrop __lowerCamelCase = layer_norm_epsilon __lowerCamelCase = initializer_range __lowerCamelCase = scale_attn_weights __lowerCamelCase = use_cache __lowerCamelCase = scale_attn_by_inverse_layer_idx __lowerCamelCase = reorder_and_upcast_attn __lowerCamelCase = tie_word_embeddings super().__init__(tie_word_embeddings=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) class lowerCAmelCase__ ( __lowercase ): @property def __A ( self : Tuple ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''sequence'''}), ] ) def __A ( self : int , SCREAMING_SNAKE_CASE__ : "FeatureExtractionMixin" , SCREAMING_SNAKE_CASE__ : int = 1 , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional["TensorType"] = None , SCREAMING_SNAKE_CASE__ : int = 3 , SCREAMING_SNAKE_CASE__ : int = 32 , SCREAMING_SNAKE_CASE__ : int = 32 , ) -> Mapping[str, Any]: __lowerCamelCase = self._generate_dummy_images(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = dict(preprocessor(images=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ ) ) return inputs
361
from datetime import datetime as dt import os from github import Github SCREAMING_SNAKE_CASE__ : Any = [ "good first issue", "good second issue", "good difficult issue", "feature request", "new model", "wip", ] def __magic_name__ ( ) -> Any: __lowerCamelCase = Github(os.environ['''GITHUB_TOKEN'''] ) __lowerCamelCase = g.get_repo('''huggingface/transformers''' ) __lowerCamelCase = repo.get_issues(state='''open''' ) for issue in open_issues: __lowerCamelCase = sorted([comment for comment in issue.get_comments()] , key=lambda __lowerCAmelCase : i.created_at , reverse=__lowerCAmelCase ) __lowerCamelCase = comments[0] if len(__lowerCAmelCase ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # print(f"Would close issue {issue.number} since it has been 7 days of inactivity since bot mention.") issue.edit(state='''closed''' ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # print(f"Would add stale comment to {issue.number}") issue.create_comment( '''This issue has been automatically marked as stale because it has not had ''' '''recent activity. If you think this still needs to be addressed ''' '''please comment on this thread.\n\nPlease note that issues that do not follow the ''' '''[contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) ''' '''are likely to be ignored.''' ) if __name__ == "__main__": main()
339
0
from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_VISION_2_SEQ_MAPPING if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING SCREAMING_SNAKE_CASE : Any = logging.get_logger(__name__) @add_end_docstrings(__lowercase ) class lowerCAmelCase__ ( __lowercase ): def __init__( self : str , *SCREAMING_SNAKE_CASE__ : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Optional[Any]: super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) requires_backends(self , '''vision''' ) self.check_model_type( TF_MODEL_FOR_VISION_2_SEQ_MAPPING if self.framework == '''tf''' else MODEL_FOR_VISION_2_SEQ_MAPPING ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : str=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None ) -> Optional[int]: __lowerCamelCase = {} __lowerCamelCase = {} if prompt is not None: __lowerCamelCase = prompt if generate_kwargs is not None: __lowerCamelCase = generate_kwargs if max_new_tokens is not None: if "generate_kwargs" not in forward_kwargs: __lowerCamelCase = {} if "max_new_tokens" in forward_kwargs["generate_kwargs"]: raise ValueError( '''\'max_new_tokens\' is defined twice, once in \'generate_kwargs\' and once as a direct parameter,''' ''' please use only one''' ) __lowerCamelCase = max_new_tokens return preprocess_params, forward_kwargs, {} def __call__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, List[str], "Image.Image", List["Image.Image"]] , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> int: return super().__call__(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[Any]=None ) -> Dict: __lowerCamelCase = load_image(SCREAMING_SNAKE_CASE__ ) if prompt is not None: if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise ValueError( f'''Received an invalid text input, got - {type(SCREAMING_SNAKE_CASE__ )} - but expected a single string. ''' '''Note also that one single text can be provided for conditional image to text generation.''' ) __lowerCamelCase = self.model.config.model_type if model_type == "git": __lowerCamelCase = self.image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors=self.framework ) __lowerCamelCase = self.tokenizer(text=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ).input_ids __lowerCamelCase = [self.tokenizer.cls_token_id] + input_ids __lowerCamelCase = torch.tensor(SCREAMING_SNAKE_CASE__ ).unsqueeze(0 ) model_inputs.update({'''input_ids''': input_ids} ) elif model_type == "pix2struct": __lowerCamelCase = self.image_processor(images=SCREAMING_SNAKE_CASE__ , header_text=SCREAMING_SNAKE_CASE__ , return_tensors=self.framework ) elif model_type != "vision-encoder-decoder": # vision-encoder-decoder does not support conditional generation __lowerCamelCase = self.image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors=self.framework ) __lowerCamelCase = self.tokenizer(SCREAMING_SNAKE_CASE__ , return_tensors=self.framework ) model_inputs.update(SCREAMING_SNAKE_CASE__ ) else: raise ValueError(f'''Model type {model_type} does not support conditional text generation''' ) else: __lowerCamelCase = self.image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors=self.framework ) if self.model.config.model_type == "git" and prompt is None: __lowerCamelCase = None return model_inputs def __A ( self : str , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str]=None ) -> Optional[Any]: # Git model sets `model_inputs["input_ids"] = None` in `preprocess` (when `prompt=None`). In batch model, the # pipeline will group them into a list of `None`, which fail `_forward`. Avoid this by checking it first. if ( "input_ids" in model_inputs and isinstance(model_inputs['''input_ids'''] , SCREAMING_SNAKE_CASE__ ) and all(x is None for x in model_inputs['''input_ids'''] ) ): __lowerCamelCase = None if generate_kwargs is None: __lowerCamelCase = {} # FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py` # parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas # the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name` # in the `_prepare_model_inputs` method. __lowerCamelCase = model_inputs.pop(self.model.main_input_name ) __lowerCamelCase = self.model.generate(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) return model_outputs def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: __lowerCamelCase = [] for output_ids in model_outputs: __lowerCamelCase = { '''generated_text''': self.tokenizer.decode( SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ , ) } records.append(SCREAMING_SNAKE_CASE__ ) return records
362
def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int ) -> str: if a < 0 or b < 0: raise ValueError('''the value of both inputs must be positive''' ) __lowerCamelCase = str(bin(__lowerCAmelCase ) )[2:] # remove the leading "0b" __lowerCamelCase = str(bin(__lowerCAmelCase ) )[2:] # remove the leading "0b" __lowerCamelCase = max(len(__lowerCAmelCase ) , len(__lowerCAmelCase ) ) return "0b" + "".join( str(int(char_a == '''1''' and char_b == '''1''' ) ) for char_a, char_b in zip(a_binary.zfill(__lowerCAmelCase ) , b_binary.zfill(__lowerCAmelCase ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
339
0
SCREAMING_SNAKE_CASE__ : Tuple = { "a": "AAAAA", "b": "AAAAB", "c": "AAABA", "d": "AAABB", "e": "AABAA", "f": "AABAB", "g": "AABBA", "h": "AABBB", "i": "ABAAA", "j": "BBBAA", "k": "ABAAB", "l": "ABABA", "m": "ABABB", "n": "ABBAA", "o": "ABBAB", "p": "ABBBA", "q": "ABBBB", "r": "BAAAA", "s": "BAAAB", "t": "BAABA", "u": "BAABB", "v": "BBBAB", "w": "BABAA", "x": "BABAB", "y": "BABBA", "z": "BABBB", " ": " ", } SCREAMING_SNAKE_CASE__ : Optional[Any] = {value: key for key, value in encode_dict.items()} def __magic_name__ ( __lowerCAmelCase : str ) -> str: __lowerCamelCase = '''''' for letter in word.lower(): if letter.isalpha() or letter == " ": encoded += encode_dict[letter] else: raise Exception('''encode() accepts only letters of the alphabet and spaces''' ) return encoded def __magic_name__ ( __lowerCAmelCase : str ) -> str: if set(__lowerCAmelCase ) - {"A", "B", " "} != set(): raise Exception('''decode() accepts only \'A\', \'B\' and spaces''' ) __lowerCamelCase = '''''' for word in coded.split(): while len(__lowerCAmelCase ) != 0: decoded += decode_dict[word[:5]] __lowerCamelCase = word[5:] decoded += " " return decoded.strip() if __name__ == "__main__": from doctest import testmod testmod()
363
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPSegProcessor, ViTImageProcessor @require_vision class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : List[str] ) -> Dict: __lowerCamelCase = tempfile.mkdtemp() # fmt: off __lowerCamelCase = ['''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''lo''', '''l</w>''', '''w</w>''', '''r</w>''', '''t</w>''', '''low</w>''', '''er</w>''', '''lowest</w>''', '''newer</w>''', '''wider''', '''<unk>''', '''<|startoftext|>''', '''<|endoftext|>'''] # fmt: on __lowerCamelCase = dict(zip(SCREAMING_SNAKE_CASE__ , range(len(SCREAMING_SNAKE_CASE__ ) ) ) ) __lowerCamelCase = ['''#version: 0.2''', '''l o''', '''lo w</w>''', '''e r</w>''', ''''''] __lowerCamelCase = {'''unk_token''': '''<unk>'''} __lowerCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) __lowerCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE__ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = { '''do_resize''': True, '''size''': 20, '''do_center_crop''': True, '''crop_size''': 18, '''do_normalize''': True, '''image_mean''': [0.48145466, 0.4578275, 0.40821073], '''image_std''': [0.26862954, 0.26130258, 0.27577711], } __lowerCamelCase = os.path.join(self.tmpdirname , SCREAMING_SNAKE_CASE__ ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : int , **SCREAMING_SNAKE_CASE__ : int ) -> Any: return CLIPTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def __A ( self : Dict , **SCREAMING_SNAKE_CASE__ : Dict ) -> Union[str, Any]: return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[int] , **SCREAMING_SNAKE_CASE__ : Any ) -> List[Any]: return ViTImageProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def __A ( self : Dict ) -> Dict: shutil.rmtree(self.tmpdirname ) def __A ( self : str ) -> Any: __lowerCamelCase = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] __lowerCamelCase = [Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def __A ( self : List[Any] ) -> List[str]: __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = self.get_rust_tokenizer() __lowerCamelCase = self.get_image_processor() __lowerCamelCase = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) processor_slow.save_pretrained(self.tmpdirname ) __lowerCamelCase = CLIPSegProcessor.from_pretrained(self.tmpdirname , use_fast=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) processor_fast.save_pretrained(self.tmpdirname ) __lowerCamelCase = 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 , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor_fast.tokenizer , SCREAMING_SNAKE_CASE__ ) 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 , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor_fast.image_processor , SCREAMING_SNAKE_CASE__ ) def __A ( self : Union[str, Any] ) -> int: __lowerCamelCase = CLIPSegProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __lowerCamelCase = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __lowerCamelCase = self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) __lowerCamelCase = CLIPSegProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , SCREAMING_SNAKE_CASE__ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[Any] ) -> Union[str, Any]: __lowerCamelCase = self.get_image_processor() __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.prepare_image_inputs() __lowerCamelCase = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='''np''' ) __lowerCamelCase = processor(images=SCREAMING_SNAKE_CASE__ , 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 __A ( self : List[Any] ) -> Optional[int]: __lowerCamelCase = self.get_image_processor() __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = '''lower newer''' __lowerCamelCase = processor(text=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = tokenizer(SCREAMING_SNAKE_CASE__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __A ( self : List[Any] ) -> Any: __lowerCamelCase = self.get_image_processor() __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = '''lower newer''' __lowerCamelCase = self.prepare_image_inputs() __lowerCamelCase = processor(text=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE__ ): processor() def __A ( self : Optional[Any] ) -> List[str]: __lowerCamelCase = self.get_image_processor() __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.prepare_image_inputs() __lowerCamelCase = self.prepare_image_inputs() __lowerCamelCase = processor(images=SCREAMING_SNAKE_CASE__ , visual_prompt=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , ['''pixel_values''', '''conditional_pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE__ ): processor() def __A ( self : List[Any] ) -> Any: __lowerCamelCase = self.get_image_processor() __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __lowerCamelCase = processor.batch_decode(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
339
0
from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class lowerCAmelCase__ ( __lowercase ): a__ : Optional[int] = """""" a__ : List[str] = """hf-legacy""" # "hf://"" is reserved for hffs def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[DatasetInfo] = None , SCREAMING_SNAKE_CASE__ : Optional[str] = None , **SCREAMING_SNAKE_CASE__ : Tuple , ) -> List[Any]: super().__init__(self , **SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = repo_info __lowerCamelCase = token __lowerCamelCase = None def __A ( self : int ) -> List[Any]: if self.dir_cache is None: __lowerCamelCase = {} for hf_file in self.repo_info.siblings: # TODO(QL): add sizes __lowerCamelCase = { '''name''': hf_file.rfilename, '''size''': None, '''type''': '''file''', } self.dir_cache.update( { str(SCREAMING_SNAKE_CASE__ ): {'''name''': str(SCREAMING_SNAKE_CASE__ ), '''size''': None, '''type''': '''directory'''} for d in list(PurePosixPath(hf_file.rfilename ).parents )[:-1] } ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str = "rb" , **SCREAMING_SNAKE_CASE__ : Dict , ) -> Tuple: if not isinstance(self.repo_info , SCREAMING_SNAKE_CASE__ ): raise NotImplementedError(f'''Open is only implemented for dataset repositories, but got {self.repo_info}''' ) __lowerCamelCase = hf_hub_url(self.repo_info.id , SCREAMING_SNAKE_CASE__ , revision=self.repo_info.sha ) return fsspec.open( SCREAMING_SNAKE_CASE__ , mode=SCREAMING_SNAKE_CASE__ , headers=get_authentication_headers_for_url(SCREAMING_SNAKE_CASE__ , use_auth_token=self.token ) , client_kwargs={'''trust_env''': True} , ).open() def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : Any ) -> Optional[int]: self._get_dirs() __lowerCamelCase = self._strip_protocol(SCREAMING_SNAKE_CASE__ ) if path in self.dir_cache: return self.dir_cache[path] else: raise FileNotFoundError(SCREAMING_SNAKE_CASE__ ) def __A ( self : int , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Dict=False , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> Any: self._get_dirs() __lowerCamelCase = PurePosixPath(path.strip('''/''' ) ) __lowerCamelCase = {} for p, f in self.dir_cache.items(): __lowerCamelCase = PurePosixPath(p.strip('''/''' ) ) __lowerCamelCase = p.parent if root == path: __lowerCamelCase = f __lowerCamelCase = list(paths.values() ) if detail: return out else: return sorted(f['''name'''] for f in out )
364
from __future__ import annotations def __magic_name__ ( __lowerCAmelCase : list , __lowerCAmelCase : int | None = None , __lowerCAmelCase : int | None = None ) -> None: if start is None: __lowerCamelCase = 0 if end is None: __lowerCamelCase = len(__lowerCAmelCase ) - 1 if start >= end: return __lowerCamelCase = (start + end) // 2 slowsort(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) slowsort(__lowerCAmelCase , mid + 1 , __lowerCAmelCase ) if sequence[end] < sequence[mid]: __lowerCamelCase , __lowerCamelCase = sequence[mid], sequence[end] slowsort(__lowerCAmelCase , __lowerCAmelCase , end - 1 ) if __name__ == "__main__": from doctest import testmod testmod()
339
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : Tuple = { "configuration_roberta_prelayernorm": [ "ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP", "RobertaPreLayerNormConfig", "RobertaPreLayerNormOnnxConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[int] = [ "ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST", "RobertaPreLayerNormForCausalLM", "RobertaPreLayerNormForMaskedLM", "RobertaPreLayerNormForMultipleChoice", "RobertaPreLayerNormForQuestionAnswering", "RobertaPreLayerNormForSequenceClassification", "RobertaPreLayerNormForTokenClassification", "RobertaPreLayerNormModel", "RobertaPreLayerNormPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRobertaPreLayerNormForCausalLM", "TFRobertaPreLayerNormForMaskedLM", "TFRobertaPreLayerNormForMultipleChoice", "TFRobertaPreLayerNormForQuestionAnswering", "TFRobertaPreLayerNormForSequenceClassification", "TFRobertaPreLayerNormForTokenClassification", "TFRobertaPreLayerNormMainLayer", "TFRobertaPreLayerNormModel", "TFRobertaPreLayerNormPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Dict = [ "FlaxRobertaPreLayerNormForCausalLM", "FlaxRobertaPreLayerNormForMaskedLM", "FlaxRobertaPreLayerNormForMultipleChoice", "FlaxRobertaPreLayerNormForQuestionAnswering", "FlaxRobertaPreLayerNormForSequenceClassification", "FlaxRobertaPreLayerNormForTokenClassification", "FlaxRobertaPreLayerNormModel", "FlaxRobertaPreLayerNormPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roberta_prelayernorm import ( ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaPreLayerNormConfig, RobertaPreLayerNormOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta_prelayernorm import ( ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaPreLayerNormForCausalLM, RobertaPreLayerNormForMaskedLM, RobertaPreLayerNormForMultipleChoice, RobertaPreLayerNormForQuestionAnswering, RobertaPreLayerNormForSequenceClassification, RobertaPreLayerNormForTokenClassification, RobertaPreLayerNormModel, RobertaPreLayerNormPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta_prelayernorm import ( TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaPreLayerNormForCausalLM, TFRobertaPreLayerNormForMaskedLM, TFRobertaPreLayerNormForMultipleChoice, TFRobertaPreLayerNormForQuestionAnswering, TFRobertaPreLayerNormForSequenceClassification, TFRobertaPreLayerNormForTokenClassification, TFRobertaPreLayerNormMainLayer, TFRobertaPreLayerNormModel, TFRobertaPreLayerNormPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
365
import json import os from typing import Dict, List, Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE__ : Any = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Optional[Any] = { "vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_config_file": "tokenizer_config.json", } SCREAMING_SNAKE_CASE__ : str = { "vocab_file": { "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json" }, "merges_file": { "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt" }, "tokenizer_config_file": { "facebook/blenderbot_small-90M": ( "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json" ) }, } SCREAMING_SNAKE_CASE__ : int = {"facebook/blenderbot_small-90M": 512} def __magic_name__ ( __lowerCAmelCase : List[str] ) -> Tuple: __lowerCamelCase = set() __lowerCamelCase = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __lowerCamelCase = char __lowerCamelCase = set(__lowerCAmelCase ) return pairs class lowerCAmelCase__ ( __lowercase ): a__ : List[Any] = VOCAB_FILES_NAMES a__ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP a__ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ : Dict = ["""input_ids""", """attention_mask"""] def __init__( self : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple="__start__" , SCREAMING_SNAKE_CASE__ : Tuple="__end__" , SCREAMING_SNAKE_CASE__ : List[str]="__unk__" , SCREAMING_SNAKE_CASE__ : str="__null__" , **SCREAMING_SNAKE_CASE__ : Optional[Any] , ) -> Optional[Any]: super().__init__(unk_token=SCREAMING_SNAKE_CASE__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) with open(SCREAMING_SNAKE_CASE__ , encoding='''utf-8''' ) as vocab_handle: __lowerCamelCase = json.load(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = {v: k for k, v in self.encoder.items()} with open(SCREAMING_SNAKE_CASE__ , encoding='''utf-8''' ) as merges_handle: __lowerCamelCase = merges_handle.read().split('''\n''' )[1:-1] __lowerCamelCase = [tuple(merge.split() ) for merge in merges] __lowerCamelCase = dict(zip(SCREAMING_SNAKE_CASE__ , range(len(SCREAMING_SNAKE_CASE__ ) ) ) ) __lowerCamelCase = {} @property def __A ( self : Dict ) -> int: return len(self.encoder ) def __A ( self : str ) -> Dict: return dict(self.encoder , **self.added_tokens_encoder ) def __A ( self : Any , SCREAMING_SNAKE_CASE__ : str ) -> str: if token in self.cache: return self.cache[token] __lowerCamelCase = re.sub('''([.,!?()])''' , R''' \1''' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = re.sub('''(\')''' , R''' \1 ''' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = re.sub(R'''\s{2,}''' , ''' ''' , SCREAMING_SNAKE_CASE__ ) if "\n" in token: __lowerCamelCase = token.replace('''\n''' , ''' __newln__''' ) __lowerCamelCase = token.split(''' ''' ) __lowerCamelCase = [] for token in tokens: if not len(SCREAMING_SNAKE_CASE__ ): continue __lowerCamelCase = token.lower() __lowerCamelCase = tuple(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = tuple(list(word[:-1] ) + [word[-1] + '''</w>'''] ) __lowerCamelCase = get_pairs(SCREAMING_SNAKE_CASE__ ) if not pairs: words.append(SCREAMING_SNAKE_CASE__ ) continue while True: __lowerCamelCase = min(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : self.bpe_ranks.get(SCREAMING_SNAKE_CASE__ , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break __lowerCamelCase , __lowerCamelCase = bigram __lowerCamelCase = [] __lowerCamelCase = 0 while i < len(SCREAMING_SNAKE_CASE__ ): try: __lowerCamelCase = word.index(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) new_word.extend(word[i:j] ) __lowerCamelCase = j except ValueError: new_word.extend(word[i:] ) break if word[i] == first and i < len(SCREAMING_SNAKE_CASE__ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 __lowerCamelCase = tuple(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = new_word if len(SCREAMING_SNAKE_CASE__ ) == 1: break else: __lowerCamelCase = get_pairs(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = '''@@ '''.join(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = word[:-4] __lowerCamelCase = word words.append(SCREAMING_SNAKE_CASE__ ) return " ".join(SCREAMING_SNAKE_CASE__ ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: __lowerCamelCase = [] __lowerCamelCase = re.findall(R'''\S+\n?''' , SCREAMING_SNAKE_CASE__ ) for token in words: split_tokens.extend(list(self.bpe(SCREAMING_SNAKE_CASE__ ).split(''' ''' ) ) ) return split_tokens def __A ( self : str , SCREAMING_SNAKE_CASE__ : str ) -> int: __lowerCamelCase = token.lower() return self.encoder.get(SCREAMING_SNAKE_CASE__ , self.encoder.get(self.unk_token ) ) def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : int ) -> str: return self.decoder.get(SCREAMING_SNAKE_CASE__ , self.unk_token ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] ) -> str: __lowerCamelCase = ''' '''.join(SCREAMING_SNAKE_CASE__ ).replace('''@@ ''' , '''''' ).strip() return out_string def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __lowerCamelCase = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) __lowerCamelCase = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(SCREAMING_SNAKE_CASE__ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=SCREAMING_SNAKE_CASE__ , ensure_ascii=SCREAMING_SNAKE_CASE__ ) + '''\n''' ) __lowerCamelCase = 0 with open(SCREAMING_SNAKE_CASE__ , '''w''' , encoding='''utf-8''' ) as writer: writer.write('''#version: 0.2\n''' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda SCREAMING_SNAKE_CASE__ : kv[1] ): if index != token_index: logger.warning( f'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.''' ''' Please check that the tokenizer is not corrupted!''' ) __lowerCamelCase = token_index writer.write(''' '''.join(SCREAMING_SNAKE_CASE__ ) + '''\n''' ) index += 1 return vocab_file, merge_file
339
0
import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert_fast import BertTokenizerFast from .tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer, DPRReaderTokenizer SCREAMING_SNAKE_CASE__ : Any = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : int = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} SCREAMING_SNAKE_CASE__ : int = { "vocab_file": { "facebook/dpr-ctx_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-ctx_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-ctx_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-ctx_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json" ), }, } SCREAMING_SNAKE_CASE__ : Tuple = { "vocab_file": { "facebook/dpr-question_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-question_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-question_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-question_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json" ), }, } SCREAMING_SNAKE_CASE__ : Tuple = { "vocab_file": { "facebook/dpr-reader-single-nq-base": ( "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-reader-multiset-base": ( "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-reader-single-nq-base": ( "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-reader-multiset-base": ( "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json" ), }, } SCREAMING_SNAKE_CASE__ : str = { "facebook/dpr-ctx_encoder-single-nq-base": 512, "facebook/dpr-ctx_encoder-multiset-base": 512, } SCREAMING_SNAKE_CASE__ : Any = { "facebook/dpr-question_encoder-single-nq-base": 512, "facebook/dpr-question_encoder-multiset-base": 512, } SCREAMING_SNAKE_CASE__ : List[str] = { "facebook/dpr-reader-single-nq-base": 512, "facebook/dpr-reader-multiset-base": 512, } SCREAMING_SNAKE_CASE__ : Optional[Any] = { "facebook/dpr-ctx_encoder-single-nq-base": {"do_lower_case": True}, "facebook/dpr-ctx_encoder-multiset-base": {"do_lower_case": True}, } SCREAMING_SNAKE_CASE__ : List[Any] = { "facebook/dpr-question_encoder-single-nq-base": {"do_lower_case": True}, "facebook/dpr-question_encoder-multiset-base": {"do_lower_case": True}, } SCREAMING_SNAKE_CASE__ : Dict = { "facebook/dpr-reader-single-nq-base": {"do_lower_case": True}, "facebook/dpr-reader-multiset-base": {"do_lower_case": True}, } class lowerCAmelCase__ ( __lowercase ): a__ : int = VOCAB_FILES_NAMES a__ : Optional[int] = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP a__ : Any = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ : int = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION a__ : Dict = DPRContextEncoderTokenizer class lowerCAmelCase__ ( __lowercase ): a__ : Any = VOCAB_FILES_NAMES a__ : Any = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP a__ : Optional[Any] = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ : int = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION a__ : int = DPRQuestionEncoderTokenizer SCREAMING_SNAKE_CASE__ : Union[str, Any] = collections.namedtuple( "DPRSpanPrediction", ["span_score", "relevance_score", "doc_id", "start_index", "end_index", "text"] ) SCREAMING_SNAKE_CASE__ : Optional[int] = collections.namedtuple("DPRReaderOutput", ["start_logits", "end_logits", "relevance_logits"]) SCREAMING_SNAKE_CASE__ : Optional[int] = r"\n Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.\n It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),\n using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`\n with the format:\n\n [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>\n\n Args:\n questions (`str` or `List[str]`):\n The questions to be encoded. You can specify one question for many passages. In this case, the question\n will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in\n `titles` or `texts`.\n titles (`str` or `List[str]`):\n The passages titles to be encoded. This can be a string or a list of strings if there are several passages.\n texts (`str` or `List[str]`):\n The passages texts to be encoded. This can be a string or a list of strings if there are several passages.\n padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):\n Activates and controls padding. Accepts the following values:\n\n - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence\n if provided).\n - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided.\n - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different\n lengths).\n truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):\n Activates and controls truncation. Accepts the following values:\n\n - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to\n the maximum acceptable input length for the model if that argument is not provided. This will truncate\n token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch\n of pairs) is provided.\n - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the first\n sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the\n second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths\n greater than the model maximum admissible input size).\n max_length (`int`, *optional*):\n Controls the maximum length to use by one of the truncation/padding parameters.\n\n If left unset or set to `None`, this will use the predefined model maximum length if a maximum length\n is required by one of the truncation/padding parameters. If the model has no specific maximum input\n length (like XLNet) truncation/padding to a maximum length will be deactivated.\n return_tensors (`str` or [`~utils.TensorType`], *optional*):\n If set, will return tensors instead of list of python integers. Acceptable values are:\n\n - `'tf'`: Return TensorFlow `tf.constant` objects.\n - `'pt'`: Return PyTorch `torch.Tensor` objects.\n - `'np'`: Return Numpy `np.ndarray` objects.\n return_attention_mask (`bool`, *optional*):\n Whether or not to return the attention mask. If not set, will return the attention mask according to the\n specific tokenizer's default, defined by the `return_outputs` attribute.\n\n [What are attention masks?](../glossary#attention-mask)\n\n Return:\n `Dict[str, List[List[int]]]`: A dictionary with the following keys:\n\n - `input_ids`: List of token ids to be fed to a model.\n - `attention_mask`: List of indices specifying which tokens should be attended to by the model.\n " @add_start_docstrings(__lowercase ) class lowerCAmelCase__ : def __call__( self : int , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[str] = None , SCREAMING_SNAKE_CASE__ : Optional[str] = None , SCREAMING_SNAKE_CASE__ : Union[bool, str] = False , SCREAMING_SNAKE_CASE__ : Union[bool, str] = False , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , **SCREAMING_SNAKE_CASE__ : Any , ) -> BatchEncoding: if titles is None and texts is None: return super().__call__( SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) elif titles is None or texts is None: __lowerCamelCase = titles if texts is None else texts return super().__call__( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = titles if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else [titles] __lowerCamelCase = texts if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else [texts] __lowerCamelCase = len(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = questions if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else [questions] * n_passages assert len(SCREAMING_SNAKE_CASE__ ) == len( SCREAMING_SNAKE_CASE__ ), f'''There should be as many titles than texts but got {len(SCREAMING_SNAKE_CASE__ )} titles and {len(SCREAMING_SNAKE_CASE__ )} texts.''' __lowerCamelCase = super().__call__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ )['''input_ids'''] __lowerCamelCase = super().__call__(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ )['''input_ids'''] __lowerCamelCase = { '''input_ids''': [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ] } if return_attention_mask is not False: __lowerCamelCase = [] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id ) for input_id in input_ids] ) __lowerCamelCase = attention_mask return self.pad(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : BatchEncoding , SCREAMING_SNAKE_CASE__ : DPRReaderOutput , SCREAMING_SNAKE_CASE__ : int = 16 , SCREAMING_SNAKE_CASE__ : int = 64 , SCREAMING_SNAKE_CASE__ : int = 4 , ) -> List[DPRSpanPrediction]: __lowerCamelCase = reader_input['''input_ids'''] __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = reader_output[:3] __lowerCamelCase = len(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = sorted(range(SCREAMING_SNAKE_CASE__ ) , reverse=SCREAMING_SNAKE_CASE__ , key=relevance_logits.__getitem__ ) __lowerCamelCase = [] for doc_id in sorted_docs: __lowerCamelCase = list(input_ids[doc_id] ) # assuming question & title information is at the beginning of the sequence __lowerCamelCase = sequence_ids.index(self.sep_token_id , 2 ) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: __lowerCamelCase = sequence_ids.index(self.pad_token_id ) else: __lowerCamelCase = len(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=SCREAMING_SNAKE_CASE__ , top_spans=SCREAMING_SNAKE_CASE__ , ) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=SCREAMING_SNAKE_CASE__ , start_index=SCREAMING_SNAKE_CASE__ , end_index=SCREAMING_SNAKE_CASE__ , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) ) if len(SCREAMING_SNAKE_CASE__ ) >= num_spans: break return nbest_spans_predictions[:num_spans] def __A ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , ) -> List[DPRSpanPrediction]: __lowerCamelCase = [] for start_index, start_score in enumerate(SCREAMING_SNAKE_CASE__ ): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length] ): scores.append(((start_index, start_index + answer_length), start_score + end_score) ) __lowerCamelCase = sorted(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : x[1] , reverse=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = [] for (start_index, end_index), score in scores: assert start_index <= end_index, f'''Wrong span indices: [{start_index}:{end_index}]''' __lowerCamelCase = end_index - start_index + 1 assert length <= max_answer_length, f'''Span is too long: {length} > {max_answer_length}''' if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals ): continue chosen_span_intervals.append((start_index, end_index) ) if len(SCREAMING_SNAKE_CASE__ ) == top_spans: break return chosen_span_intervals @add_end_docstrings(__lowercase ) class lowerCAmelCase__ ( __lowercase , __lowercase ): a__ : Tuple = VOCAB_FILES_NAMES a__ : Union[str, Any] = READER_PRETRAINED_VOCAB_FILES_MAP a__ : List[Any] = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ : List[str] = READER_PRETRAINED_INIT_CONFIGURATION a__ : Optional[int] = ["""input_ids""", """attention_mask"""] a__ : List[Any] = DPRReaderTokenizer
366
import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class lowerCAmelCase__ ( __lowercase , unittest.TestCase ): a__ : str = ShapEImgaImgPipeline a__ : Union[str, Any] = ["""image"""] a__ : Optional[int] = ["""image"""] a__ : Union[str, Any] = [ """num_images_per_prompt""", """num_inference_steps""", """generator""", """latents""", """guidance_scale""", """frame_size""", """output_type""", """return_dict""", ] a__ : List[str] = False @property def __A ( self : Dict ) -> Optional[Any]: return 32 @property def __A ( self : Optional[int] ) -> Optional[int]: return 32 @property def __A ( self : Optional[int] ) -> List[Any]: return self.time_input_dim * 4 @property def __A ( self : str ) -> List[Any]: return 8 @property def __A ( self : Optional[Any] ) -> Union[str, Any]: torch.manual_seed(0 ) __lowerCamelCase = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) __lowerCamelCase = CLIPVisionModel(SCREAMING_SNAKE_CASE__ ) return model @property def __A ( self : Union[str, Any] ) -> Union[str, Any]: __lowerCamelCase = CLIPImageProcessor( crop_size=2_24 , do_center_crop=SCREAMING_SNAKE_CASE__ , do_normalize=SCREAMING_SNAKE_CASE__ , do_resize=SCREAMING_SNAKE_CASE__ , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=2_24 , ) return image_processor @property def __A ( self : Dict ) -> int: torch.manual_seed(0 ) __lowerCamelCase = { '''num_attention_heads''': 2, '''attention_head_dim''': 16, '''embedding_dim''': self.time_input_dim, '''num_embeddings''': 32, '''embedding_proj_dim''': self.text_embedder_hidden_size, '''time_embed_dim''': self.time_embed_dim, '''num_layers''': 1, '''clip_embed_dim''': self.time_input_dim * 2, '''additional_embeddings''': 0, '''time_embed_act_fn''': '''gelu''', '''norm_in_type''': '''layer''', '''embedding_proj_norm_type''': '''layer''', '''encoder_hid_proj_type''': None, '''added_emb_type''': None, } __lowerCamelCase = PriorTransformer(**SCREAMING_SNAKE_CASE__ ) return model @property def __A ( self : Tuple ) -> Dict: torch.manual_seed(0 ) __lowerCamelCase = { '''param_shapes''': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), '''d_latent''': self.time_input_dim, '''d_hidden''': self.renderer_dim, '''n_output''': 12, '''background''': ( 0.1, 0.1, 0.1, ), } __lowerCamelCase = ShapERenderer(**SCREAMING_SNAKE_CASE__ ) return model def __A ( self : Optional[int] ) -> List[str]: __lowerCamelCase = self.dummy_prior __lowerCamelCase = self.dummy_image_encoder __lowerCamelCase = self.dummy_image_processor __lowerCamelCase = self.dummy_renderer __lowerCamelCase = HeunDiscreteScheduler( beta_schedule='''exp''' , num_train_timesteps=10_24 , prediction_type='''sample''' , use_karras_sigmas=SCREAMING_SNAKE_CASE__ , clip_sample=SCREAMING_SNAKE_CASE__ , clip_sample_range=1.0 , ) __lowerCamelCase = { '''prior''': prior, '''image_encoder''': image_encoder, '''image_processor''': image_processor, '''renderer''': renderer, '''scheduler''': scheduler, } return components def __A ( self : str , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any=0 ) -> int: __lowerCamelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) if str(SCREAMING_SNAKE_CASE__ ).startswith('''mps''' ): __lowerCamelCase = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: __lowerCamelCase = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = { '''image''': input_image, '''generator''': generator, '''num_inference_steps''': 1, '''frame_size''': 32, '''output_type''': '''np''', } return inputs def __A ( self : Union[str, Any] ) -> Dict: __lowerCamelCase = '''cpu''' __lowerCamelCase = self.get_dummy_components() __lowerCamelCase = self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe(**self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = output.images[0] __lowerCamelCase = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __lowerCamelCase = np.array( [ 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __A ( self : str ) -> Tuple: # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def __A ( self : Optional[Any] ) -> str: __lowerCamelCase = torch_device == '''cpu''' __lowerCamelCase = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=SCREAMING_SNAKE_CASE__ , relax_max_difference=SCREAMING_SNAKE_CASE__ , ) def __A ( self : Dict ) -> Optional[int]: __lowerCamelCase = self.get_dummy_components() __lowerCamelCase = self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = 1 __lowerCamelCase = 2 __lowerCamelCase = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) for key in inputs.keys(): if key in self.batch_params: __lowerCamelCase = batch_size * [inputs[key]] __lowerCamelCase = pipe(**SCREAMING_SNAKE_CASE__ , num_images_per_prompt=SCREAMING_SNAKE_CASE__ )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : str ) -> Union[str, Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self : str ) -> Union[str, Any]: __lowerCamelCase = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/corgi.png''' ) __lowerCamelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/test_shap_e_img2img_out.npy''' ) __lowerCamelCase = ShapEImgaImgPipeline.from_pretrained('''openai/shap-e-img2img''' ) __lowerCamelCase = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(0 ) __lowerCamelCase = pipe( SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type='''np''' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
339
0
# flake8: noqa # Lint as: python3 SCREAMING_SNAKE_CASE__ : Any = [ "VerificationMode", "Version", "disable_progress_bar", "enable_progress_bar", "is_progress_bar_enabled", "experimental", ] from .info_utils import VerificationMode from .logging import disable_progress_bar, enable_progress_bar, is_progress_bar_enabled from .version import Version from .experimental import experimental
367
import glob import os import random from string import ascii_lowercase, digits import cva SCREAMING_SNAKE_CASE__ : str = "" SCREAMING_SNAKE_CASE__ : Any = "" SCREAMING_SNAKE_CASE__ : Optional[Any] = "" SCREAMING_SNAKE_CASE__ : Optional[Any] = 1 # (0 is vertical, 1 is horizontal) def __magic_name__ ( ) -> None: __lowerCamelCase , __lowerCamelCase = get_dataset(__lowerCAmelCase , __lowerCAmelCase ) print('''Processing...''' ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = update_image_and_anno(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) for index, image in enumerate(__lowerCAmelCase ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' __lowerCamelCase = random_chars(32 ) __lowerCamelCase = paths[index].split(os.sep )[-1].rsplit('''.''' , 1 )[0] __lowerCamelCase = f'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(f'''/{file_root}.jpg''' , __lowerCAmelCase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(f'''Success {index+1}/{len(__lowerCAmelCase )} with {file_name}''' ) __lowerCamelCase = [] for anno in new_annos[index]: __lowerCamelCase = f'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(__lowerCAmelCase ) with open(f'''/{file_root}.txt''' , '''w''' ) as outfile: outfile.write('''\n'''.join(line for line in annos_list ) ) def __magic_name__ ( __lowerCAmelCase : str , __lowerCAmelCase : str ) -> tuple[list, list]: __lowerCamelCase = [] __lowerCamelCase = [] for label_file in glob.glob(os.path.join(__lowerCAmelCase , '''*.txt''' ) ): __lowerCamelCase = label_file.split(os.sep )[-1].rsplit('''.''' , 1 )[0] with open(__lowerCAmelCase ) as in_file: __lowerCamelCase = in_file.readlines() __lowerCamelCase = os.path.join(__lowerCAmelCase , f'''{label_name}.jpg''' ) __lowerCamelCase = [] for obj_list in obj_lists: __lowerCamelCase = obj_list.rstrip('''\n''' ).split(''' ''' ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(__lowerCAmelCase ) labels.append(__lowerCAmelCase ) return img_paths, labels def __magic_name__ ( __lowerCAmelCase : list , __lowerCAmelCase : list , __lowerCAmelCase : int = 1 ) -> tuple[list, list, list]: __lowerCamelCase = [] __lowerCamelCase = [] __lowerCamelCase = [] for idx in range(len(__lowerCAmelCase ) ): __lowerCamelCase = [] __lowerCamelCase = img_list[idx] path_list.append(__lowerCAmelCase ) __lowerCamelCase = anno_list[idx] __lowerCamelCase = cva.imread(__lowerCAmelCase ) if flip_type == 1: __lowerCamelCase = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: __lowerCamelCase = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: __lowerCamelCase = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: __lowerCamelCase = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(__lowerCAmelCase ) new_imgs_list.append(__lowerCAmelCase ) return new_imgs_list, new_annos_lists, path_list def __magic_name__ ( __lowerCAmelCase : int = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" __lowerCamelCase = ascii_lowercase + digits return "".join(random.choice(__lowerCAmelCase ) for _ in range(__lowerCAmelCase ) ) if __name__ == "__main__": main() print("DONE ✅")
339
0
from __future__ import annotations SCREAMING_SNAKE_CASE__ : Dict = 8.988E9 # units = N * m^s * C^-2 def __magic_name__ ( __lowerCAmelCase : float , __lowerCAmelCase : float , __lowerCAmelCase : float , __lowerCAmelCase : float ) -> dict[str, float]: __lowerCamelCase = abs(chargea * chargea ) if (force, chargea, chargea, distance).count(0 ) != 1: raise ValueError('''One and only one argument must be 0''' ) if distance < 0: raise ValueError('''Distance cannot be negative''' ) if force == 0: __lowerCamelCase = COULOMBS_CONSTANT * charge_product / (distance**2) return {"force": force} elif chargea == 0: __lowerCamelCase = abs(__lowerCAmelCase ) * (distance**2) / (COULOMBS_CONSTANT * chargea) return {"charge1": chargea} elif chargea == 0: __lowerCamelCase = abs(__lowerCAmelCase ) * (distance**2) / (COULOMBS_CONSTANT * chargea) return {"charge2": chargea} elif distance == 0: __lowerCamelCase = (COULOMBS_CONSTANT * charge_product / abs(__lowerCAmelCase )) ** 0.5 return {"distance": distance} raise ValueError('''Exactly one argument must be 0''' ) if __name__ == "__main__": import doctest doctest.testmod()
368
import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated SCREAMING_SNAKE_CASE__ : Tuple = collections.namedtuple("_Datasets", ["train", "validation", "test"]) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ SCREAMING_SNAKE_CASE__ : List[str] = "https://storage.googleapis.com/cvdf-datasets/mnist/" def __magic_name__ ( __lowerCAmelCase : Any ) -> int: __lowerCamelCase = numpy.dtype(numpy.uintaa ).newbyteorder('''>''' ) return numpy.frombuffer(bytestream.read(4 ) , dtype=__lowerCAmelCase )[0] @deprecated(__lowerCAmelCase , '''Please use tf.data to implement this functionality.''' ) def __magic_name__ ( __lowerCAmelCase : List[Any] ) -> str: print('''Extracting''' , f.name ) with gzip.GzipFile(fileobj=__lowerCAmelCase ) as bytestream: __lowerCamelCase = _readaa(__lowerCAmelCase ) if magic != 2051: raise ValueError( '''Invalid magic number %d in MNIST image file: %s''' % (magic, f.name) ) __lowerCamelCase = _readaa(__lowerCAmelCase ) __lowerCamelCase = _readaa(__lowerCAmelCase ) __lowerCamelCase = _readaa(__lowerCAmelCase ) __lowerCamelCase = bytestream.read(rows * cols * num_images ) __lowerCamelCase = numpy.frombuffer(__lowerCAmelCase , dtype=numpy.uinta ) __lowerCamelCase = data.reshape(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , 1 ) return data @deprecated(__lowerCAmelCase , '''Please use tf.one_hot on tensors.''' ) def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : List[Any] ) -> Dict: __lowerCamelCase = labels_dense.shape[0] __lowerCamelCase = numpy.arange(__lowerCAmelCase ) * num_classes __lowerCamelCase = numpy.zeros((num_labels, num_classes) ) __lowerCamelCase = 1 return labels_one_hot @deprecated(__lowerCAmelCase , '''Please use tf.data to implement this functionality.''' ) def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : str=False , __lowerCAmelCase : List[str]=10 ) -> List[str]: print('''Extracting''' , f.name ) with gzip.GzipFile(fileobj=__lowerCAmelCase ) as bytestream: __lowerCamelCase = _readaa(__lowerCAmelCase ) if magic != 2049: raise ValueError( '''Invalid magic number %d in MNIST label file: %s''' % (magic, f.name) ) __lowerCamelCase = _readaa(__lowerCAmelCase ) __lowerCamelCase = bytestream.read(__lowerCAmelCase ) __lowerCamelCase = numpy.frombuffer(__lowerCAmelCase , dtype=numpy.uinta ) if one_hot: return _dense_to_one_hot(__lowerCAmelCase , __lowerCAmelCase ) return labels class lowerCAmelCase__ : @deprecated( SCREAMING_SNAKE_CASE__ , '''Please use alternatives such as official/mnist/_DataSet.py''' ''' from tensorflow/models.''' , ) def __init__( self : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : List[str]=False , SCREAMING_SNAKE_CASE__ : str=dtypes.floataa , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : str=None , ) -> Optional[int]: __lowerCamelCase , __lowerCamelCase = random_seed.get_seed(SCREAMING_SNAKE_CASE__ ) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seeda if seed is None else seeda ) __lowerCamelCase = dtypes.as_dtype(SCREAMING_SNAKE_CASE__ ).base_dtype if dtype not in (dtypes.uinta, dtypes.floataa): raise TypeError('''Invalid image dtype %r, expected uint8 or float32''' % dtype ) if fake_data: __lowerCamelCase = 1_00_00 __lowerCamelCase = one_hot else: assert ( images.shape[0] == labels.shape[0] ), f'''images.shape: {images.shape} labels.shape: {labels.shape}''' __lowerCamelCase = images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 __lowerCamelCase = images.reshape( images.shape[0] , images.shape[1] * images.shape[2] ) if dtype == dtypes.floataa: # Convert from [0, 255] -> [0.0, 1.0]. __lowerCamelCase = images.astype(numpy.floataa ) __lowerCamelCase = numpy.multiply(SCREAMING_SNAKE_CASE__ , 1.0 / 255.0 ) __lowerCamelCase = images __lowerCamelCase = labels __lowerCamelCase = 0 __lowerCamelCase = 0 @property def __A ( self : str ) -> Optional[int]: return self._images @property def __A ( self : Any ) -> Dict: return self._labels @property def __A ( self : List[Any] ) -> int: return self._num_examples @property def __A ( self : str ) -> Any: return self._epochs_completed def __A ( self : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : str=True ) -> str: if fake_data: __lowerCamelCase = [1] * 7_84 __lowerCamelCase = [1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(SCREAMING_SNAKE_CASE__ )], [fake_label for _ in range(SCREAMING_SNAKE_CASE__ )], ) __lowerCamelCase = self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: __lowerCamelCase = numpy.arange(self._num_examples ) numpy.random.shuffle(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.images[perma] __lowerCamelCase = self.labels[perma] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch __lowerCamelCase = self._num_examples - start __lowerCamelCase = self._images[start : self._num_examples] __lowerCamelCase = self._labels[start : self._num_examples] # Shuffle the data if shuffle: __lowerCamelCase = numpy.arange(self._num_examples ) numpy.random.shuffle(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.images[perm] __lowerCamelCase = self.labels[perm] # Start next epoch __lowerCamelCase = 0 __lowerCamelCase = batch_size - rest_num_examples __lowerCamelCase = self._index_in_epoch __lowerCamelCase = self._images[start:end] __lowerCamelCase = self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part) , axis=0 ), numpy.concatenate((labels_rest_part, labels_new_part) , axis=0 ), ) else: self._index_in_epoch += batch_size __lowerCamelCase = self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(__lowerCAmelCase , '''Please write your own downloading logic.''' ) def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int , __lowerCAmelCase : Union[str, Any] ) -> List[Any]: if not gfile.Exists(__lowerCAmelCase ): gfile.MakeDirs(__lowerCAmelCase ) __lowerCamelCase = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) if not gfile.Exists(__lowerCAmelCase ): urllib.request.urlretrieve(__lowerCAmelCase , __lowerCAmelCase ) # noqa: S310 with gfile.GFile(__lowerCAmelCase ) as f: __lowerCamelCase = f.size() print('''Successfully downloaded''' , __lowerCAmelCase , __lowerCAmelCase , '''bytes.''' ) return filepath @deprecated( __lowerCAmelCase , '''Please use alternatives such as:''' ''' tensorflow_datasets.load(\'mnist\')''' ) def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[Any]=False , __lowerCAmelCase : Dict=False , __lowerCAmelCase : List[str]=dtypes.floataa , __lowerCAmelCase : Union[str, Any]=True , __lowerCAmelCase : int=5000 , __lowerCAmelCase : Any=None , __lowerCAmelCase : List[str]=DEFAULT_SOURCE_URL , ) -> Optional[Any]: if fake_data: def fake(): return _DataSet( [] , [] , fake_data=__lowerCAmelCase , one_hot=__lowerCAmelCase , dtype=__lowerCAmelCase , seed=__lowerCAmelCase ) __lowerCamelCase = fake() __lowerCamelCase = fake() __lowerCamelCase = fake() return _Datasets(train=__lowerCAmelCase , validation=__lowerCAmelCase , test=__lowerCAmelCase ) if not source_url: # empty string check __lowerCamelCase = DEFAULT_SOURCE_URL __lowerCamelCase = '''train-images-idx3-ubyte.gz''' __lowerCamelCase = '''train-labels-idx1-ubyte.gz''' __lowerCamelCase = '''t10k-images-idx3-ubyte.gz''' __lowerCamelCase = '''t10k-labels-idx1-ubyte.gz''' __lowerCamelCase = _maybe_download( __lowerCAmelCase , __lowerCAmelCase , source_url + train_images_file ) with gfile.Open(__lowerCAmelCase , '''rb''' ) as f: __lowerCamelCase = _extract_images(__lowerCAmelCase ) __lowerCamelCase = _maybe_download( __lowerCAmelCase , __lowerCAmelCase , source_url + train_labels_file ) with gfile.Open(__lowerCAmelCase , '''rb''' ) as f: __lowerCamelCase = _extract_labels(__lowerCAmelCase , one_hot=__lowerCAmelCase ) __lowerCamelCase = _maybe_download( __lowerCAmelCase , __lowerCAmelCase , source_url + test_images_file ) with gfile.Open(__lowerCAmelCase , '''rb''' ) as f: __lowerCamelCase = _extract_images(__lowerCAmelCase ) __lowerCamelCase = _maybe_download( __lowerCAmelCase , __lowerCAmelCase , source_url + test_labels_file ) with gfile.Open(__lowerCAmelCase , '''rb''' ) as f: __lowerCamelCase = _extract_labels(__lowerCAmelCase , one_hot=__lowerCAmelCase ) if not 0 <= validation_size <= len(__lowerCAmelCase ): __lowerCamelCase = ( '''Validation size should be between 0 and ''' f'''{len(__lowerCAmelCase )}. Received: {validation_size}.''' ) raise ValueError(__lowerCAmelCase ) __lowerCamelCase = train_images[:validation_size] __lowerCamelCase = train_labels[:validation_size] __lowerCamelCase = train_images[validation_size:] __lowerCamelCase = train_labels[validation_size:] __lowerCamelCase = {'''dtype''': dtype, '''reshape''': reshape, '''seed''': seed} __lowerCamelCase = _DataSet(__lowerCAmelCase , __lowerCAmelCase , **__lowerCAmelCase ) __lowerCamelCase = _DataSet(__lowerCAmelCase , __lowerCAmelCase , **__lowerCAmelCase ) __lowerCamelCase = _DataSet(__lowerCAmelCase , __lowerCAmelCase , **__lowerCAmelCase ) return _Datasets(train=__lowerCAmelCase , validation=__lowerCAmelCase , test=__lowerCAmelCase )
339
0
import warnings from ...utils import logging from .image_processing_yolos import YolosImageProcessor SCREAMING_SNAKE_CASE__ : Tuple = logging.get_logger(__name__) class lowerCAmelCase__ ( __lowercase ): def __init__( self : List[Any] , *SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> None: warnings.warn( '''The class YolosFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use YolosImageProcessor instead.''' , SCREAMING_SNAKE_CASE__ , ) super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
369
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_squeezebert import SqueezeBertTokenizer SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Dict = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "vocab_file": { "squeezebert/squeezebert-uncased": ( "https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt" ), "squeezebert/squeezebert-mnli": "https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt", "squeezebert/squeezebert-mnli-headless": ( "https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt" ), }, "tokenizer_file": { "squeezebert/squeezebert-uncased": ( "https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/tokenizer.json" ), "squeezebert/squeezebert-mnli": ( "https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/tokenizer.json" ), "squeezebert/squeezebert-mnli-headless": ( "https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/tokenizer.json" ), }, } SCREAMING_SNAKE_CASE__ : List[Any] = { "squeezebert/squeezebert-uncased": 512, "squeezebert/squeezebert-mnli": 512, "squeezebert/squeezebert-mnli-headless": 512, } SCREAMING_SNAKE_CASE__ : Dict = { "squeezebert/squeezebert-uncased": {"do_lower_case": True}, "squeezebert/squeezebert-mnli": {"do_lower_case": True}, "squeezebert/squeezebert-mnli-headless": {"do_lower_case": True}, } class lowerCAmelCase__ ( __lowercase ): a__ : Optional[int] = VOCAB_FILES_NAMES a__ : Any = PRETRAINED_VOCAB_FILES_MAP a__ : Union[str, Any] = PRETRAINED_INIT_CONFIGURATION a__ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ : Optional[Any] = SqueezeBertTokenizer def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[UNK]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[PAD]" , SCREAMING_SNAKE_CASE__ : Tuple="[CLS]" , SCREAMING_SNAKE_CASE__ : str="[MASK]" , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : int=None , **SCREAMING_SNAKE_CASE__ : Dict , ) -> Optional[Any]: super().__init__( SCREAMING_SNAKE_CASE__ , tokenizer_file=SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , tokenize_chinese_chars=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = 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 ): __lowerCamelCase = getattr(SCREAMING_SNAKE_CASE__ , normalizer_state.pop('''type''' ) ) __lowerCamelCase = do_lower_case __lowerCamelCase = strip_accents __lowerCamelCase = tokenize_chinese_chars __lowerCamelCase = normalizer_class(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = do_lower_case def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[str]=None ) -> str: __lowerCamelCase = [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 : Tuple , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: __lowerCamelCase = [self.sep_token_id] __lowerCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __A ( self : int , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: __lowerCamelCase = self._tokenizer.model.save(SCREAMING_SNAKE_CASE__ , name=SCREAMING_SNAKE_CASE__ ) return tuple(SCREAMING_SNAKE_CASE__ )
339
0
from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo SCREAMING_SNAKE_CASE__ : Union[str, Any] = "\\n@misc{wu2016googles,\n title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey\n and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin\n Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto\n Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and\n Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes\n and Jeffrey Dean},\n year={2016},\n eprint={1609.08144},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}\n" SCREAMING_SNAKE_CASE__ : Tuple = "\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe 'GLEU score'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore's range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n" SCREAMING_SNAKE_CASE__ : str = "\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n predictions (list of str): list of translations to score.\n Each translation should be tokenized into a list of tokens.\n references (list of list of str): list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\n min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n 'google_bleu': google_bleu score\n\nExamples:\n Example 1:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.44\n\n Example 2:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n ... 'heed', 'the', 'cat', 'commands']\n >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n ... 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.61\n\n Example 3:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n ... 'heed', 'the', 'cat', 'commands']\n >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n ... 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.53\n\n Example 4:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n ... 'heed', 'the', 'cat', 'commands']\n >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n ... 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.4\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): def __A ( self : str ) -> MetricInfo: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''' , id='''token''' ) , id='''sequence''' ), '''references''': datasets.Sequence( datasets.Sequence(datasets.Value('''string''' , id='''token''' ) , id='''sequence''' ) , id='''references''' ), } ) , ) def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : List[List[List[str]]] , SCREAMING_SNAKE_CASE__ : List[List[str]] , SCREAMING_SNAKE_CASE__ : int = 1 , SCREAMING_SNAKE_CASE__ : int = 4 , ) -> Dict[str, float]: return { "google_bleu": gleu_score.corpus_gleu( list_of_references=SCREAMING_SNAKE_CASE__ , hypotheses=SCREAMING_SNAKE_CASE__ , min_len=SCREAMING_SNAKE_CASE__ , max_len=SCREAMING_SNAKE_CASE__ ) }
370
from __future__ import annotations def __magic_name__ ( __lowerCAmelCase : list[int] ) -> bool: return len(set(__lowerCAmelCase ) ) == len(__lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
339
0
from __future__ import annotations SCREAMING_SNAKE_CASE__ : Any = list[list[int]] # assigning initial values to the grid SCREAMING_SNAKE_CASE__ : Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution SCREAMING_SNAKE_CASE__ : Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def __magic_name__ ( __lowerCAmelCase : Matrix , __lowerCAmelCase : int , __lowerCAmelCase : int , __lowerCAmelCase : int ) -> bool: for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def __magic_name__ ( __lowerCAmelCase : Matrix ) -> tuple[int, int] | None: for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def __magic_name__ ( __lowerCAmelCase : Matrix ) -> Matrix | None: if location := find_empty_location(__lowerCAmelCase ): __lowerCamelCase , __lowerCamelCase = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 10 ): if is_safe(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): __lowerCamelCase = digit if sudoku(__lowerCAmelCase ) is not None: return grid __lowerCamelCase = 0 return None def __magic_name__ ( __lowerCAmelCase : Matrix ) -> None: for row in grid: for cell in row: print(__lowerCAmelCase , end=''' ''' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print("\nExample grid:\n" + "=" * 20) print_solution(example_grid) print("\nExample grid solution:") SCREAMING_SNAKE_CASE__ : Dict = sudoku(example_grid) if solution is not None: print_solution(solution) else: print("Cannot find a solution.")
371
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) SCREAMING_SNAKE_CASE__ : Dict = { "configuration_falcon": ["FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP", "FalconConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Tuple = [ "FALCON_PRETRAINED_MODEL_ARCHIVE_LIST", "FalconForCausalLM", "FalconModel", "FalconPreTrainedModel", "FalconForSequenceClassification", "FalconForTokenClassification", "FalconForQuestionAnswering", ] if TYPE_CHECKING: from .configuration_falcon import FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP, FalconConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_falcon import ( FALCON_PRETRAINED_MODEL_ARCHIVE_LIST, FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, FalconPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
339
0
import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def __magic_name__ ( __lowerCAmelCase : List[str] ) -> Union[str, Any]: # encoder.embeddings are double copied in original FLAVA return sum(param.float().sum() if '''encoder.embeddings''' not in key else 0 for key, param in state_dict.items() ) def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : int ) -> str: __lowerCamelCase = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue __lowerCamelCase = key.replace('''heads.cmd.mim_head.cls.predictions''' , '''mmm_image_head''' ) __lowerCamelCase = key.replace('''heads.cmd.mlm_head.cls.predictions''' , '''mmm_text_head''' ) __lowerCamelCase = key.replace('''heads.cmd.itm_head.cls''' , '''itm_head''' ) __lowerCamelCase = key.replace('''heads.cmd.itm_head.pooler''' , '''itm_head.pooler''' ) __lowerCamelCase = key.replace('''heads.cmd.clip_head.logit_scale''' , '''flava.logit_scale''' ) __lowerCamelCase = key.replace('''heads.fairseq_mlm.cls.predictions''' , '''mlm_head''' ) __lowerCamelCase = key.replace('''heads.imagenet.mim_head.cls.predictions''' , '''mim_head''' ) __lowerCamelCase = key.replace('''mm_text_projection''' , '''flava.text_to_mm_projection''' ) __lowerCamelCase = key.replace('''mm_image_projection''' , '''flava.image_to_mm_projection''' ) __lowerCamelCase = key.replace('''image_encoder.module''' , '''flava.image_model''' ) __lowerCamelCase = key.replace('''text_encoder.module''' , '''flava.text_model''' ) __lowerCamelCase = key.replace('''mm_encoder.module.encoder.cls_token''' , '''flava.multimodal_model.cls_token''' ) __lowerCamelCase = key.replace('''mm_encoder.module''' , '''flava.multimodal_model''' ) __lowerCamelCase = key.replace('''text_projection''' , '''flava.text_projection''' ) __lowerCamelCase = key.replace('''image_projection''' , '''flava.image_projection''' ) __lowerCamelCase = value.float() for key, value in codebook_state_dict.items(): __lowerCamelCase = value return upgrade @torch.no_grad() def __magic_name__ ( __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Dict , __lowerCAmelCase : List[str] , __lowerCAmelCase : Any=None ) -> Any: if config_path is not None: __lowerCamelCase = FlavaConfig.from_pretrained(__lowerCAmelCase ) else: __lowerCamelCase = FlavaConfig() __lowerCamelCase = FlavaForPreTraining(__lowerCAmelCase ).eval() __lowerCamelCase = convert_dalle_checkpoint(__lowerCAmelCase , __lowerCAmelCase , save_checkpoint=__lowerCAmelCase ) if os.path.exists(__lowerCAmelCase ): __lowerCamelCase = torch.load(__lowerCAmelCase , map_location='''cpu''' ) else: __lowerCamelCase = torch.hub.load_state_dict_from_url(__lowerCAmelCase , map_location='''cpu''' ) __lowerCamelCase = upgrade_state_dict(__lowerCAmelCase , __lowerCAmelCase ) hf_model.load_state_dict(__lowerCAmelCase ) __lowerCamelCase = hf_model.state_dict() __lowerCamelCase = count_parameters(__lowerCAmelCase ) __lowerCamelCase = count_parameters(__lowerCAmelCase ) + count_parameters(__lowerCAmelCase ) assert torch.allclose(__lowerCAmelCase , __lowerCAmelCase , atol=1E-3 ) hf_model.save_pretrained(__lowerCAmelCase ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to flava checkpoint") parser.add_argument("--codebook_path", default=None, type=str, help="Path to flava codebook checkpoint") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") SCREAMING_SNAKE_CASE__ = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
350
def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int ) -> int: return abs(__lowerCAmelCase ) if a == 0 else greatest_common_divisor(b % a , __lowerCAmelCase ) def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int ) -> int: while y: # --> when y=0 then loop will terminate and return x as final GCD. __lowerCamelCase , __lowerCamelCase = y, x % y return abs(__lowerCAmelCase ) def __magic_name__ ( ) -> Tuple: try: __lowerCamelCase = input('''Enter two integers separated by comma (,): ''' ).split(''',''' ) __lowerCamelCase = int(nums[0] ) __lowerCamelCase = int(nums[1] ) print( f'''greatest_common_divisor({num_a}, {num_a}) = ''' f'''{greatest_common_divisor(__lowerCAmelCase , __lowerCAmelCase )}''' ) print(f'''By iterative gcd({num_a}, {num_a}) = {gcd_by_iterative(__lowerCAmelCase , __lowerCAmelCase )}''' ) except (IndexError, UnboundLocalError, ValueError): print('''Wrong input''' ) if __name__ == "__main__": main()
339
0
"""simple docstring""" def __magic_name__ ( __lowerCAmelCase : int ) -> int: if not isinstance(__lowerCAmelCase , __lowerCAmelCase ): __lowerCamelCase = f'''Input value of [number={number}] must be an integer''' raise TypeError(__lowerCAmelCase ) if number < 1: __lowerCamelCase = f'''Input value of [number={number}] must be > 0''' raise ValueError(__lowerCAmelCase ) __lowerCamelCase = 1 for i in range(1 , __lowerCAmelCase ): current_number *= 4 * i - 2 current_number //= i + 1 return current_number if __name__ == "__main__": import doctest doctest.testmod()
351
import unittest from transformers import is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, require_torch, slow if is_flax_available(): import optax from flax.training.common_utils import onehot from transformers import AutoTokenizer, FlaxMTaForConditionalGeneration from transformers.models.ta.modeling_flax_ta import shift_tokens_right @require_torch @require_sentencepiece @require_tokenizers @require_flax class lowerCAmelCase__ ( unittest.TestCase ): @slow def __A ( self : Optional[int] ) -> Union[str, Any]: __lowerCamelCase = FlaxMTaForConditionalGeneration.from_pretrained('''google/mt5-small''' ) __lowerCamelCase = AutoTokenizer.from_pretrained('''google/mt5-small''' ) __lowerCamelCase = tokenizer('''Hello there''' , return_tensors='''np''' ).input_ids __lowerCamelCase = tokenizer('''Hi I am''' , return_tensors='''np''' ).input_ids __lowerCamelCase = shift_tokens_right(SCREAMING_SNAKE_CASE__ , model.config.pad_token_id , model.config.decoder_start_token_id ) __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ , decoder_input_ids=SCREAMING_SNAKE_CASE__ ).logits __lowerCamelCase = optax.softmax_cross_entropy(SCREAMING_SNAKE_CASE__ , onehot(SCREAMING_SNAKE_CASE__ , logits.shape[-1] ) ).mean() __lowerCamelCase = -(labels.shape[-1] * loss.item()) __lowerCamelCase = -84.9127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1e-4 )
339
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available SCREAMING_SNAKE_CASE__ : Any = {"tokenization_herbert": ["HerbertTokenizer"]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = ["HerbertTokenizerFast"] if TYPE_CHECKING: from .tokenization_herbert import HerbertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_herbert_fast import HerbertTokenizerFast else: import sys SCREAMING_SNAKE_CASE__ : int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
352
import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer SCREAMING_SNAKE_CASE__ : Optional[int] = "bart" SCREAMING_SNAKE_CASE__ : Dict = True @st.cache(allow_output_mutation=__lowerCAmelCase ) def __magic_name__ ( ) -> str: if LOAD_DENSE_INDEX: __lowerCamelCase = AutoTokenizer.from_pretrained('''yjernite/retribert-base-uncased''' ) __lowerCamelCase = AutoModel.from_pretrained('''yjernite/retribert-base-uncased''' ).to('''cuda:0''' ) __lowerCamelCase = qar_model.eval() else: __lowerCamelCase , __lowerCamelCase = (None, None) if MODEL_TYPE == "bart": __lowerCamelCase = AutoTokenizer.from_pretrained('''yjernite/bart_eli5''' ) __lowerCamelCase = AutoModelForSeqaSeqLM.from_pretrained('''yjernite/bart_eli5''' ).to('''cuda:0''' ) __lowerCamelCase = torch.load('''seq2seq_models/eli5_bart_model_blm_2.pth''' ) sas_model.load_state_dict(save_dict['''model'''] ) __lowerCamelCase = sas_model.eval() else: __lowerCamelCase , __lowerCamelCase = make_qa_sas_model( model_name='''t5-small''' , from_file='''seq2seq_models/eli5_t5_model_1024_4.pth''' , device='''cuda:0''' ) return (qar_tokenizer, qar_model, sas_tokenizer, sas_model) @st.cache(allow_output_mutation=__lowerCAmelCase ) def __magic_name__ ( ) -> Optional[int]: if LOAD_DENSE_INDEX: __lowerCamelCase = faiss.StandardGpuResources() __lowerCamelCase = datasets.load_dataset(path='''wiki_snippets''' , name='''wiki40b_en_100_0''' )['''train'''] __lowerCamelCase = np.memmap( '''wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat''' , dtype='''float32''' , mode='''r''' , shape=(wikiaab_passages.num_rows, 128) , ) __lowerCamelCase = faiss.IndexFlatIP(128 ) __lowerCamelCase = faiss.index_cpu_to_gpu(__lowerCAmelCase , 1 , __lowerCAmelCase ) wikiaab_gpu_index_flat.add(__lowerCAmelCase ) # TODO fix for larger GPU else: __lowerCamelCase , __lowerCamelCase = (None, None) __lowerCamelCase = Elasticsearch([{'''host''': '''localhost''', '''port''': '''9200'''}] ) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=__lowerCAmelCase ) def __magic_name__ ( ) -> List[str]: __lowerCamelCase = datasets.load_dataset('''eli5''' , name='''LFQA_reddit''' ) __lowerCamelCase = elia['''train_eli5'''] __lowerCamelCase = np.memmap( '''eli5_questions_reps.dat''' , dtype='''float32''' , mode='''r''' , shape=(elia_train.num_rows, 128) ) __lowerCamelCase = faiss.IndexFlatIP(128 ) eli5_train_q_index.add(__lowerCAmelCase ) return (elia_train, eli5_train_q_index) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = load_indexes() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = load_models() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = load_train_data() def __magic_name__ ( __lowerCAmelCase : Dict , __lowerCAmelCase : List[str]=10 ) -> List[str]: __lowerCamelCase = embed_questions_for_retrieval([question] , __lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase , __lowerCamelCase = eli5_train_q_index.search(__lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase = [elia_train[int(__lowerCAmelCase )] for i in I[0]] return nn_examples def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : Dict="wiki40b" , __lowerCAmelCase : Any="dense" , __lowerCAmelCase : Dict=10 ) -> Union[str, Any]: if source == "none": __lowerCamelCase , __lowerCamelCase = (''' <P> '''.join(['''''' for _ in range(11 )] ).strip(), []) else: if method == "dense": __lowerCamelCase , __lowerCamelCase = query_qa_dense_index( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) else: __lowerCamelCase , __lowerCamelCase = query_es_index( __lowerCAmelCase , __lowerCAmelCase , index_name='''english_wiki40b_snippets_100w''' , n_results=__lowerCAmelCase , ) __lowerCamelCase = [ (res['''article_title'''], res['''section_title'''].strip(), res['''score'''], res['''passage_text''']) for res in hit_lst ] __lowerCamelCase = '''question: {} context: {}'''.format(__lowerCAmelCase , __lowerCAmelCase ) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda __lowerCAmelCase : None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda __lowerCAmelCase : None), } ) def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : Dict , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : str=64 , __lowerCAmelCase : Dict=256 , __lowerCAmelCase : Union[str, Any]=False , __lowerCAmelCase : Optional[int]=2 , __lowerCAmelCase : Optional[Any]=0.95 , __lowerCAmelCase : List[Any]=0.8 ) -> Any: with torch.no_grad(): __lowerCamelCase = qa_sas_generate( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , num_answers=1 , num_beams=__lowerCAmelCase , min_len=__lowerCAmelCase , max_len=__lowerCAmelCase , do_sample=__lowerCAmelCase , temp=__lowerCAmelCase , top_p=__lowerCAmelCase , top_k=__lowerCAmelCase , max_input_length=1024 , device='''cuda:0''' , )[0] return (answer, support_list) st.title("Long Form Question Answering with ELI5") # Start sidebar SCREAMING_SNAKE_CASE__ : List[str] = "<img src='https://huggingface.co/front/assets/huggingface_logo.svg'>" SCREAMING_SNAKE_CASE__ : Dict = "\n<html>\n <head>\n <style>\n .img-container {\n padding-left: 90px;\n padding-right: 90px;\n padding-top: 50px;\n padding-bottom: 50px;\n background-color: #f0f3f9;\n }\n </style>\n </head>\n <body>\n <span class=\"img-container\"> <!-- Inline parent element -->\n %s\n </span>\n </body>\n</html>\n" % ( header_html, ) st.sidebar.markdown( header_full, unsafe_allow_html=True, ) # Long Form QA with ELI5 and Wikipedia SCREAMING_SNAKE_CASE__ : int = "\nThis demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).\nFirst, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,\na pre-processed fixed snapshot of Wikipedia.\n" st.sidebar.markdown(description, unsafe_allow_html=True) SCREAMING_SNAKE_CASE__ : str = [ "Answer the question", "View the retrieved document only", "View the most similar ELI5 question and answer", "Show me everything, please!", ] SCREAMING_SNAKE_CASE__ : Optional[int] = st.sidebar.checkbox("Demo options") if demo_options: SCREAMING_SNAKE_CASE__ : Optional[int] = st.sidebar.selectbox( "", action_list, index=3, ) SCREAMING_SNAKE_CASE__ : Optional[Any] = action_list.index(action_st) SCREAMING_SNAKE_CASE__ : int = st.sidebar.selectbox( "", ["Show full text of passages", "Show passage section titles"], index=0, ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = show_type == "Show full text of passages" else: SCREAMING_SNAKE_CASE__ : Any = 3 SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : Union[str, Any] = st.sidebar.checkbox("Retrieval options") if retrieval_options: SCREAMING_SNAKE_CASE__ : Tuple = "\n ### Information retriever options\n\n The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding\n trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.\n The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.\n " st.sidebar.markdown(retriever_info) SCREAMING_SNAKE_CASE__ : Union[str, Any] = st.sidebar.selectbox("Which Wikipedia format should the model use?", ["wiki40b", "none"]) SCREAMING_SNAKE_CASE__ : int = st.sidebar.selectbox("Which Wikipedia indexer should the model use?", ["dense", "sparse", "mixed"]) else: SCREAMING_SNAKE_CASE__ : List[str] = "wiki40b" SCREAMING_SNAKE_CASE__ : Optional[Any] = "dense" SCREAMING_SNAKE_CASE__ : str = "beam" SCREAMING_SNAKE_CASE__ : List[Any] = 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = 64 SCREAMING_SNAKE_CASE__ : List[Any] = 256 SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : List[str] = st.sidebar.checkbox("Generation options") if generate_options: SCREAMING_SNAKE_CASE__ : Dict = "\n ### Answer generation options\n\n The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)\n weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with\n **beam** search, or **sample** from the decoder's output probabilities.\n " st.sidebar.markdown(generate_info) SCREAMING_SNAKE_CASE__ : List[str] = st.sidebar.selectbox("Would you like to use beam search or sample an answer?", ["beam", "sampled"]) SCREAMING_SNAKE_CASE__ : Any = st.sidebar.slider( "Minimum generation length", min_value=8, max_value=256, value=64, step=8, format=None, key=None ) SCREAMING_SNAKE_CASE__ : str = st.sidebar.slider( "Maximum generation length", min_value=64, max_value=512, value=256, step=16, format=None, key=None ) if sampled == "beam": SCREAMING_SNAKE_CASE__ : Union[str, Any] = st.sidebar.slider("Beam size", min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: SCREAMING_SNAKE_CASE__ : Any = st.sidebar.slider( "Nucleus sampling p", min_value=0.1, max_value=1.0, value=0.9_5, step=0.0_1, format=None, key=None ) SCREAMING_SNAKE_CASE__ : Dict = st.sidebar.slider( "Temperature", min_value=0.1, max_value=1.0, value=0.7, step=0.0_1, format=None, key=None ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = None # start main text SCREAMING_SNAKE_CASE__ : Any = [ "<MY QUESTION>", "How do people make chocolate?", "Why do we get a fever when we are sick?", "How can different animals perceive different colors?", "What is natural language processing?", "What's the best way to treat a sunburn?", "What exactly are vitamins ?", "How does nuclear energy provide electricity?", "What's the difference between viruses and bacteria?", "Why are flutes classified as woodwinds when most of them are made out of metal ?", "Why do people like drinking coffee even though it tastes so bad?", "What happens when wine ages? How does it make the wine taste better?", "If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?", "How can we set a date to the beginning or end of an artistic period? Doesn't the change happen gradually?", "How does New Zealand have so many large bird predators?", ] SCREAMING_SNAKE_CASE__ : List[str] = st.selectbox( "What would you like to ask? ---- select <MY QUESTION> to enter a new query", questions_list, index=1, ) if question_s == "<MY QUESTION>": SCREAMING_SNAKE_CASE__ : Union[str, Any] = st.text_input("Enter your question here:", "") else: SCREAMING_SNAKE_CASE__ : str = question_s if st.button("Show me!"): if action in [0, 1, 3]: if index_type == "mixed": SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = make_support(question, source=wiki_source, method="dense", n_results=10) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = make_support(question, source=wiki_source, method="sparse", n_results=10) SCREAMING_SNAKE_CASE__ : int = [] for res_d, res_s in zip(support_list_dense, support_list_sparse): if tuple(res_d) not in support_list: support_list += [tuple(res_d)] if tuple(res_s) not in support_list: support_list += [tuple(res_s)] SCREAMING_SNAKE_CASE__ : Optional[Any] = support_list[:10] SCREAMING_SNAKE_CASE__ : Tuple = "<P> " + " <P> ".join([res[-1] for res in support_list]) else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = answer_question( question_doc, sas_model, sas_tokenizer, min_len=min_len, max_len=int(max_len), sampling=(sampled == "sampled"), n_beams=n_beams, top_p=top_p, temp=temp, ) st.markdown("### The model generated answer is:") st.write(answer) if action in [0, 1, 3] and wiki_source != "none": st.markdown("--- \n ### The model is drawing information from the following Wikipedia passages:") for i, res in enumerate(support_list): SCREAMING_SNAKE_CASE__ : Optional[int] = "https://en.wikipedia.org/wiki/{}".format(res[0].replace(" ", "_")) SCREAMING_SNAKE_CASE__ : Tuple = res[1].strip() if sec_titles == "": SCREAMING_SNAKE_CASE__ : Union[str, Any] = "[{}]({})".format(res[0], wiki_url) else: SCREAMING_SNAKE_CASE__ : Dict = sec_titles.split(" & ") SCREAMING_SNAKE_CASE__ : int = " & ".join( ["[{}]({}#{})".format(sec.strip(), wiki_url, sec.strip().replace(" ", "_")) for sec in sec_list] ) st.markdown( "{0:02d} - **Article**: {1:<18} <br> _Section_: {2}".format(i + 1, res[0], sections), unsafe_allow_html=True, ) if show_passages: st.write( "> <span style=\"font-family:arial; font-size:10pt;\">" + res[-1] + "</span>", unsafe_allow_html=True ) if action in [2, 3]: SCREAMING_SNAKE_CASE__ : Any = find_nearest_training(question) SCREAMING_SNAKE_CASE__ : List[Any] = nn_train_list[0] st.markdown( "--- \n ### The most similar question in the ELI5 training set was: \n\n {}".format(train_exple["title"]) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ "{}. {}".format(i + 1, " \n".join([line.strip() for line in ans.split("\n") if line.strip() != ""])) for i, (ans, sc) in enumerate(zip(train_exple["answers"]["text"], train_exple["answers"]["score"])) if i == 0 or sc > 2 ] st.markdown("##### Its answers were: \n\n {}".format("\n".join(answers_st))) SCREAMING_SNAKE_CASE__ : List[Any] = "\n---\n\n**Disclaimer**\n\n*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.\nEvaluating biases of such a model and ensuring factual generations are still very much open research problems.\nTherefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*\n" st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
339
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available SCREAMING_SNAKE_CASE__ : List[Any] = { "configuration_nezha": ["NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP", "NezhaConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [ "NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST", "NezhaForNextSentencePrediction", "NezhaForMaskedLM", "NezhaForPreTraining", "NezhaForMultipleChoice", "NezhaForQuestionAnswering", "NezhaForSequenceClassification", "NezhaForTokenClassification", "NezhaModel", "NezhaPreTrainedModel", ] if TYPE_CHECKING: from .configuration_nezha import NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP, NezhaConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nezha import ( NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, NezhaPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
353
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : List[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : str = { "facebook/xmod-base": "https://huggingface.co/facebook/xmod-base/resolve/main/config.json", "facebook/xmod-large-prenorm": "https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json", "facebook/xmod-base-13-125k": "https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json", "facebook/xmod-base-30-125k": "https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json", "facebook/xmod-base-30-195k": "https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json", "facebook/xmod-base-60-125k": "https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json", "facebook/xmod-base-60-265k": "https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json", "facebook/xmod-base-75-125k": "https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json", "facebook/xmod-base-75-269k": "https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json", } class lowerCAmelCase__ ( __lowercase ): a__ : Dict = """xmod""" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3_05_22 , SCREAMING_SNAKE_CASE__ : str=7_68 , SCREAMING_SNAKE_CASE__ : int=12 , SCREAMING_SNAKE_CASE__ : Dict=12 , SCREAMING_SNAKE_CASE__ : List[str]=30_72 , SCREAMING_SNAKE_CASE__ : List[Any]="gelu" , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : int=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=5_12 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=0.02 , SCREAMING_SNAKE_CASE__ : Optional[Any]=1e-12 , SCREAMING_SNAKE_CASE__ : List[str]=1 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0 , SCREAMING_SNAKE_CASE__ : int=2 , SCREAMING_SNAKE_CASE__ : Any="absolute" , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : Tuple=2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Dict=("en_XX",) , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , **SCREAMING_SNAKE_CASE__ : int , ) -> str: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = vocab_size __lowerCamelCase = hidden_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = hidden_act __lowerCamelCase = intermediate_size __lowerCamelCase = hidden_dropout_prob __lowerCamelCase = attention_probs_dropout_prob __lowerCamelCase = max_position_embeddings __lowerCamelCase = type_vocab_size __lowerCamelCase = initializer_range __lowerCamelCase = layer_norm_eps __lowerCamelCase = position_embedding_type __lowerCamelCase = use_cache __lowerCamelCase = classifier_dropout __lowerCamelCase = pre_norm __lowerCamelCase = adapter_reduction_factor __lowerCamelCase = adapter_layer_norm __lowerCamelCase = adapter_reuse_layer_norm __lowerCamelCase = ln_before_adapter __lowerCamelCase = list(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = default_language class lowerCAmelCase__ ( __lowercase ): @property def __A ( self : Optional[Any] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": __lowerCamelCase = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: __lowerCamelCase = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
339
0
import unittest import numpy as np from transformers import RoFormerConfig, 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.roformer.modeling_flax_roformer import ( FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, ) class lowerCAmelCase__ ( unittest.TestCase ): def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : List[str]=13 , SCREAMING_SNAKE_CASE__ : int=7 , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=99 , SCREAMING_SNAKE_CASE__ : Tuple=32 , SCREAMING_SNAKE_CASE__ : Dict=5 , SCREAMING_SNAKE_CASE__ : Any=4 , SCREAMING_SNAKE_CASE__ : str=37 , SCREAMING_SNAKE_CASE__ : Any="gelu" , SCREAMING_SNAKE_CASE__ : Tuple=0.1 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.1 , SCREAMING_SNAKE_CASE__ : str=5_12 , SCREAMING_SNAKE_CASE__ : Tuple=16 , SCREAMING_SNAKE_CASE__ : Optional[int]=2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE__ : int=4 , ) -> List[str]: __lowerCamelCase = parent __lowerCamelCase = batch_size __lowerCamelCase = seq_length __lowerCamelCase = is_training __lowerCamelCase = use_attention_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_choices def __A ( self : str ) -> List[Any]: __lowerCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCamelCase = None if self.use_attention_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 = RoFormerConfig( 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=SCREAMING_SNAKE_CASE__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def __A ( self : Union[str, Any] ) -> int: __lowerCamelCase = self.prepare_config_and_inputs() __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = config_and_inputs __lowerCamelCase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict @require_flax class lowerCAmelCase__ ( __lowercase , unittest.TestCase ): a__ : str = True a__ : Dict = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def __A ( self : List[Any] ) -> List[Any]: __lowerCamelCase = FlaxRoFormerModelTester(self ) @slow def __A ( self : Tuple ) -> Optional[Any]: for model_class_name in self.all_model_classes: __lowerCamelCase = model_class_name.from_pretrained('''junnyu/roformer_chinese_small''' , from_pt=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model(np.ones((1, 1) ) ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_flax class lowerCAmelCase__ ( unittest.TestCase ): @slow def __A ( self : Optional[int] ) -> List[Any]: __lowerCamelCase = FlaxRoFormerForMaskedLM.from_pretrained('''junnyu/roformer_chinese_base''' ) __lowerCamelCase = jnp.array([[0, 1, 2, 3, 4, 5]] ) __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ )[0] __lowerCamelCase = 5_00_00 __lowerCamelCase = (1, 6, vocab_size) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = jnp.array( [[[-0.1205, -1.0265, 0.2922], [-1.5134, 0.1974, 0.1519], [-5.0135, -3.9003, -0.8404]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
354
from collections import namedtuple import requests from lxml import html # type: ignore SCREAMING_SNAKE_CASE__ : List[Any] = namedtuple("covid_data", "cases deaths recovered") def __magic_name__ ( __lowerCAmelCase : str = "https://www.worldometers.info/coronavirus/" ) -> covid_data: __lowerCamelCase = '''//div[@class = "maincounter-number"]/span/text()''' return covid_data(*html.fromstring(requests.get(__lowerCAmelCase ).content ).xpath(__lowerCAmelCase ) ) SCREAMING_SNAKE_CASE__ : List[str] = "Total COVID-19 cases in the world: {}\nTotal deaths due to COVID-19 in the world: {}\nTotal COVID-19 patients recovered in the world: {}" print(fmt.format(*covid_stats()))
339
0
def __magic_name__ ( __lowerCAmelCase : list[int] ) -> float: if not nums: # Makes sure that the list is not empty raise ValueError('''List is empty''' ) __lowerCamelCase = sum(__lowerCAmelCase ) / len(__lowerCAmelCase ) # Calculate the average return sum(abs(x - average ) for x in nums ) / len(__lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
355
import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer, HfArgumentParser, MBartTokenizer, MBartTokenizerFast, set_seed, ) from transformers.trainer_utils import EvaluationStrategy, is_main_process from transformers.training_args import ParallelMode from utils import ( SeqaSeqDataCollator, SeqaSeqDataset, assert_all_frozen, build_compute_metrics_fn, check_output_dir, freeze_embeds, freeze_params, lmap, save_json, use_task_specific_params, write_txt_file, ) SCREAMING_SNAKE_CASE__ : int = logging.getLogger(__name__) @dataclass class lowerCAmelCase__ : a__ : str = field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} ) a__ : Optional[str] = field( default=__lowercase , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) a__ : Optional[str] = field( default=__lowercase , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} ) a__ : Optional[str] = field( default=__lowercase , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) a__ : bool = field(default=__lowercase , metadata={"""help""": """Whether tp freeze the encoder."""} ) a__ : bool = field(default=__lowercase , metadata={"""help""": """Whether to freeze the embeddings."""} ) @dataclass class lowerCAmelCase__ : a__ : str = field( metadata={"""help""": """The input data dir. Should contain the .tsv files (or other data files) for the task."""} ) a__ : Optional[str] = field( default="""summarization""" , metadata={"""help""": """Task name, summarization (or summarization_{dataset} for pegasus) or translation"""} , ) a__ : Optional[int] = field( default=1_024 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) a__ : Optional[int] = field( default=128 , metadata={ """help""": ( """The maximum total sequence length for target text after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) a__ : Optional[int] = field( default=142 , metadata={ """help""": ( """The maximum total sequence length for validation target text after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded. """ """This argument is also used to override the ``max_length`` param of ``model.generate``, which is used """ """during ``evaluate`` and ``predict``.""" ) } , ) a__ : Optional[int] = field( default=142 , metadata={ """help""": ( """The maximum total sequence length for test target text after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) a__ : Optional[int] = field(default=-1 , metadata={"""help""": """# training examples. -1 means use all."""} ) a__ : Optional[int] = field(default=-1 , metadata={"""help""": """# validation examples. -1 means use all."""} ) a__ : Optional[int] = field(default=-1 , metadata={"""help""": """# test examples. -1 means use all."""} ) a__ : Optional[str] = field(default=__lowercase , metadata={"""help""": """Source language id for translation."""} ) a__ : Optional[str] = field(default=__lowercase , metadata={"""help""": """Target language id for translation."""} ) a__ : Optional[int] = field(default=__lowercase , metadata={"""help""": """# num_beams to use for evaluation."""} ) a__ : bool = field( default=__lowercase , metadata={"""help""": """If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined."""} , ) def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : str , __lowerCAmelCase : int ) -> Dict: logger.info(f'''***** {split} metrics *****''' ) for key in sorted(metrics.keys() ): logger.info(f''' {key} = {metrics[key]}''' ) save_json(__lowerCAmelCase , os.path.join(__lowerCAmelCase , f'''{split}_results.json''' ) ) def __magic_name__ ( ) -> Optional[Any]: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. __lowerCamelCase = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) ) 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. __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = parser.parse_args_into_dataclasses() check_output_dir(__lowerCAmelCase ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info('''Training/evaluation parameters %s''' , __lowerCAmelCase ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __lowerCamelCase = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) __lowerCamelCase = ('''encoder_layerdrop''', '''decoder_layerdrop''', '''dropout''', '''attention_dropout''') for p in extra_model_params: if getattr(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): assert hasattr(__lowerCAmelCase , __lowerCAmelCase ), f'''({config.__class__.__name__}) doesn\'t have a `{p}` attribute''' setattr(__lowerCAmelCase , __lowerCAmelCase , getattr(__lowerCAmelCase , __lowerCAmelCase ) ) __lowerCamelCase = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) __lowerCamelCase = AutoModelForSeqaSeqLM.from_pretrained( model_args.model_name_or_path , from_tf='''.ckpt''' in model_args.model_name_or_path , config=__lowerCAmelCase , cache_dir=model_args.cache_dir , ) # use task specific params use_task_specific_params(__lowerCAmelCase , data_args.task ) # set num_beams for evaluation if data_args.eval_beams is None: __lowerCamelCase = model.config.num_beams # set decoder_start_token_id for MBart if model.config.decoder_start_token_id is None and isinstance(__lowerCAmelCase , (MBartTokenizer, MBartTokenizerFast) ): assert ( data_args.tgt_lang is not None and data_args.src_lang is not None ), "mBart requires --tgt_lang and --src_lang" if isinstance(__lowerCAmelCase , __lowerCAmelCase ): __lowerCamelCase = tokenizer.lang_code_to_id[data_args.tgt_lang] else: __lowerCamelCase = tokenizer.convert_tokens_to_ids(data_args.tgt_lang ) if model_args.freeze_embeds: freeze_embeds(__lowerCAmelCase ) if model_args.freeze_encoder: freeze_params(model.get_encoder() ) assert_all_frozen(model.get_encoder() ) __lowerCamelCase = SeqaSeqDataset # Get datasets __lowerCamelCase = ( dataset_class( __lowerCAmelCase , type_path='''train''' , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_train else None ) __lowerCamelCase = ( dataset_class( __lowerCAmelCase , type_path='''val''' , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO else None ) __lowerCamelCase = ( dataset_class( __lowerCAmelCase , type_path='''test''' , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_predict else None ) # Initialize our Trainer __lowerCamelCase = ( build_compute_metrics_fn(data_args.task , __lowerCAmelCase ) if training_args.predict_with_generate else None ) __lowerCamelCase = SeqaSeqTrainer( model=__lowerCAmelCase , args=__lowerCAmelCase , data_args=__lowerCAmelCase , train_dataset=__lowerCAmelCase , eval_dataset=__lowerCAmelCase , data_collator=SeqaSeqDataCollator( __lowerCAmelCase , __lowerCAmelCase , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=__lowerCAmelCase , tokenizer=__lowerCAmelCase , ) __lowerCamelCase = {} # Training if training_args.do_train: logger.info('''*** Train ***''' ) __lowerCamelCase = trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) __lowerCamelCase = train_result.metrics __lowerCamelCase = data_args.n_train trainer.save_model() # this also saves the tokenizer if trainer.is_world_process_zero(): handle_metrics('''train''' , __lowerCAmelCase , training_args.output_dir ) all_metrics.update(__lowerCAmelCase ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , '''trainer_state.json''' ) ) # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) tokenizer.save_pretrained(training_args.output_dir ) # Evaluation if training_args.do_eval: logger.info('''*** Evaluate ***''' ) __lowerCamelCase = trainer.evaluate(metric_key_prefix='''val''' ) __lowerCamelCase = data_args.n_val __lowerCamelCase = round(metrics['''val_loss'''] , 4 ) if trainer.is_world_process_zero(): handle_metrics('''val''' , __lowerCAmelCase , training_args.output_dir ) all_metrics.update(__lowerCAmelCase ) if training_args.do_predict: logger.info('''*** Predict ***''' ) __lowerCamelCase = trainer.predict(test_dataset=__lowerCAmelCase , metric_key_prefix='''test''' ) __lowerCamelCase = test_output.metrics __lowerCamelCase = data_args.n_test if trainer.is_world_process_zero(): __lowerCamelCase = round(metrics['''test_loss'''] , 4 ) handle_metrics('''test''' , __lowerCAmelCase , training_args.output_dir ) all_metrics.update(__lowerCAmelCase ) if training_args.predict_with_generate: __lowerCamelCase = tokenizer.batch_decode( test_output.predictions , skip_special_tokens=__lowerCAmelCase , clean_up_tokenization_spaces=__lowerCAmelCase ) __lowerCamelCase = lmap(str.strip , __lowerCAmelCase ) write_txt_file(__lowerCAmelCase , os.path.join(training_args.output_dir , '''test_generations.txt''' ) ) if trainer.is_world_process_zero(): save_json(__lowerCAmelCase , os.path.join(training_args.output_dir , '''all_results.json''' ) ) return all_metrics def __magic_name__ ( __lowerCAmelCase : List[str] ) -> Union[str, Any]: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
339
0
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCAmelCase__ ( __lowercase ): a__ : str = ["""image_processor""", """tokenizer"""] a__ : List[Any] = """AutoImageProcessor""" a__ : Optional[Any] = """AutoTokenizer""" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any ) -> str: super().__init__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.image_processor def __call__( self : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : Any=None , **SCREAMING_SNAKE_CASE__ : int ) -> str: if text is None and images is None: raise ValueError('''You have to specify either text or images. Both cannot be none.''' ) if text is not None: __lowerCamelCase = self.tokenizer(SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if images is not None: __lowerCamelCase = self.image_processor(SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if text is not None and images is not None: __lowerCamelCase = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**SCREAMING_SNAKE_CASE__ ) , tensor_type=SCREAMING_SNAKE_CASE__ ) def __A ( self : Tuple , *SCREAMING_SNAKE_CASE__ : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : int ) -> List[Any]: return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def __A ( self : Tuple , *SCREAMING_SNAKE_CASE__ : Dict , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> List[Any]: return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) @property def __A ( self : str ) -> Any: return ["input_ids", "attention_mask", "pixel_values"]
356
import unittest import numpy as np import torch from diffusers import ScoreSdeVePipeline, ScoreSdeVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class lowerCAmelCase__ ( unittest.TestCase ): @property def __A ( self : List[Any] ) -> Optional[Any]: torch.manual_seed(0 ) __lowerCamelCase = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) return model def __A ( self : Optional[int] ) -> Optional[Any]: __lowerCamelCase = self.dummy_uncond_unet __lowerCamelCase = ScoreSdeVeScheduler() __lowerCamelCase = ScoreSdeVePipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) sde_ve.to(SCREAMING_SNAKE_CASE__ ) sde_ve.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = torch.manual_seed(0 ) __lowerCamelCase = sde_ve(num_inference_steps=2 , output_type='''numpy''' , generator=SCREAMING_SNAKE_CASE__ ).images __lowerCamelCase = torch.manual_seed(0 ) __lowerCamelCase = sde_ve(num_inference_steps=2 , output_type='''numpy''' , generator=SCREAMING_SNAKE_CASE__ , return_dict=SCREAMING_SNAKE_CASE__ )[ 0 ] __lowerCamelCase = image[0, -3:, -3:, -1] __lowerCamelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __lowerCamelCase = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Tuple ) -> str: __lowerCamelCase = '''google/ncsnpp-church-256''' __lowerCamelCase = UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = ScoreSdeVeScheduler.from_pretrained(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = ScoreSdeVePipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) sde_ve.to(SCREAMING_SNAKE_CASE__ ) sde_ve.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = torch.manual_seed(0 ) __lowerCamelCase = sde_ve(num_inference_steps=10 , output_type='''numpy''' , generator=SCREAMING_SNAKE_CASE__ ).images __lowerCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 2_56, 2_56, 3) __lowerCamelCase = np.array([0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
339
0
from math import sqrt def __magic_name__ ( __lowerCAmelCase : int ) -> 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 __magic_name__ ( __lowerCAmelCase : int = 1_0001 ) -> int: """simple docstring""" __lowerCamelCase = 0 __lowerCamelCase = 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() = }')
357
from functools import lru_cache def __magic_name__ ( __lowerCAmelCase : int ) -> set: __lowerCamelCase = 2 __lowerCamelCase = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(__lowerCAmelCase ) if n > 1: factors.add(__lowerCAmelCase ) return factors @lru_cache def __magic_name__ ( __lowerCAmelCase : int ) -> int: return len(unique_prime_factors(__lowerCAmelCase ) ) def __magic_name__ ( __lowerCAmelCase : list ) -> bool: return len(set(__lowerCAmelCase ) ) in (0, 1) def __magic_name__ ( __lowerCAmelCase : int ) -> list: __lowerCamelCase = 2 while True: # Increment each value of a generated range __lowerCamelCase = [base + i for i in range(__lowerCAmelCase )] # Run elements through out unique_prime_factors function # Append our target number to the end. __lowerCamelCase = [upf_len(__lowerCAmelCase ) for x in group] checker.append(__lowerCAmelCase ) # If all numbers in the list are equal, return the group variable. if equality(__lowerCAmelCase ): return group # Increment our base variable by 1 base += 1 def __magic_name__ ( __lowerCAmelCase : int = 4 ) -> int: __lowerCamelCase = run(__lowerCAmelCase ) return results[0] if len(__lowerCAmelCase ) else None if __name__ == "__main__": print(solution())
339
0
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar SCREAMING_SNAKE_CASE__ : Dict = TypeVar("T") def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (position - 1) // 2 def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (2 * position) + 1 def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (2 * position) + 2 class lowerCAmelCase__ ( Generic[T] ): def __init__( self : Optional[Any] ) -> None: __lowerCamelCase = [] __lowerCamelCase = {} __lowerCamelCase = 0 def __len__( self : Tuple ) -> int: return self.elements def __repr__( self : str ) -> str: return str(self.heap ) def __A ( self : Optional[Any] ) -> bool: # Check if the priority queue is empty return self.elements == 0 def __A ( self : str , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # Add an element with given priority to the queue self.heap.append((elem, weight) ) __lowerCamelCase = self.elements self.elements += 1 self._bubble_up(SCREAMING_SNAKE_CASE__ ) def __A ( self : Union[str, Any] ) -> T: # Remove and return the element with lowest weight (highest priority) if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) __lowerCamelCase , __lowerCamelCase = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: __lowerCamelCase , __lowerCamelCase = self.heap[0] self._bubble_down(SCREAMING_SNAKE_CASE__ ) return elem def __A ( self : int , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # Update the weight of the given key __lowerCamelCase = self.position_map[elem] __lowerCamelCase = (elem, weight) if position > 0: __lowerCamelCase = get_parent_position(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase , __lowerCamelCase = self.heap[parent_position] if parent_weight > weight: self._bubble_up(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : T ) -> None: # Place a node at the proper position (upward movement) [to be used internally # only] __lowerCamelCase = self.position_map[elem] if curr_pos == 0: return None __lowerCamelCase = get_parent_position(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase , __lowerCamelCase = self.heap[curr_pos] __lowerCamelCase , __lowerCamelCase = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_up(SCREAMING_SNAKE_CASE__ ) return None def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : T ) -> None: # Place a node at the proper position (downward movement) [to be used # internally only] __lowerCamelCase = self.position_map[elem] __lowerCamelCase , __lowerCamelCase = self.heap[curr_pos] __lowerCamelCase = get_child_left_position(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = get_child_right_position(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements and child_right_position < self.elements: __lowerCamelCase , __lowerCamelCase = self.heap[child_left_position] __lowerCamelCase , __lowerCamelCase = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements: __lowerCamelCase , __lowerCamelCase = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: return None if child_right_position < self.elements: __lowerCamelCase , __lowerCamelCase = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) return None def __A ( self : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> None: # Swap the nodes at the given positions __lowerCamelCase = self.heap[nodea_pos][0] __lowerCamelCase = self.heap[nodea_pos][0] __lowerCamelCase , __lowerCamelCase = ( self.heap[nodea_pos], self.heap[nodea_pos], ) __lowerCamelCase = nodea_pos __lowerCamelCase = nodea_pos class lowerCAmelCase__ ( Generic[T] ): def __init__( self : Tuple ) -> None: __lowerCamelCase = {} __lowerCamelCase = 0 def __repr__( self : int ) -> str: return str(self.connections ) def __len__( self : int ) -> int: return self.nodes def __A ( self : Any , SCREAMING_SNAKE_CASE__ : T ) -> None: # Add a node in the graph if it is not in the graph if node not in self.connections: __lowerCamelCase = {} self.nodes += 1 def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # Add an edge between 2 nodes in the graph self.add_node(SCREAMING_SNAKE_CASE__ ) self.add_node(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = weight __lowerCamelCase = weight def __magic_name__ ( __lowerCAmelCase : GraphUndirectedWeighted[T] , ) -> tuple[dict[T, int], dict[T, T | None]]: __lowerCamelCase = {node: maxsize for node in graph.connections} __lowerCamelCase = {node: None for node in graph.connections} __lowerCamelCase = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(__lowerCAmelCase , __lowerCAmelCase ) if priority_queue.is_empty(): return dist, parent # initialization __lowerCamelCase = priority_queue.extract_min() __lowerCamelCase = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __lowerCamelCase = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(__lowerCAmelCase , dist[neighbour] ) __lowerCamelCase = node # running prim's algorithm while not priority_queue.is_empty(): __lowerCamelCase = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __lowerCamelCase = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(__lowerCAmelCase , dist[neighbour] ) __lowerCamelCase = node return dist, parent
358
import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel class lowerCAmelCase__ : def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any]=99 , SCREAMING_SNAKE_CASE__ : List[Any]=13 , SCREAMING_SNAKE_CASE__ : Tuple=7 , SCREAMING_SNAKE_CASE__ : int=9 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Dict=False , SCREAMING_SNAKE_CASE__ : int=32 , SCREAMING_SNAKE_CASE__ : Tuple=5 , SCREAMING_SNAKE_CASE__ : List[str]=4 , SCREAMING_SNAKE_CASE__ : str=37 , SCREAMING_SNAKE_CASE__ : int=8 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.002 , SCREAMING_SNAKE_CASE__ : str=1 , SCREAMING_SNAKE_CASE__ : Tuple=0 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0 , SCREAMING_SNAKE_CASE__ : int=None , SCREAMING_SNAKE_CASE__ : Dict=None , ) -> Optional[Any]: __lowerCamelCase = parent __lowerCamelCase = batch_size __lowerCamelCase = encoder_seq_length __lowerCamelCase = decoder_seq_length # For common tests __lowerCamelCase = self.decoder_seq_length __lowerCamelCase = is_training __lowerCamelCase = use_attention_mask __lowerCamelCase = use_labels __lowerCamelCase = vocab_size __lowerCamelCase = hidden_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = d_ff __lowerCamelCase = relative_attention_num_buckets __lowerCamelCase = dropout_rate __lowerCamelCase = initializer_factor __lowerCamelCase = eos_token_id __lowerCamelCase = pad_token_id __lowerCamelCase = decoder_start_token_id __lowerCamelCase = None __lowerCamelCase = decoder_layers def __A ( self : Any ) -> Tuple: return TaConfig.from_pretrained('''google/umt5-base''' ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , ) -> Optional[int]: if attention_mask is None: __lowerCamelCase = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: __lowerCamelCase = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: __lowerCamelCase = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=SCREAMING_SNAKE_CASE__ ) if decoder_head_mask is None: __lowerCamelCase = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=SCREAMING_SNAKE_CASE__ ) if cross_attn_head_mask is None: __lowerCamelCase = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=SCREAMING_SNAKE_CASE__ ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } def __A ( self : List[Any] ) -> Tuple: __lowerCamelCase = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) __lowerCamelCase = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for NllbMoe the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input __lowerCamelCase = input_ids.clamp(self.pad_token_id + 1 ) __lowerCamelCase = decoder_input_ids.clamp(self.pad_token_id + 1 ) __lowerCamelCase = self.get_config() __lowerCamelCase = config.num_attention_heads __lowerCamelCase = self.prepare_inputs_dict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return config, input_dict def __A ( self : Tuple ) -> List[str]: __lowerCamelCase , __lowerCamelCase = self.prepare_config_and_inputs() return config, inputs_dict def __A ( self : Optional[Any] ) -> Any: return TaConfig( vocab_size=1_66 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def __A ( self : List[Any] ) -> Any: return TaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> int: __lowerCamelCase = UMTaModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __lowerCamelCase = model( input_ids=SCREAMING_SNAKE_CASE__ , decoder_input_ids=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , decoder_attention_mask=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = model(input_ids=SCREAMING_SNAKE_CASE__ , decoder_input_ids=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = result.last_hidden_state __lowerCamelCase = result.past_key_values __lowerCamelCase = result.encoder_last_hidden_state self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) ) self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) ) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , config.num_layers ) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0] ) , 4 ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple , ) -> Dict: __lowerCamelCase = UMTaModel(config=SCREAMING_SNAKE_CASE__ ).get_decoder().to(SCREAMING_SNAKE_CASE__ ).eval() # first forward pass __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ , use_cache=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ , use_cache=SCREAMING_SNAKE_CASE__ ) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE__ ) == len(SCREAMING_SNAKE_CASE__ ) ) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE__ ) == len(SCREAMING_SNAKE_CASE__ ) + 1 ) __lowerCamelCase , __lowerCamelCase = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids __lowerCamelCase = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and __lowerCamelCase = torch.cat([input_ids, next_tokens] , dim=-1 ) __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ )['''last_hidden_state'''] __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ , past_key_values=SCREAMING_SNAKE_CASE__ )['''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(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple , ) -> Optional[int]: __lowerCamelCase = UMTaModel(config=SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ ).half().eval() __lowerCamelCase = model(**SCREAMING_SNAKE_CASE__ )['''last_hidden_state'''] self.parent.assertFalse(torch.isnan(SCREAMING_SNAKE_CASE__ ).any().item() ) @require_torch class lowerCAmelCase__ ( __lowercase , __lowercase , __lowercase , unittest.TestCase ): a__ : List[Any] = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) a__ : Union[str, Any] = (UMTaForConditionalGeneration,) if is_torch_available() else () a__ : Tuple = ( { """conversational""": UMTaForConditionalGeneration, """feature-extraction""": UMTaModel, """summarization""": UMTaForConditionalGeneration, """text2text-generation""": UMTaForConditionalGeneration, """translation""": UMTaForConditionalGeneration, """question-answering""": UMTaForQuestionAnswering, } if is_torch_available() else {} ) a__ : int = True a__ : int = False a__ : Tuple = False a__ : Optional[int] = True a__ : Optional[int] = True # The small UMT5 model needs higher percentages for CPU/MP tests a__ : Tuple = [0.8, 0.9] def __A ( self : Tuple ) -> Tuple: __lowerCamelCase = UMTaModelTester(self ) @unittest.skip('''Test has a segmentation fault on torch 1.8.0''' ) def __A ( self : List[str] ) -> Union[str, Any]: __lowerCamelCase = self.model_tester.prepare_config_and_inputs() __lowerCamelCase = UMTaModel(config_and_inputs[0] ).to(SCREAMING_SNAKE_CASE__ ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( SCREAMING_SNAKE_CASE__ , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , f'''{tmpdirname}/t5_test.onnx''' , export_params=SCREAMING_SNAKE_CASE__ , opset_version=9 , input_names=['''input_ids''', '''decoder_input_ids'''] , ) @unittest.skipIf(torch_device == '''cpu''' , '''Cant do half precision''' ) def __A ( self : Union[str, Any] ) -> Any: __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*SCREAMING_SNAKE_CASE__ ) def __A ( self : Any ) -> Any: __lowerCamelCase = ['''encoder_attentions''', '''decoder_attentions''', '''cross_attentions'''] __lowerCamelCase = self.model_tester.prepare_config_and_inputs() __lowerCamelCase = config_and_inputs[0] __lowerCamelCase = UMTaForConditionalGeneration(SCREAMING_SNAKE_CASE__ ).eval() model.to(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = { '''head_mask''': torch.zeros(config.num_layers , config.num_heads , device=SCREAMING_SNAKE_CASE__ ), '''decoder_head_mask''': torch.zeros(config.num_decoder_layers , config.num_heads , device=SCREAMING_SNAKE_CASE__ ), '''cross_attn_head_mask''': torch.zeros(config.num_decoder_layers , config.num_heads , device=SCREAMING_SNAKE_CASE__ ), } for attn_name, (name, mask) in zip(SCREAMING_SNAKE_CASE__ , head_masking.items() ): __lowerCamelCase = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": __lowerCamelCase = torch.ones( config.num_decoder_layers , config.num_heads , device=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model.generate( config_and_inputs[1]['''input_ids'''] , num_beams=1 , max_length=3 , output_attentions=SCREAMING_SNAKE_CASE__ , return_dict_in_generate=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) # We check the state of decoder_attentions and cross_attentions just from the last step __lowerCamelCase = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 ) @unittest.skip('''Does not work on the tiny model as we keep hitting edge cases.''' ) def __A ( self : Tuple ) -> Optional[Any]: pass @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): @slow @unittest.skip( '''Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged''' ) def __A ( self : int ) -> Optional[Any]: __lowerCamelCase = UMTaForConditionalGeneration.from_pretrained('''google/umt5-small''' , return_dict=SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = AutoTokenizer.from_pretrained('''google/umt5-small''' , use_fast=SCREAMING_SNAKE_CASE__ , legacy=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = [ '''Bonjour monsieur <extra_id_0> bien <extra_id_1>.''', '''No se como puedo <extra_id_0>.''', '''This is the reason why we <extra_id_0> them.''', '''The <extra_id_0> walks in <extra_id_1>, seats''', '''A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.''', ] __lowerCamelCase = tokenizer(SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , padding=SCREAMING_SNAKE_CASE__ ).input_ids # fmt: off __lowerCamelCase = torch.tensor( [ [ 3_85_30, 21_07_03, 25_62_99, 14_10, 25_62_98, 2_74, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 8_26, 3_21, 6_71, 2_59_22, 25_62_99, 2_74, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 14_60, 3_39, 3_12, 1_90_14, 1_06_20, 7_58, 25_62_99, 23_55,2_74, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 5_17, 25_62_99, 1_48_69, 2_81, 3_01, 25_62_98, 2_75, 11_99_83,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 3_20, 25_62_99, 1_48_69, 2_81, 22_34, 2_89, 22_75, 3_33,6_13_91, 2_89, 25_62_98, 5_43, 25_62_97, 16_87_14, 3_29, 25_62_96,2_74, 1], ] ) # fmt: on torch.testing.assert_allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model.generate(input_ids.to(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = [ '''<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>''', '''<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', ] __lowerCamelCase = tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
339
0
from __future__ import annotations from collections import Counter from random import random class lowerCAmelCase__ : def __init__( self : Dict ) -> Dict: __lowerCamelCase = {} def __A ( self : List[str] , SCREAMING_SNAKE_CASE__ : str ) -> None: __lowerCamelCase = {} def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : float ) -> None: if nodea not in self.connections: self.add_node(SCREAMING_SNAKE_CASE__ ) if nodea not in self.connections: self.add_node(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = probability def __A ( self : Optional[int] ) -> list[str]: return list(self.connections ) def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : str ) -> str: __lowerCamelCase = 0 __lowerCamelCase = random() for dest in self.connections[node]: current_probability += self.connections[node][dest] if current_probability > random_value: return dest return "" def __magic_name__ ( __lowerCAmelCase : str , __lowerCAmelCase : list[tuple[str, str, float]] , __lowerCAmelCase : int ) -> dict[str, int]: __lowerCamelCase = MarkovChainGraphUndirectedUnweighted() for nodea, nodea, probability in transitions: graph.add_transition_probability(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase = Counter(graph.get_nodes() ) __lowerCamelCase = start for _ in range(__lowerCAmelCase ): __lowerCamelCase = graph.transition(__lowerCAmelCase ) visited[node] += 1 return visited if __name__ == "__main__": import doctest doctest.testmod()
359
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : Union[str, Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Tuple = { "s-JoL/Open-Llama-V1": "https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/config.json", } class lowerCAmelCase__ ( __lowercase ): a__ : Union[str, Any] = """open-llama""" def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Any=10_00_00 , SCREAMING_SNAKE_CASE__ : Any=40_96 , SCREAMING_SNAKE_CASE__ : Any=1_10_08 , SCREAMING_SNAKE_CASE__ : Tuple=32 , SCREAMING_SNAKE_CASE__ : str=32 , SCREAMING_SNAKE_CASE__ : Any="silu" , SCREAMING_SNAKE_CASE__ : Union[str, Any]=20_48 , SCREAMING_SNAKE_CASE__ : List[str]=0.02 , SCREAMING_SNAKE_CASE__ : List[Any]=1e-6 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Dict=0 , SCREAMING_SNAKE_CASE__ : Tuple=1 , SCREAMING_SNAKE_CASE__ : str=2 , SCREAMING_SNAKE_CASE__ : List[Any]=False , SCREAMING_SNAKE_CASE__ : Any=True , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Any=0.1 , SCREAMING_SNAKE_CASE__ : Any=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : List[str]=None , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> Dict: __lowerCamelCase = vocab_size __lowerCamelCase = max_position_embeddings __lowerCamelCase = hidden_size __lowerCamelCase = intermediate_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = hidden_act __lowerCamelCase = initializer_range __lowerCamelCase = rms_norm_eps __lowerCamelCase = use_cache __lowerCamelCase = kwargs.pop( '''use_memorry_efficient_attention''' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = hidden_dropout_prob __lowerCamelCase = attention_dropout_prob __lowerCamelCase = use_stable_embedding __lowerCamelCase = shared_input_output_embedding __lowerCamelCase = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , tie_word_embeddings=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) def __A ( self : Dict ) -> Optional[int]: if self.rope_scaling is None: return if not isinstance(self.rope_scaling , SCREAMING_SNAKE_CASE__ ) or len(self.rope_scaling ) != 2: raise ValueError( '''`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ''' f'''got {self.rope_scaling}''' ) __lowerCamelCase = self.rope_scaling.get('''type''' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.rope_scaling.get('''factor''' , SCREAMING_SNAKE_CASE__ ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' ) if rope_scaling_factor is None or not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or rope_scaling_factor <= 1.0: raise ValueError(f'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
339
0
from graphs.minimum_spanning_tree_kruskal import kruskal def __magic_name__ ( ) -> Union[str, Any]: __lowerCamelCase = 9 __lowerCamelCase = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 14], [3, 4, 9], [5, 4, 10], [1, 7, 11], ] __lowerCamelCase = kruskal(__lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase = [ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] assert sorted(__lowerCAmelCase ) == sorted(__lowerCAmelCase )
360
from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar SCREAMING_SNAKE_CASE__ : Any = TypeVar("KEY") SCREAMING_SNAKE_CASE__ : Dict = TypeVar("VAL") @dataclass(frozen=__lowercase , slots=__lowercase ) class lowerCAmelCase__ ( Generic[KEY, VAL] ): a__ : KEY a__ : VAL class lowerCAmelCase__ ( _Item ): def __init__( self : str ) -> None: super().__init__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __bool__( self : Tuple ) -> bool: return False SCREAMING_SNAKE_CASE__ : List[Any] = _DeletedItem() class lowerCAmelCase__ ( MutableMapping[KEY, VAL] ): def __init__( self : int , SCREAMING_SNAKE_CASE__ : int = 8 , SCREAMING_SNAKE_CASE__ : float = 0.75 ) -> None: __lowerCamelCase = initial_block_size __lowerCamelCase = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 __lowerCamelCase = capacity_factor __lowerCamelCase = 0 def __A ( self : Any , SCREAMING_SNAKE_CASE__ : KEY ) -> int: return hash(SCREAMING_SNAKE_CASE__ ) % len(self._buckets ) def __A ( self : Any , SCREAMING_SNAKE_CASE__ : int ) -> int: return (ind + 1) % len(self._buckets ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : KEY , SCREAMING_SNAKE_CASE__ : VAL ) -> bool: __lowerCamelCase = self._buckets[ind] if not stored: __lowerCamelCase = _Item(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self._len += 1 return True elif stored.key == key: __lowerCamelCase = _Item(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return True else: return False def __A ( self : Any ) -> bool: __lowerCamelCase = len(self._buckets ) * self._capacity_factor return len(self ) >= int(SCREAMING_SNAKE_CASE__ ) def __A ( self : List[Any] ) -> bool: if len(self._buckets ) <= self._initial_block_size: return False __lowerCamelCase = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def __A ( self : int , SCREAMING_SNAKE_CASE__ : int ) -> None: __lowerCamelCase = self._buckets __lowerCamelCase = [None] * new_size __lowerCamelCase = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def __A ( self : str ) -> None: self._resize(len(self._buckets ) * 2 ) def __A ( self : Dict ) -> None: self._resize(len(self._buckets ) // 2 ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : KEY ) -> Iterator[int]: __lowerCamelCase = self._get_bucket_index(SCREAMING_SNAKE_CASE__ ) for _ in range(len(self._buckets ) ): yield ind __lowerCamelCase = self._get_next_ind(SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : KEY , SCREAMING_SNAKE_CASE__ : VAL ) -> None: for ind in self._iterate_buckets(SCREAMING_SNAKE_CASE__ ): if self._try_set(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): break def __setitem__( self : Tuple , SCREAMING_SNAKE_CASE__ : KEY , SCREAMING_SNAKE_CASE__ : VAL ) -> None: if self._is_full(): self._size_up() self._add_item(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __delitem__( self : List[Any] , SCREAMING_SNAKE_CASE__ : KEY ) -> None: for ind in self._iterate_buckets(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = self._buckets[ind] if item is None: raise KeyError(SCREAMING_SNAKE_CASE__ ) if item is _deleted: continue if item.key == key: __lowerCamelCase = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : KEY ) -> VAL: for ind in self._iterate_buckets(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(SCREAMING_SNAKE_CASE__ ) def __len__( self : int ) -> int: return self._len def __iter__( self : Tuple ) -> Iterator[KEY]: yield from (item.key for item in self._buckets if item) def __repr__( self : Optional[Any] ) -> str: __lowerCamelCase = ''' ,'''.join( f'''{item.key}: {item.val}''' for item in self._buckets if item ) return f'''HashMap({val_string})'''
339
0
from datetime import datetime as dt import os from github import Github SCREAMING_SNAKE_CASE__ : Any = [ "good first issue", "good second issue", "good difficult issue", "feature request", "new model", "wip", ] def __magic_name__ ( ) -> Any: __lowerCamelCase = Github(os.environ['''GITHUB_TOKEN'''] ) __lowerCamelCase = g.get_repo('''huggingface/transformers''' ) __lowerCamelCase = repo.get_issues(state='''open''' ) for issue in open_issues: __lowerCamelCase = sorted([comment for comment in issue.get_comments()] , key=lambda __lowerCAmelCase : i.created_at , reverse=__lowerCAmelCase ) __lowerCamelCase = comments[0] if len(__lowerCAmelCase ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # print(f"Would close issue {issue.number} since it has been 7 days of inactivity since bot mention.") issue.edit(state='''closed''' ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # print(f"Would add stale comment to {issue.number}") issue.create_comment( '''This issue has been automatically marked as stale because it has not had ''' '''recent activity. If you think this still needs to be addressed ''' '''please comment on this thread.\n\nPlease note that issues that do not follow the ''' '''[contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) ''' '''are likely to be ignored.''' ) if __name__ == "__main__": main()
361
from datetime import datetime as dt import os from github import Github SCREAMING_SNAKE_CASE__ : Any = [ "good first issue", "good second issue", "good difficult issue", "feature request", "new model", "wip", ] def __magic_name__ ( ) -> Any: __lowerCamelCase = Github(os.environ['''GITHUB_TOKEN'''] ) __lowerCamelCase = g.get_repo('''huggingface/transformers''' ) __lowerCamelCase = repo.get_issues(state='''open''' ) for issue in open_issues: __lowerCamelCase = sorted([comment for comment in issue.get_comments()] , key=lambda __lowerCAmelCase : i.created_at , reverse=__lowerCAmelCase ) __lowerCamelCase = comments[0] if len(__lowerCAmelCase ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # print(f"Would close issue {issue.number} since it has been 7 days of inactivity since bot mention.") issue.edit(state='''closed''' ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # print(f"Would add stale comment to {issue.number}") issue.create_comment( '''This issue has been automatically marked as stale because it has not had ''' '''recent activity. If you think this still needs to be addressed ''' '''please comment on this thread.\n\nPlease note that issues that do not follow the ''' '''[contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) ''' '''are likely to be ignored.''' ) if __name__ == "__main__": main()
339
0
from typing import Callable, List, Optional, Union import PIL import torch from transformers import ( CLIPImageProcessor, CLIPSegForImageSegmentation, CLIPSegProcessor, CLIPTextModel, CLIPTokenizer, ) from diffusers import DiffusionPipeline from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import deprecate, is_accelerate_available, logging SCREAMING_SNAKE_CASE : List[str] = logging.get_logger(__name__) # pylint: disable=invalid-name class lowerCAmelCase__ ( __lowercase ): def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : CLIPSegForImageSegmentation , SCREAMING_SNAKE_CASE__ : CLIPSegProcessor , SCREAMING_SNAKE_CASE__ : AutoencoderKL , SCREAMING_SNAKE_CASE__ : CLIPTextModel , SCREAMING_SNAKE_CASE__ : CLIPTokenizer , SCREAMING_SNAKE_CASE__ : UNetaDConditionModel , SCREAMING_SNAKE_CASE__ : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , SCREAMING_SNAKE_CASE__ : StableDiffusionSafetyChecker , SCREAMING_SNAKE_CASE__ : CLIPImageProcessor , ) -> Dict: super().__init__() if hasattr(scheduler.config , '''steps_offset''' ) and scheduler.config.steps_offset != 1: __lowerCamelCase = ( f'''The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`''' f''' should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure ''' '''to update the config accordingly as leaving `steps_offset` might led to incorrect results''' ''' in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,''' ''' it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`''' ''' file''' ) deprecate('''steps_offset!=1''' , '''1.0.0''' , SCREAMING_SNAKE_CASE__ , standard_warn=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = dict(scheduler.config ) __lowerCamelCase = 1 __lowerCamelCase = FrozenDict(SCREAMING_SNAKE_CASE__ ) if hasattr(scheduler.config , '''skip_prk_steps''' ) and scheduler.config.skip_prk_steps is False: __lowerCamelCase = ( f'''The configuration file of this scheduler: {scheduler} has not set the configuration''' ''' `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make''' ''' sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to''' ''' incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face''' ''' Hub, it would be very nice if you could open a Pull request for the''' ''' `scheduler/scheduler_config.json` file''' ) deprecate('''skip_prk_steps not set''' , '''1.0.0''' , SCREAMING_SNAKE_CASE__ , standard_warn=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = dict(scheduler.config ) __lowerCamelCase = True __lowerCamelCase = FrozenDict(SCREAMING_SNAKE_CASE__ ) if safety_checker is None: logger.warning( f'''You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure''' ''' that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered''' ''' results in services or applications open to the public. Both the diffusers team and Hugging Face''' ''' strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling''' ''' it only for use-cases that involve analyzing network behavior or auditing its results. For more''' ''' information, please have a look at https://github.com/huggingface/diffusers/pull/254 .''' ) self.register_modules( segmentation_model=SCREAMING_SNAKE_CASE__ , segmentation_processor=SCREAMING_SNAKE_CASE__ , vae=SCREAMING_SNAKE_CASE__ , text_encoder=SCREAMING_SNAKE_CASE__ , tokenizer=SCREAMING_SNAKE_CASE__ , unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ , safety_checker=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ , ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Union[str, int]] = "auto" ) -> str: if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory __lowerCamelCase = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(SCREAMING_SNAKE_CASE__ ) def __A ( self : Any ) -> Dict: self.enable_attention_slicing(SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[Any] ) -> Union[str, Any]: if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) __lowerCamelCase = torch.device('''cuda''' ) for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]: if cpu_offloaded_model is not None: cpu_offload(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __A ( self : Optional[Any] ) -> List[str]: if self.device != torch.device('''meta''' ) or not hasattr(self.unet , '''_hf_hook''' ): return self.device for module in self.unet.modules(): if ( hasattr(SCREAMING_SNAKE_CASE__ , '''_hf_hook''' ) and hasattr(module._hf_hook , '''execution_device''' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() def __call__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, List[str]] , SCREAMING_SNAKE_CASE__ : Union[torch.FloatTensor, PIL.Image.Image] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int = 5_12 , SCREAMING_SNAKE_CASE__ : int = 5_12 , SCREAMING_SNAKE_CASE__ : int = 50 , SCREAMING_SNAKE_CASE__ : float = 7.5 , SCREAMING_SNAKE_CASE__ : Optional[Union[str, List[str]]] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = 1 , SCREAMING_SNAKE_CASE__ : float = 0.0 , SCREAMING_SNAKE_CASE__ : Optional[torch.Generator] = None , SCREAMING_SNAKE_CASE__ : Optional[torch.FloatTensor] = None , SCREAMING_SNAKE_CASE__ : Optional[str] = "pil" , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , SCREAMING_SNAKE_CASE__ : int = 1 , **SCREAMING_SNAKE_CASE__ : Dict , ) -> Union[str, Any]: __lowerCamelCase = self.segmentation_processor( text=[text] , images=[image] , padding='''max_length''' , return_tensors='''pt''' ).to(self.device ) __lowerCamelCase = self.segmentation_model(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy() __lowerCamelCase = self.numpy_to_pil(SCREAMING_SNAKE_CASE__ )[0].resize(image.size ) # Run inpainting pipeline with the generated mask __lowerCamelCase = StableDiffusionInpaintPipeline( vae=self.vae , text_encoder=self.text_encoder , tokenizer=self.tokenizer , unet=self.unet , scheduler=self.scheduler , safety_checker=self.safety_checker , feature_extractor=self.feature_extractor , ) return inpainting_pipeline( prompt=SCREAMING_SNAKE_CASE__ , image=SCREAMING_SNAKE_CASE__ , mask_image=SCREAMING_SNAKE_CASE__ , height=SCREAMING_SNAKE_CASE__ , width=SCREAMING_SNAKE_CASE__ , num_inference_steps=SCREAMING_SNAKE_CASE__ , guidance_scale=SCREAMING_SNAKE_CASE__ , negative_prompt=SCREAMING_SNAKE_CASE__ , num_images_per_prompt=SCREAMING_SNAKE_CASE__ , eta=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , latents=SCREAMING_SNAKE_CASE__ , output_type=SCREAMING_SNAKE_CASE__ , return_dict=SCREAMING_SNAKE_CASE__ , callback=SCREAMING_SNAKE_CASE__ , callback_steps=SCREAMING_SNAKE_CASE__ , )
362
def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int ) -> str: if a < 0 or b < 0: raise ValueError('''the value of both inputs must be positive''' ) __lowerCamelCase = str(bin(__lowerCAmelCase ) )[2:] # remove the leading "0b" __lowerCamelCase = str(bin(__lowerCAmelCase ) )[2:] # remove the leading "0b" __lowerCamelCase = max(len(__lowerCAmelCase ) , len(__lowerCAmelCase ) ) return "0b" + "".join( str(int(char_a == '''1''' and char_b == '''1''' ) ) for char_a, char_b in zip(a_binary.zfill(__lowerCAmelCase ) , b_binary.zfill(__lowerCAmelCase ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
339
0
import unittest import numpy as np import timeout_decorator # noqa from transformers import BlenderbotSmallConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html SCREAMING_SNAKE_CASE__ : Any = "platform" import jax import jax.numpy as jnp from transformers.models.blenderbot_small.modeling_flax_blenderbot_small import ( FlaxBlenderbotSmallForConditionalGeneration, FlaxBlenderbotSmallModel, shift_tokens_right, ) def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int , __lowerCAmelCase : Dict=None , __lowerCAmelCase : str=None , __lowerCAmelCase : int=None , __lowerCAmelCase : Tuple=None , __lowerCAmelCase : Union[str, Any]=None , __lowerCAmelCase : Optional[int]=None , ) -> Optional[Any]: if attention_mask is None: __lowerCamelCase = np.where(input_ids != config.pad_token_id , 1 , 0 ) if decoder_attention_mask is None: __lowerCamelCase = np.where(decoder_input_ids != config.pad_token_id , 1 , 0 ) if head_mask is None: __lowerCamelCase = np.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: __lowerCamelCase = np.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: __lowerCamelCase = np.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": attention_mask, } class lowerCAmelCase__ : def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str]=13 , SCREAMING_SNAKE_CASE__ : Dict=7 , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Tuple=False , SCREAMING_SNAKE_CASE__ : List[str]=99 , SCREAMING_SNAKE_CASE__ : Optional[Any]=16 , SCREAMING_SNAKE_CASE__ : Tuple=2 , SCREAMING_SNAKE_CASE__ : Any=4 , SCREAMING_SNAKE_CASE__ : Any=4 , SCREAMING_SNAKE_CASE__ : Dict="gelu" , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=0.1 , SCREAMING_SNAKE_CASE__ : Dict=32 , SCREAMING_SNAKE_CASE__ : Any=2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=1 , SCREAMING_SNAKE_CASE__ : str=0 , SCREAMING_SNAKE_CASE__ : int=0.02 , ) -> List[str]: __lowerCamelCase = parent __lowerCamelCase = batch_size __lowerCamelCase = seq_length __lowerCamelCase = is_training __lowerCamelCase = use_labels __lowerCamelCase = vocab_size __lowerCamelCase = hidden_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = intermediate_size __lowerCamelCase = hidden_act __lowerCamelCase = hidden_dropout_prob __lowerCamelCase = attention_probs_dropout_prob __lowerCamelCase = max_position_embeddings __lowerCamelCase = eos_token_id __lowerCamelCase = pad_token_id __lowerCamelCase = bos_token_id __lowerCamelCase = initializer_range def __A ( self : Dict ) -> str: __lowerCamelCase = np.clip(ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) , 3 , self.vocab_size ) __lowerCamelCase = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1) , dtype=np.intaa )) , -1 ) __lowerCamelCase = shift_tokens_right(SCREAMING_SNAKE_CASE__ , 1 , 2 ) __lowerCamelCase = BlenderbotSmallConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , initializer_range=self.initializer_range , use_cache=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = prepare_blenderbot_inputs_dict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return config, inputs_dict def __A ( self : Any ) -> Dict: __lowerCamelCase , __lowerCamelCase = self.prepare_config_and_inputs() return config, inputs_dict def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Tuple ) -> List[Any]: __lowerCamelCase = 20 __lowerCamelCase = model_class_name(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model.encode(inputs_dict['''input_ids'''] ) __lowerCamelCase , __lowerCamelCase = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) __lowerCamelCase = model.init_cache(decoder_input_ids.shape[0] , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype='''i4''' ) __lowerCamelCase = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __lowerCamelCase = model.decode( decoder_input_ids[:, :-1] , SCREAMING_SNAKE_CASE__ , decoder_attention_mask=SCREAMING_SNAKE_CASE__ , past_key_values=SCREAMING_SNAKE_CASE__ , decoder_position_ids=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) __lowerCamelCase = model.decode( decoder_input_ids[:, -1:] , SCREAMING_SNAKE_CASE__ , decoder_attention_mask=SCREAMING_SNAKE_CASE__ , past_key_values=outputs_cache.past_key_values , decoder_position_ids=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = model.decode(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=f'''Max diff is {diff}''' ) def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: __lowerCamelCase = 20 __lowerCamelCase = model_class_name(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model.encode(inputs_dict['''input_ids'''] ) __lowerCamelCase , __lowerCamelCase = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) __lowerCamelCase = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) __lowerCamelCase = model.init_cache(decoder_input_ids.shape[0] , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __lowerCamelCase = model.decode( decoder_input_ids[:, :-1] , SCREAMING_SNAKE_CASE__ , decoder_attention_mask=SCREAMING_SNAKE_CASE__ , past_key_values=SCREAMING_SNAKE_CASE__ , decoder_position_ids=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) __lowerCamelCase = model.decode( decoder_input_ids[:, -1:] , SCREAMING_SNAKE_CASE__ , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=SCREAMING_SNAKE_CASE__ , decoder_position_ids=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = model.decode(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , decoder_attention_mask=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=f'''Max diff is {diff}''' ) @require_flax class lowerCAmelCase__ ( unittest.TestCase ): a__ : Optional[Any] = 99 def __A ( self : str ) -> List[Any]: __lowerCamelCase = np.array( [ [71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 82, 2], [5, 97, 17, 39, 94, 40, 2], [76, 83, 94, 25, 70, 78, 2], [87, 59, 41, 35, 48, 66, 2], [55, 13, 16, 58, 5, 2, 1], # note padding [64, 27, 31, 51, 12, 75, 2], [52, 64, 86, 17, 83, 39, 2], [48, 61, 9, 24, 71, 82, 2], [26, 1, 60, 48, 22, 13, 2], [21, 5, 62, 28, 14, 76, 2], [45, 98, 37, 86, 59, 48, 2], [70, 70, 50, 9, 28, 0, 2], ] , dtype=np.intaa , ) __lowerCamelCase = input_ids.shape[0] __lowerCamelCase = BlenderbotSmallConfig( vocab_size=self.vocab_size , d_model=24 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=32 , decoder_ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size def __A ( self : str ) -> int: __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = self._get_config_and_data() __lowerCamelCase = FlaxBlenderbotSmallForConditionalGeneration(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = lm_model(input_ids=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = (batch_size, input_ids.shape[1], config.vocab_size) self.assertEqual(outputs['''logits'''].shape , SCREAMING_SNAKE_CASE__ ) def __A ( self : int ) -> str: __lowerCamelCase = BlenderbotSmallConfig( vocab_size=self.vocab_size , d_model=14 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=8 , decoder_ffn_dim=8 , max_position_embeddings=48 , ) __lowerCamelCase = FlaxBlenderbotSmallForConditionalGeneration(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]] , dtype=np.intaa ) __lowerCamelCase = np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]] , dtype=np.intaa ) __lowerCamelCase = lm_model(input_ids=SCREAMING_SNAKE_CASE__ , decoder_input_ids=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = (*summary.shape, config.vocab_size) self.assertEqual(outputs['''logits'''].shape , SCREAMING_SNAKE_CASE__ ) def __A ( self : List[str] ) -> List[Any]: __lowerCamelCase = np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]] , dtype=np.intaa ) __lowerCamelCase = shift_tokens_right(SCREAMING_SNAKE_CASE__ , 1 , 2 ) __lowerCamelCase = np.equal(SCREAMING_SNAKE_CASE__ , 1 ).astype(np.floataa ).sum() __lowerCamelCase = np.equal(SCREAMING_SNAKE_CASE__ , 1 ).astype(np.floataa ).sum() self.assertEqual(shifted.shape , input_ids.shape ) self.assertEqual(SCREAMING_SNAKE_CASE__ , n_pad_before - 1 ) self.assertTrue(np.equal(shifted[:, 0] , 2 ).all() ) @require_flax class lowerCAmelCase__ ( __lowercase , unittest.TestCase , __lowercase ): a__ : Tuple = True a__ : List[Any] = ( ( FlaxBlenderbotSmallModel, FlaxBlenderbotSmallForConditionalGeneration, ) if is_flax_available() else () ) a__ : Tuple = (FlaxBlenderbotSmallForConditionalGeneration,) if is_flax_available() else () def __A ( self : List[Any] ) -> Optional[int]: __lowerCamelCase = FlaxBlenderbotSmallModelTester(self ) def __A ( self : Tuple ) -> List[Any]: __lowerCamelCase , __lowerCamelCase = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : List[Any] ) -> int: __lowerCamelCase , __lowerCamelCase = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : List[str] ) -> List[str]: __lowerCamelCase , __lowerCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __lowerCamelCase = self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model_class(SCREAMING_SNAKE_CASE__ ) @jax.jit def encode_jitted(SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , **SCREAMING_SNAKE_CASE__ : int ): return model.encode(input_ids=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) with self.subTest('''JIT Enabled''' ): __lowerCamelCase = encode_jitted(**SCREAMING_SNAKE_CASE__ ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): __lowerCamelCase = encode_jitted(**SCREAMING_SNAKE_CASE__ ).to_tuple() self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) ) for jitted_output, output in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(jitted_output.shape , output.shape ) def __A ( self : Tuple ) -> Tuple: __lowerCamelCase , __lowerCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __lowerCamelCase = model_class(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model.encode(inputs_dict['''input_ids'''] , inputs_dict['''attention_mask'''] ) __lowerCamelCase = { '''decoder_input_ids''': inputs_dict['''decoder_input_ids'''], '''decoder_attention_mask''': inputs_dict['''decoder_attention_mask'''], '''encoder_outputs''': encoder_outputs, } @jax.jit def decode_jitted(SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str ): return model.decode( decoder_input_ids=SCREAMING_SNAKE_CASE__ , decoder_attention_mask=SCREAMING_SNAKE_CASE__ , encoder_outputs=SCREAMING_SNAKE_CASE__ , ) with self.subTest('''JIT Enabled''' ): __lowerCamelCase = decode_jitted(**SCREAMING_SNAKE_CASE__ ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): __lowerCamelCase = decode_jitted(**SCREAMING_SNAKE_CASE__ ).to_tuple() self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) ) for jitted_output, output in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(jitted_output.shape , output.shape ) @slow def __A ( self : Dict ) -> int: for model_class_name in self.all_model_classes: __lowerCamelCase = model_class_name.from_pretrained('''facebook/blenderbot_small-90M''' ) # FlaxBlenderbotForSequenceClassification expects eos token in input_ids __lowerCamelCase = np.ones((1, 1) ) * model.config.eos_token_id __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ )
363
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPSegProcessor, ViTImageProcessor @require_vision class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : List[str] ) -> Dict: __lowerCamelCase = tempfile.mkdtemp() # fmt: off __lowerCamelCase = ['''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''lo''', '''l</w>''', '''w</w>''', '''r</w>''', '''t</w>''', '''low</w>''', '''er</w>''', '''lowest</w>''', '''newer</w>''', '''wider''', '''<unk>''', '''<|startoftext|>''', '''<|endoftext|>'''] # fmt: on __lowerCamelCase = dict(zip(SCREAMING_SNAKE_CASE__ , range(len(SCREAMING_SNAKE_CASE__ ) ) ) ) __lowerCamelCase = ['''#version: 0.2''', '''l o''', '''lo w</w>''', '''e r</w>''', ''''''] __lowerCamelCase = {'''unk_token''': '''<unk>'''} __lowerCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) __lowerCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE__ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = { '''do_resize''': True, '''size''': 20, '''do_center_crop''': True, '''crop_size''': 18, '''do_normalize''': True, '''image_mean''': [0.48145466, 0.4578275, 0.40821073], '''image_std''': [0.26862954, 0.26130258, 0.27577711], } __lowerCamelCase = os.path.join(self.tmpdirname , SCREAMING_SNAKE_CASE__ ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : int , **SCREAMING_SNAKE_CASE__ : int ) -> Any: return CLIPTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def __A ( self : Dict , **SCREAMING_SNAKE_CASE__ : Dict ) -> Union[str, Any]: return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[int] , **SCREAMING_SNAKE_CASE__ : Any ) -> List[Any]: return ViTImageProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def __A ( self : Dict ) -> Dict: shutil.rmtree(self.tmpdirname ) def __A ( self : str ) -> Any: __lowerCamelCase = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] __lowerCamelCase = [Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def __A ( self : List[Any] ) -> List[str]: __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = self.get_rust_tokenizer() __lowerCamelCase = self.get_image_processor() __lowerCamelCase = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) processor_slow.save_pretrained(self.tmpdirname ) __lowerCamelCase = CLIPSegProcessor.from_pretrained(self.tmpdirname , use_fast=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) processor_fast.save_pretrained(self.tmpdirname ) __lowerCamelCase = 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 , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor_fast.tokenizer , SCREAMING_SNAKE_CASE__ ) 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 , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor_fast.image_processor , SCREAMING_SNAKE_CASE__ ) def __A ( self : Union[str, Any] ) -> int: __lowerCamelCase = CLIPSegProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __lowerCamelCase = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __lowerCamelCase = self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) __lowerCamelCase = CLIPSegProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , SCREAMING_SNAKE_CASE__ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[Any] ) -> Union[str, Any]: __lowerCamelCase = self.get_image_processor() __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.prepare_image_inputs() __lowerCamelCase = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='''np''' ) __lowerCamelCase = processor(images=SCREAMING_SNAKE_CASE__ , 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 __A ( self : List[Any] ) -> Optional[int]: __lowerCamelCase = self.get_image_processor() __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = '''lower newer''' __lowerCamelCase = processor(text=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = tokenizer(SCREAMING_SNAKE_CASE__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __A ( self : List[Any] ) -> Any: __lowerCamelCase = self.get_image_processor() __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = '''lower newer''' __lowerCamelCase = self.prepare_image_inputs() __lowerCamelCase = processor(text=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE__ ): processor() def __A ( self : Optional[Any] ) -> List[str]: __lowerCamelCase = self.get_image_processor() __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.prepare_image_inputs() __lowerCamelCase = self.prepare_image_inputs() __lowerCamelCase = processor(images=SCREAMING_SNAKE_CASE__ , visual_prompt=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , ['''pixel_values''', '''conditional_pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE__ ): processor() def __A ( self : List[Any] ) -> Any: __lowerCamelCase = self.get_image_processor() __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __lowerCamelCase = processor.batch_decode(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
339
0
import gc import unittest import numpy as np import torch from diffusers import StableDiffusionKDiffusionPipeline from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : str ) -> Optional[Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self : int ) -> Optional[Any]: __lowerCamelCase = StableDiffusionKDiffusionPipeline.from_pretrained('''CompVis/stable-diffusion-v1-4''' ) __lowerCamelCase = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) sd_pipe.set_scheduler('''sample_euler''' ) __lowerCamelCase = '''A painting of a squirrel eating a burger''' __lowerCamelCase = torch.manual_seed(0 ) __lowerCamelCase = sd_pipe([prompt] , generator=SCREAMING_SNAKE_CASE__ , guidance_scale=9.0 , num_inference_steps=20 , output_type='''np''' ) __lowerCamelCase = output.images __lowerCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) __lowerCamelCase = np.array([0.0447, 0.0492, 0.0468, 0.0408, 0.0383, 0.0408, 0.0354, 0.0380, 0.0339] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __A ( self : int ) -> Tuple: __lowerCamelCase = StableDiffusionKDiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base''' ) __lowerCamelCase = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) sd_pipe.set_scheduler('''sample_euler''' ) __lowerCamelCase = '''A painting of a squirrel eating a burger''' __lowerCamelCase = torch.manual_seed(0 ) __lowerCamelCase = sd_pipe([prompt] , generator=SCREAMING_SNAKE_CASE__ , guidance_scale=9.0 , num_inference_steps=20 , output_type='''np''' ) __lowerCamelCase = output.images __lowerCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) __lowerCamelCase = np.array([0.1237, 0.1320, 0.1438, 0.1359, 0.1390, 0.1132, 0.1277, 0.1175, 0.1112] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-1 def __A ( self : str ) -> str: __lowerCamelCase = StableDiffusionKDiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base''' ) __lowerCamelCase = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) sd_pipe.set_scheduler('''sample_dpmpp_2m''' ) __lowerCamelCase = '''A painting of a squirrel eating a burger''' __lowerCamelCase = torch.manual_seed(0 ) __lowerCamelCase = sd_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE__ , guidance_scale=7.5 , num_inference_steps=15 , output_type='''np''' , use_karras_sigmas=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = output.images __lowerCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) __lowerCamelCase = np.array( [0.11381689, 0.12112921, 0.1389457, 0.12549606, 0.1244964, 0.10831517, 0.11562866, 0.10867816, 0.10499048] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
364
from __future__ import annotations def __magic_name__ ( __lowerCAmelCase : list , __lowerCAmelCase : int | None = None , __lowerCAmelCase : int | None = None ) -> None: if start is None: __lowerCamelCase = 0 if end is None: __lowerCamelCase = len(__lowerCAmelCase ) - 1 if start >= end: return __lowerCamelCase = (start + end) // 2 slowsort(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) slowsort(__lowerCAmelCase , mid + 1 , __lowerCAmelCase ) if sequence[end] < sequence[mid]: __lowerCamelCase , __lowerCamelCase = sequence[mid], sequence[end] slowsort(__lowerCAmelCase , __lowerCAmelCase , end - 1 ) if __name__ == "__main__": from doctest import testmod testmod()
339
0
import copy import fnmatch import json import os import pickle as pkl import shutil import sys import tarfile import tempfile from collections import OrderedDict from contextlib import contextmanager from functools import partial from hashlib import shaaaa from io import BytesIO from pathlib import Path from urllib.parse import urlparse from zipfile import ZipFile, is_zipfile import cva import numpy as np import requests import wget from filelock import FileLock from PIL import Image from tqdm.auto import tqdm from yaml import Loader, dump, load try: import torch SCREAMING_SNAKE_CASE__ : Any = True except ImportError: SCREAMING_SNAKE_CASE__ : str = False try: from torch.hub import _get_torch_home SCREAMING_SNAKE_CASE__ : Optional[Any] = _get_torch_home() except ImportError: SCREAMING_SNAKE_CASE__ : List[Any] = os.path.expanduser( os.getenv("TORCH_HOME", os.path.join(os.getenv("XDG_CACHE_HOME", "~/.cache"), "torch")) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.path.join(torch_cache_home, "transformers") SCREAMING_SNAKE_CASE__ : List[Any] = "https://cdn.huggingface.co" SCREAMING_SNAKE_CASE__ : Dict = "https://s3.amazonaws.com/models.huggingface.co/bert" SCREAMING_SNAKE_CASE__ : List[str] = "/".join(str(Path(__file__).resolve()).split("/")[:-1]) SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(PATH, "config.yaml") SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.join(PATH, "attributes.txt") SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.join(PATH, "objects.txt") SCREAMING_SNAKE_CASE__ : Dict = os.getenv("PYTORCH_PRETRAINED_BERT_CACHE", default_cache_path) SCREAMING_SNAKE_CASE__ : Tuple = os.getenv("PYTORCH_TRANSFORMERS_CACHE", PYTORCH_PRETRAINED_BERT_CACHE) SCREAMING_SNAKE_CASE__ : Dict = os.getenv("TRANSFORMERS_CACHE", PYTORCH_TRANSFORMERS_CACHE) SCREAMING_SNAKE_CASE__ : Tuple = "pytorch_model.bin" SCREAMING_SNAKE_CASE__ : Union[str, Any] = "config.yaml" def __magic_name__ ( __lowerCAmelCase : Optional[int]=OBJECTS , __lowerCAmelCase : Any=ATTRIBUTES ) -> Any: __lowerCamelCase = [] with open(__lowerCAmelCase ) as f: for object in f.readlines(): vg_classes.append(object.split(''',''' )[0].lower().strip() ) __lowerCamelCase = [] with open(__lowerCAmelCase ) as f: for object in f.readlines(): vg_attrs.append(object.split(''',''' )[0].lower().strip() ) return vg_classes, vg_attrs def __magic_name__ ( __lowerCAmelCase : List[Any] ) -> Tuple: __lowerCamelCase = OrderedDict() with open(__lowerCAmelCase , '''rb''' ) as f: __lowerCamelCase = pkl.load(__lowerCAmelCase )['''model'''] for k in copy.deepcopy(list(ckp.keys() ) ): __lowerCamelCase = ckp.pop(__lowerCAmelCase ) if isinstance(__lowerCAmelCase , np.ndarray ): __lowerCamelCase = torch.tensor(__lowerCAmelCase ) else: assert isinstance(__lowerCAmelCase , torch.tensor ), type(__lowerCAmelCase ) __lowerCamelCase = v return r class lowerCAmelCase__ : a__ : Optional[Any] = {} def __init__( self : Any , SCREAMING_SNAKE_CASE__ : dict , SCREAMING_SNAKE_CASE__ : str = "root" , SCREAMING_SNAKE_CASE__ : Tuple=0 ) -> Optional[Any]: __lowerCamelCase = name __lowerCamelCase = level __lowerCamelCase = {} for k, v in dictionary.items(): if v is None: raise ValueError() __lowerCamelCase = copy.deepcopy(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = copy.deepcopy(SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = Config(SCREAMING_SNAKE_CASE__ , name=SCREAMING_SNAKE_CASE__ , level=level + 1 ) __lowerCamelCase = v setattr(self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = d def __repr__( self : int ) -> Union[str, Any]: return str(list((self._pointer.keys()) ) ) def __setattr__( self : Tuple , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[str]: __lowerCamelCase = val __lowerCamelCase = val __lowerCamelCase = key.split('''.''' ) __lowerCamelCase = len(SCREAMING_SNAKE_CASE__ ) - 1 __lowerCamelCase = self._pointer if len(SCREAMING_SNAKE_CASE__ ) > 1: for i, l in enumerate(SCREAMING_SNAKE_CASE__ ): if hasattr(self , SCREAMING_SNAKE_CASE__ ) and isinstance(getattr(self , SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ): setattr(getattr(self , SCREAMING_SNAKE_CASE__ ) , '''.'''.join(levels[i:] ) , SCREAMING_SNAKE_CASE__ ) if l == last_level: __lowerCamelCase = val else: __lowerCamelCase = pointer[l] def __A ( self : List[str] ) -> Dict: return self._pointer def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Any: with open(f'''{file_name}''' , '''w''' ) as stream: dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : str ) -> Dict: with open(f'''{file_name}''' , '''w''' ) as stream: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @staticmethod def __A ( SCREAMING_SNAKE_CASE__ : List[Any] ) -> Union[str, Any]: with open(SCREAMING_SNAKE_CASE__ ) as stream: __lowerCamelCase = load(SCREAMING_SNAKE_CASE__ , Loader=SCREAMING_SNAKE_CASE__ ) return data def __str__( self : int ) -> Any: __lowerCamelCase = ''' ''' if self._name != "root": __lowerCamelCase = f'''{t * (self._level-1)}{self._name}:\n''' else: __lowerCamelCase = '''''' __lowerCamelCase = self._level for i, (k, v) in enumerate(self._pointer.items() ): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): r += f'''{t * (self._level)}{v}\n''' self._level += 1 else: r += f'''{t * (self._level)}{k}: {v} ({type(SCREAMING_SNAKE_CASE__ ).__name__})\n''' __lowerCamelCase = level return r[:-1] @classmethod def __A ( cls : List[str] , SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : str ) -> Any: __lowerCamelCase , __lowerCamelCase = cls.get_config_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) return cls(SCREAMING_SNAKE_CASE__ ) @classmethod def __A ( cls : str , SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : Tuple ) -> Dict: __lowerCamelCase = kwargs.pop('''cache_dir''' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = kwargs.pop('''force_download''' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = kwargs.pop('''resume_download''' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = kwargs.pop('''proxies''' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = kwargs.pop('''local_files_only''' , SCREAMING_SNAKE_CASE__ ) if os.path.isdir(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif os.path.isfile(SCREAMING_SNAKE_CASE__ ) or is_remote_url(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = pretrained_model_name_or_path else: __lowerCamelCase = hf_bucket_url(SCREAMING_SNAKE_CASE__ , filename=SCREAMING_SNAKE_CASE__ , use_cdn=SCREAMING_SNAKE_CASE__ ) try: # Load from URL or cache if already cached __lowerCamelCase = cached_path( SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ , force_download=SCREAMING_SNAKE_CASE__ , proxies=SCREAMING_SNAKE_CASE__ , resume_download=SCREAMING_SNAKE_CASE__ , local_files_only=SCREAMING_SNAKE_CASE__ , ) # Load config dict if resolved_config_file is None: raise EnvironmentError __lowerCamelCase = Config.load_yaml(SCREAMING_SNAKE_CASE__ ) except EnvironmentError: __lowerCamelCase = '''Can\'t load config for''' raise EnvironmentError(SCREAMING_SNAKE_CASE__ ) if resolved_config_file == config_file: print('''loading configuration file from path''' ) else: print('''loading configuration file cache''' ) return Config.load_yaml(SCREAMING_SNAKE_CASE__ ), kwargs def __magic_name__ ( __lowerCAmelCase : List[Any] ) -> Tuple: __lowerCamelCase = torch.load('''dump.pt''' , map_location=in_tensor.device ) __lowerCamelCase = in_tensor.numpy() __lowerCamelCase = out_tensor.numpy()[0] print(na.shape , na[0, 0, :5] ) print(na.shape , na[0, 0, :5] ) assert np.allclose(__lowerCAmelCase , __lowerCAmelCase , rtol=0.01 , atol=0.1 ), ( f'''{sum([1 for x in np.isclose(__lowerCAmelCase , __lowerCAmelCase , rtol=0.01 , atol=0.1 ).flatten() if x is False] )/len(na.flatten() )*100:.4f} %''' " element-wise mismatch" ) raise Exception('''tensors are all good''' ) # Hugging face functions below def __magic_name__ ( __lowerCAmelCase : List[str] ) -> Union[str, Any]: __lowerCamelCase = urlparse(__lowerCAmelCase ) return parsed.scheme in ("http", "https") def __magic_name__ ( __lowerCAmelCase : str , __lowerCAmelCase : str , __lowerCAmelCase : Union[str, Any]=True ) -> str: __lowerCamelCase = CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX __lowerCamelCase = '''/''' not in model_id if legacy_format: return f'''{endpoint}/{model_id}-{filename}''' else: return f'''{endpoint}/{model_id}/{filename}''' def __magic_name__ ( __lowerCAmelCase : str , __lowerCAmelCase : str , __lowerCAmelCase : int=None , __lowerCAmelCase : Optional[int]=0 , __lowerCAmelCase : Tuple=None , ) -> Optional[Any]: __lowerCamelCase = '''python/{}'''.format(sys.version.split()[0] ) if _torch_available: ua += "; torch/{}".format(torch.__version__ ) if isinstance(__lowerCAmelCase , __lowerCAmelCase ): ua += "; " + "; ".join('''{}/{}'''.format(__lowerCAmelCase , __lowerCAmelCase ) for k, v in user_agent.items() ) elif isinstance(__lowerCAmelCase , __lowerCAmelCase ): ua += "; " + user_agent __lowerCamelCase = {'''user-agent''': ua} if resume_size > 0: __lowerCamelCase = '''bytes=%d-''' % (resume_size,) __lowerCamelCase = requests.get(__lowerCAmelCase , stream=__lowerCAmelCase , proxies=__lowerCAmelCase , headers=__lowerCAmelCase ) if response.status_code == 416: # Range not satisfiable return __lowerCamelCase = response.headers.get('''Content-Length''' ) __lowerCamelCase = resume_size + int(__lowerCAmelCase ) if content_length is not None else None __lowerCamelCase = tqdm( unit='''B''' , unit_scale=__lowerCAmelCase , total=__lowerCAmelCase , initial=__lowerCAmelCase , desc='''Downloading''' , ) for chunk in response.iter_content(chunk_size=1024 ): if chunk: # filter out keep-alive new chunks progress.update(len(__lowerCAmelCase ) ) temp_file.write(__lowerCAmelCase ) progress.close() def __magic_name__ ( __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Optional[int]=None , __lowerCAmelCase : Any=False , __lowerCAmelCase : str=None , __lowerCAmelCase : Optional[Any]=10 , __lowerCAmelCase : Optional[int]=False , __lowerCAmelCase : Union[str, Any]=None , __lowerCAmelCase : Union[str, Any]=False , ) -> Dict: if cache_dir is None: __lowerCamelCase = TRANSFORMERS_CACHE if isinstance(__lowerCAmelCase , __lowerCAmelCase ): __lowerCamelCase = str(__lowerCAmelCase ) os.makedirs(__lowerCAmelCase , exist_ok=__lowerCAmelCase ) __lowerCamelCase = None if not local_files_only: try: __lowerCamelCase = requests.head(__lowerCAmelCase , allow_redirects=__lowerCAmelCase , proxies=__lowerCAmelCase , timeout=__lowerCAmelCase ) if response.status_code == 200: __lowerCamelCase = response.headers.get('''ETag''' ) except (EnvironmentError, requests.exceptions.Timeout): # etag is already None pass __lowerCamelCase = url_to_filename(__lowerCAmelCase , __lowerCAmelCase ) # get cache path to put the file __lowerCamelCase = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) # etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible. # try to get the last downloaded one if etag is None: if os.path.exists(__lowerCAmelCase ): return cache_path else: __lowerCamelCase = [ file for file in fnmatch.filter(os.listdir(__lowerCAmelCase ) , filename + '''.*''' ) if not file.endswith('''.json''' ) and not file.endswith('''.lock''' ) ] if len(__lowerCAmelCase ) > 0: return os.path.join(__lowerCAmelCase , matching_files[-1] ) else: # If files cannot be found and local_files_only=True, # the models might've been found if local_files_only=False # Notify the user about that if local_files_only: raise ValueError( '''Cannot find the requested files in the cached path and outgoing traffic has been''' ''' disabled. To enable model look-ups and downloads online, set \'local_files_only\'''' ''' to False.''' ) return None # From now on, etag is not None. if os.path.exists(__lowerCAmelCase ) and not force_download: return cache_path # Prevent parallel downloads of the same file with a lock. __lowerCamelCase = cache_path + '''.lock''' with FileLock(__lowerCAmelCase ): # If the download just completed while the lock was activated. if os.path.exists(__lowerCAmelCase ) and not force_download: # Even if returning early like here, the lock will be released. return cache_path if resume_download: __lowerCamelCase = cache_path + '''.incomplete''' @contextmanager def _resumable_file_manager(): with open(__lowerCAmelCase , '''a+b''' ) as f: yield f __lowerCamelCase = _resumable_file_manager if os.path.exists(__lowerCAmelCase ): __lowerCamelCase = os.stat(__lowerCAmelCase ).st_size else: __lowerCamelCase = 0 else: __lowerCamelCase = partial(tempfile.NamedTemporaryFile , dir=__lowerCAmelCase , delete=__lowerCAmelCase ) __lowerCamelCase = 0 # Download to temporary file, then copy to cache dir once finished. # Otherwise you get corrupt cache entries if the download gets interrupted. with temp_file_manager() as temp_file: print( '''%s not found in cache or force_download set to True, downloading to %s''' , __lowerCAmelCase , temp_file.name , ) http_get( __lowerCAmelCase , __lowerCAmelCase , proxies=__lowerCAmelCase , resume_size=__lowerCAmelCase , user_agent=__lowerCAmelCase , ) os.replace(temp_file.name , __lowerCAmelCase ) __lowerCamelCase = {'''url''': url, '''etag''': etag} __lowerCamelCase = cache_path + '''.json''' with open(__lowerCAmelCase , '''w''' ) as meta_file: json.dump(__lowerCAmelCase , __lowerCAmelCase ) return cache_path def __magic_name__ ( __lowerCAmelCase : List[str] , __lowerCAmelCase : List[Any]=None ) -> int: __lowerCamelCase = url.encode('''utf-8''' ) __lowerCamelCase = shaaaa(__lowerCAmelCase ) __lowerCamelCase = url_hash.hexdigest() if etag: __lowerCamelCase = etag.encode('''utf-8''' ) __lowerCamelCase = shaaaa(__lowerCAmelCase ) filename += "." + etag_hash.hexdigest() if url.endswith('''.h5''' ): filename += ".h5" return filename def __magic_name__ ( __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Optional[int]=None , __lowerCAmelCase : List[Any]=False , __lowerCAmelCase : Optional[Any]=None , __lowerCAmelCase : Optional[Any]=False , __lowerCAmelCase : List[str]=None , __lowerCAmelCase : Optional[Any]=False , __lowerCAmelCase : Dict=False , __lowerCAmelCase : Dict=False , ) -> List[str]: if cache_dir is None: __lowerCamelCase = TRANSFORMERS_CACHE if isinstance(__lowerCAmelCase , __lowerCAmelCase ): __lowerCamelCase = str(__lowerCAmelCase ) if isinstance(__lowerCAmelCase , __lowerCAmelCase ): __lowerCamelCase = str(__lowerCAmelCase ) if is_remote_url(__lowerCAmelCase ): # URL, so get it from the cache (downloading if necessary) __lowerCamelCase = get_from_cache( __lowerCAmelCase , cache_dir=__lowerCAmelCase , force_download=__lowerCAmelCase , proxies=__lowerCAmelCase , resume_download=__lowerCAmelCase , user_agent=__lowerCAmelCase , local_files_only=__lowerCAmelCase , ) elif os.path.exists(__lowerCAmelCase ): # File, and it exists. __lowerCamelCase = url_or_filename elif urlparse(__lowerCAmelCase ).scheme == "": # File, but it doesn't exist. raise EnvironmentError('''file {} not found'''.format(__lowerCAmelCase ) ) else: # Something unknown raise ValueError('''unable to parse {} as a URL or as a local path'''.format(__lowerCAmelCase ) ) if extract_compressed_file: if not is_zipfile(__lowerCAmelCase ) and not tarfile.is_tarfile(__lowerCAmelCase ): return output_path # Path where we extract compressed archives # We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/" __lowerCamelCase , __lowerCamelCase = os.path.split(__lowerCAmelCase ) __lowerCamelCase = output_file.replace('''.''' , '''-''' ) + '''-extracted''' __lowerCamelCase = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) if os.path.isdir(__lowerCAmelCase ) and os.listdir(__lowerCAmelCase ) and not force_extract: return output_path_extracted # Prevent parallel extractions __lowerCamelCase = output_path + '''.lock''' with FileLock(__lowerCAmelCase ): shutil.rmtree(__lowerCAmelCase , ignore_errors=__lowerCAmelCase ) os.makedirs(__lowerCAmelCase ) if is_zipfile(__lowerCAmelCase ): with ZipFile(__lowerCAmelCase , '''r''' ) as zip_file: zip_file.extractall(__lowerCAmelCase ) zip_file.close() elif tarfile.is_tarfile(__lowerCAmelCase ): __lowerCamelCase = tarfile.open(__lowerCAmelCase ) tar_file.extractall(__lowerCAmelCase ) tar_file.close() else: raise EnvironmentError('''Archive format of {} could not be identified'''.format(__lowerCAmelCase ) ) return output_path_extracted return output_path def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : Optional[Any]="," ) -> Any: assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) if os.path.isfile(__lowerCAmelCase ): with open(__lowerCAmelCase ) as f: __lowerCamelCase = eval(f.read() ) else: __lowerCamelCase = requests.get(__lowerCAmelCase ) try: __lowerCamelCase = requests.json() except Exception: __lowerCamelCase = req.content.decode() assert data is not None, "could not connect" try: __lowerCamelCase = eval(__lowerCAmelCase ) except Exception: __lowerCamelCase = data.split('''\n''' ) req.close() return data def __magic_name__ ( __lowerCAmelCase : Optional[Any] ) -> List[str]: __lowerCamelCase = requests.get(__lowerCAmelCase ) __lowerCamelCase = np.array(Image.open(BytesIO(response.content ) ) ) return img def __magic_name__ ( __lowerCAmelCase : List[Any] ) -> str: __lowerCamelCase = url.split('''/''' )[-1] if fn not in os.listdir(os.getcwd() ): wget.download(__lowerCAmelCase ) with open(__lowerCAmelCase , '''rb''' ) as stream: __lowerCamelCase = pkl.load(__lowerCAmelCase ) __lowerCamelCase = weights.pop('''model''' ) __lowerCamelCase = {} for k, v in model.items(): __lowerCamelCase = torch.from_numpy(__lowerCAmelCase ) if "running_var" in k: __lowerCamelCase = torch.tensor([0] ) __lowerCamelCase = k.replace('''running_var''' , '''num_batches_tracked''' ) __lowerCamelCase = zero return new def __magic_name__ ( ) -> Any: print(f'''{os.path.abspath(os.path.join(__lowerCAmelCase , os.pardir ) )}/demo.ipynb''' ) def __magic_name__ ( __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Dict="RGB" ) -> str: assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) if os.path.isfile(__lowerCAmelCase ): __lowerCamelCase = cva.imread(__lowerCAmelCase ) else: __lowerCamelCase = get_image_from_url(__lowerCAmelCase ) assert img is not None, f'''could not connect to: {im}''' __lowerCamelCase = cva.cvtColor(__lowerCAmelCase , cva.COLOR_BGR2RGB ) if input_format == "RGB": __lowerCamelCase = img[:, :, ::-1] return img def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : Tuple=1 ) -> Optional[int]: return (images[i : i + batch] for i in range(0 , len(__lowerCAmelCase ) , __lowerCAmelCase ))
365
import json import os from typing import Dict, List, Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE__ : Any = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Optional[Any] = { "vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_config_file": "tokenizer_config.json", } SCREAMING_SNAKE_CASE__ : str = { "vocab_file": { "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json" }, "merges_file": { "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt" }, "tokenizer_config_file": { "facebook/blenderbot_small-90M": ( "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json" ) }, } SCREAMING_SNAKE_CASE__ : int = {"facebook/blenderbot_small-90M": 512} def __magic_name__ ( __lowerCAmelCase : List[str] ) -> Tuple: __lowerCamelCase = set() __lowerCamelCase = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __lowerCamelCase = char __lowerCamelCase = set(__lowerCAmelCase ) return pairs class lowerCAmelCase__ ( __lowercase ): a__ : List[Any] = VOCAB_FILES_NAMES a__ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP a__ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ : Dict = ["""input_ids""", """attention_mask"""] def __init__( self : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple="__start__" , SCREAMING_SNAKE_CASE__ : Tuple="__end__" , SCREAMING_SNAKE_CASE__ : List[str]="__unk__" , SCREAMING_SNAKE_CASE__ : str="__null__" , **SCREAMING_SNAKE_CASE__ : Optional[Any] , ) -> Optional[Any]: super().__init__(unk_token=SCREAMING_SNAKE_CASE__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) with open(SCREAMING_SNAKE_CASE__ , encoding='''utf-8''' ) as vocab_handle: __lowerCamelCase = json.load(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = {v: k for k, v in self.encoder.items()} with open(SCREAMING_SNAKE_CASE__ , encoding='''utf-8''' ) as merges_handle: __lowerCamelCase = merges_handle.read().split('''\n''' )[1:-1] __lowerCamelCase = [tuple(merge.split() ) for merge in merges] __lowerCamelCase = dict(zip(SCREAMING_SNAKE_CASE__ , range(len(SCREAMING_SNAKE_CASE__ ) ) ) ) __lowerCamelCase = {} @property def __A ( self : Dict ) -> int: return len(self.encoder ) def __A ( self : str ) -> Dict: return dict(self.encoder , **self.added_tokens_encoder ) def __A ( self : Any , SCREAMING_SNAKE_CASE__ : str ) -> str: if token in self.cache: return self.cache[token] __lowerCamelCase = re.sub('''([.,!?()])''' , R''' \1''' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = re.sub('''(\')''' , R''' \1 ''' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = re.sub(R'''\s{2,}''' , ''' ''' , SCREAMING_SNAKE_CASE__ ) if "\n" in token: __lowerCamelCase = token.replace('''\n''' , ''' __newln__''' ) __lowerCamelCase = token.split(''' ''' ) __lowerCamelCase = [] for token in tokens: if not len(SCREAMING_SNAKE_CASE__ ): continue __lowerCamelCase = token.lower() __lowerCamelCase = tuple(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = tuple(list(word[:-1] ) + [word[-1] + '''</w>'''] ) __lowerCamelCase = get_pairs(SCREAMING_SNAKE_CASE__ ) if not pairs: words.append(SCREAMING_SNAKE_CASE__ ) continue while True: __lowerCamelCase = min(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : self.bpe_ranks.get(SCREAMING_SNAKE_CASE__ , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break __lowerCamelCase , __lowerCamelCase = bigram __lowerCamelCase = [] __lowerCamelCase = 0 while i < len(SCREAMING_SNAKE_CASE__ ): try: __lowerCamelCase = word.index(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) new_word.extend(word[i:j] ) __lowerCamelCase = j except ValueError: new_word.extend(word[i:] ) break if word[i] == first and i < len(SCREAMING_SNAKE_CASE__ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 __lowerCamelCase = tuple(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = new_word if len(SCREAMING_SNAKE_CASE__ ) == 1: break else: __lowerCamelCase = get_pairs(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = '''@@ '''.join(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = word[:-4] __lowerCamelCase = word words.append(SCREAMING_SNAKE_CASE__ ) return " ".join(SCREAMING_SNAKE_CASE__ ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: __lowerCamelCase = [] __lowerCamelCase = re.findall(R'''\S+\n?''' , SCREAMING_SNAKE_CASE__ ) for token in words: split_tokens.extend(list(self.bpe(SCREAMING_SNAKE_CASE__ ).split(''' ''' ) ) ) return split_tokens def __A ( self : str , SCREAMING_SNAKE_CASE__ : str ) -> int: __lowerCamelCase = token.lower() return self.encoder.get(SCREAMING_SNAKE_CASE__ , self.encoder.get(self.unk_token ) ) def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : int ) -> str: return self.decoder.get(SCREAMING_SNAKE_CASE__ , self.unk_token ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] ) -> str: __lowerCamelCase = ''' '''.join(SCREAMING_SNAKE_CASE__ ).replace('''@@ ''' , '''''' ).strip() return out_string def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __lowerCamelCase = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) __lowerCamelCase = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(SCREAMING_SNAKE_CASE__ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=SCREAMING_SNAKE_CASE__ , ensure_ascii=SCREAMING_SNAKE_CASE__ ) + '''\n''' ) __lowerCamelCase = 0 with open(SCREAMING_SNAKE_CASE__ , '''w''' , encoding='''utf-8''' ) as writer: writer.write('''#version: 0.2\n''' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda SCREAMING_SNAKE_CASE__ : kv[1] ): if index != token_index: logger.warning( f'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.''' ''' Please check that the tokenizer is not corrupted!''' ) __lowerCamelCase = token_index writer.write(''' '''.join(SCREAMING_SNAKE_CASE__ ) + '''\n''' ) index += 1 return vocab_file, merge_file
339
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available SCREAMING_SNAKE_CASE__ : Tuple = { "configuration_graphormer": ["GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "GraphormerConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "GraphormerForGraphClassification", "GraphormerModel", "GraphormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_graphormer import GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, GraphormerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_graphormer import ( GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST, GraphormerForGraphClassification, GraphormerModel, GraphormerPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
366
import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class lowerCAmelCase__ ( __lowercase , unittest.TestCase ): a__ : str = ShapEImgaImgPipeline a__ : Union[str, Any] = ["""image"""] a__ : Optional[int] = ["""image"""] a__ : Union[str, Any] = [ """num_images_per_prompt""", """num_inference_steps""", """generator""", """latents""", """guidance_scale""", """frame_size""", """output_type""", """return_dict""", ] a__ : List[str] = False @property def __A ( self : Dict ) -> Optional[Any]: return 32 @property def __A ( self : Optional[int] ) -> Optional[int]: return 32 @property def __A ( self : Optional[int] ) -> List[Any]: return self.time_input_dim * 4 @property def __A ( self : str ) -> List[Any]: return 8 @property def __A ( self : Optional[Any] ) -> Union[str, Any]: torch.manual_seed(0 ) __lowerCamelCase = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) __lowerCamelCase = CLIPVisionModel(SCREAMING_SNAKE_CASE__ ) return model @property def __A ( self : Union[str, Any] ) -> Union[str, Any]: __lowerCamelCase = CLIPImageProcessor( crop_size=2_24 , do_center_crop=SCREAMING_SNAKE_CASE__ , do_normalize=SCREAMING_SNAKE_CASE__ , do_resize=SCREAMING_SNAKE_CASE__ , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=2_24 , ) return image_processor @property def __A ( self : Dict ) -> int: torch.manual_seed(0 ) __lowerCamelCase = { '''num_attention_heads''': 2, '''attention_head_dim''': 16, '''embedding_dim''': self.time_input_dim, '''num_embeddings''': 32, '''embedding_proj_dim''': self.text_embedder_hidden_size, '''time_embed_dim''': self.time_embed_dim, '''num_layers''': 1, '''clip_embed_dim''': self.time_input_dim * 2, '''additional_embeddings''': 0, '''time_embed_act_fn''': '''gelu''', '''norm_in_type''': '''layer''', '''embedding_proj_norm_type''': '''layer''', '''encoder_hid_proj_type''': None, '''added_emb_type''': None, } __lowerCamelCase = PriorTransformer(**SCREAMING_SNAKE_CASE__ ) return model @property def __A ( self : Tuple ) -> Dict: torch.manual_seed(0 ) __lowerCamelCase = { '''param_shapes''': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), '''d_latent''': self.time_input_dim, '''d_hidden''': self.renderer_dim, '''n_output''': 12, '''background''': ( 0.1, 0.1, 0.1, ), } __lowerCamelCase = ShapERenderer(**SCREAMING_SNAKE_CASE__ ) return model def __A ( self : Optional[int] ) -> List[str]: __lowerCamelCase = self.dummy_prior __lowerCamelCase = self.dummy_image_encoder __lowerCamelCase = self.dummy_image_processor __lowerCamelCase = self.dummy_renderer __lowerCamelCase = HeunDiscreteScheduler( beta_schedule='''exp''' , num_train_timesteps=10_24 , prediction_type='''sample''' , use_karras_sigmas=SCREAMING_SNAKE_CASE__ , clip_sample=SCREAMING_SNAKE_CASE__ , clip_sample_range=1.0 , ) __lowerCamelCase = { '''prior''': prior, '''image_encoder''': image_encoder, '''image_processor''': image_processor, '''renderer''': renderer, '''scheduler''': scheduler, } return components def __A ( self : str , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any=0 ) -> int: __lowerCamelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) if str(SCREAMING_SNAKE_CASE__ ).startswith('''mps''' ): __lowerCamelCase = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: __lowerCamelCase = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = { '''image''': input_image, '''generator''': generator, '''num_inference_steps''': 1, '''frame_size''': 32, '''output_type''': '''np''', } return inputs def __A ( self : Union[str, Any] ) -> Dict: __lowerCamelCase = '''cpu''' __lowerCamelCase = self.get_dummy_components() __lowerCamelCase = self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe(**self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = output.images[0] __lowerCamelCase = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __lowerCamelCase = np.array( [ 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __A ( self : str ) -> Tuple: # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def __A ( self : Optional[Any] ) -> str: __lowerCamelCase = torch_device == '''cpu''' __lowerCamelCase = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=SCREAMING_SNAKE_CASE__ , relax_max_difference=SCREAMING_SNAKE_CASE__ , ) def __A ( self : Dict ) -> Optional[int]: __lowerCamelCase = self.get_dummy_components() __lowerCamelCase = self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = 1 __lowerCamelCase = 2 __lowerCamelCase = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) for key in inputs.keys(): if key in self.batch_params: __lowerCamelCase = batch_size * [inputs[key]] __lowerCamelCase = pipe(**SCREAMING_SNAKE_CASE__ , num_images_per_prompt=SCREAMING_SNAKE_CASE__ )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : str ) -> Union[str, Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self : str ) -> Union[str, Any]: __lowerCamelCase = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/corgi.png''' ) __lowerCamelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/test_shap_e_img2img_out.npy''' ) __lowerCamelCase = ShapEImgaImgPipeline.from_pretrained('''openai/shap-e-img2img''' ) __lowerCamelCase = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(0 ) __lowerCamelCase = pipe( SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type='''np''' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
339
0
from __future__ import annotations def __magic_name__ ( __lowerCAmelCase : list[int] ) -> bool: return len(set(__lowerCAmelCase ) ) == len(__lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
367
import glob import os import random from string import ascii_lowercase, digits import cva SCREAMING_SNAKE_CASE__ : str = "" SCREAMING_SNAKE_CASE__ : Any = "" SCREAMING_SNAKE_CASE__ : Optional[Any] = "" SCREAMING_SNAKE_CASE__ : Optional[Any] = 1 # (0 is vertical, 1 is horizontal) def __magic_name__ ( ) -> None: __lowerCamelCase , __lowerCamelCase = get_dataset(__lowerCAmelCase , __lowerCAmelCase ) print('''Processing...''' ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = update_image_and_anno(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) for index, image in enumerate(__lowerCAmelCase ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' __lowerCamelCase = random_chars(32 ) __lowerCamelCase = paths[index].split(os.sep )[-1].rsplit('''.''' , 1 )[0] __lowerCamelCase = f'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(f'''/{file_root}.jpg''' , __lowerCAmelCase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(f'''Success {index+1}/{len(__lowerCAmelCase )} with {file_name}''' ) __lowerCamelCase = [] for anno in new_annos[index]: __lowerCamelCase = f'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(__lowerCAmelCase ) with open(f'''/{file_root}.txt''' , '''w''' ) as outfile: outfile.write('''\n'''.join(line for line in annos_list ) ) def __magic_name__ ( __lowerCAmelCase : str , __lowerCAmelCase : str ) -> tuple[list, list]: __lowerCamelCase = [] __lowerCamelCase = [] for label_file in glob.glob(os.path.join(__lowerCAmelCase , '''*.txt''' ) ): __lowerCamelCase = label_file.split(os.sep )[-1].rsplit('''.''' , 1 )[0] with open(__lowerCAmelCase ) as in_file: __lowerCamelCase = in_file.readlines() __lowerCamelCase = os.path.join(__lowerCAmelCase , f'''{label_name}.jpg''' ) __lowerCamelCase = [] for obj_list in obj_lists: __lowerCamelCase = obj_list.rstrip('''\n''' ).split(''' ''' ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(__lowerCAmelCase ) labels.append(__lowerCAmelCase ) return img_paths, labels def __magic_name__ ( __lowerCAmelCase : list , __lowerCAmelCase : list , __lowerCAmelCase : int = 1 ) -> tuple[list, list, list]: __lowerCamelCase = [] __lowerCamelCase = [] __lowerCamelCase = [] for idx in range(len(__lowerCAmelCase ) ): __lowerCamelCase = [] __lowerCamelCase = img_list[idx] path_list.append(__lowerCAmelCase ) __lowerCamelCase = anno_list[idx] __lowerCamelCase = cva.imread(__lowerCAmelCase ) if flip_type == 1: __lowerCamelCase = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: __lowerCamelCase = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: __lowerCamelCase = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: __lowerCamelCase = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(__lowerCAmelCase ) new_imgs_list.append(__lowerCAmelCase ) return new_imgs_list, new_annos_lists, path_list def __magic_name__ ( __lowerCAmelCase : int = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" __lowerCamelCase = ascii_lowercase + digits return "".join(random.choice(__lowerCAmelCase ) for _ in range(__lowerCAmelCase ) ) if __name__ == "__main__": main() print("DONE ✅")
339
0
def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int ) -> int: return abs(__lowerCAmelCase ) if a == 0 else greatest_common_divisor(b % a , __lowerCAmelCase ) def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int ) -> int: while y: # --> when y=0 then loop will terminate and return x as final GCD. __lowerCamelCase , __lowerCamelCase = y, x % y return abs(__lowerCAmelCase ) def __magic_name__ ( ) -> Tuple: try: __lowerCamelCase = input('''Enter two integers separated by comma (,): ''' ).split(''',''' ) __lowerCamelCase = int(nums[0] ) __lowerCamelCase = int(nums[1] ) print( f'''greatest_common_divisor({num_a}, {num_a}) = ''' f'''{greatest_common_divisor(__lowerCAmelCase , __lowerCAmelCase )}''' ) print(f'''By iterative gcd({num_a}, {num_a}) = {gcd_by_iterative(__lowerCAmelCase , __lowerCAmelCase )}''' ) except (IndexError, UnboundLocalError, ValueError): print('''Wrong input''' ) if __name__ == "__main__": main()
368
import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated SCREAMING_SNAKE_CASE__ : Tuple = collections.namedtuple("_Datasets", ["train", "validation", "test"]) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ SCREAMING_SNAKE_CASE__ : List[str] = "https://storage.googleapis.com/cvdf-datasets/mnist/" def __magic_name__ ( __lowerCAmelCase : Any ) -> int: __lowerCamelCase = numpy.dtype(numpy.uintaa ).newbyteorder('''>''' ) return numpy.frombuffer(bytestream.read(4 ) , dtype=__lowerCAmelCase )[0] @deprecated(__lowerCAmelCase , '''Please use tf.data to implement this functionality.''' ) def __magic_name__ ( __lowerCAmelCase : List[Any] ) -> str: print('''Extracting''' , f.name ) with gzip.GzipFile(fileobj=__lowerCAmelCase ) as bytestream: __lowerCamelCase = _readaa(__lowerCAmelCase ) if magic != 2051: raise ValueError( '''Invalid magic number %d in MNIST image file: %s''' % (magic, f.name) ) __lowerCamelCase = _readaa(__lowerCAmelCase ) __lowerCamelCase = _readaa(__lowerCAmelCase ) __lowerCamelCase = _readaa(__lowerCAmelCase ) __lowerCamelCase = bytestream.read(rows * cols * num_images ) __lowerCamelCase = numpy.frombuffer(__lowerCAmelCase , dtype=numpy.uinta ) __lowerCamelCase = data.reshape(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , 1 ) return data @deprecated(__lowerCAmelCase , '''Please use tf.one_hot on tensors.''' ) def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : List[Any] ) -> Dict: __lowerCamelCase = labels_dense.shape[0] __lowerCamelCase = numpy.arange(__lowerCAmelCase ) * num_classes __lowerCamelCase = numpy.zeros((num_labels, num_classes) ) __lowerCamelCase = 1 return labels_one_hot @deprecated(__lowerCAmelCase , '''Please use tf.data to implement this functionality.''' ) def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : str=False , __lowerCAmelCase : List[str]=10 ) -> List[str]: print('''Extracting''' , f.name ) with gzip.GzipFile(fileobj=__lowerCAmelCase ) as bytestream: __lowerCamelCase = _readaa(__lowerCAmelCase ) if magic != 2049: raise ValueError( '''Invalid magic number %d in MNIST label file: %s''' % (magic, f.name) ) __lowerCamelCase = _readaa(__lowerCAmelCase ) __lowerCamelCase = bytestream.read(__lowerCAmelCase ) __lowerCamelCase = numpy.frombuffer(__lowerCAmelCase , dtype=numpy.uinta ) if one_hot: return _dense_to_one_hot(__lowerCAmelCase , __lowerCAmelCase ) return labels class lowerCAmelCase__ : @deprecated( SCREAMING_SNAKE_CASE__ , '''Please use alternatives such as official/mnist/_DataSet.py''' ''' from tensorflow/models.''' , ) def __init__( self : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : List[str]=False , SCREAMING_SNAKE_CASE__ : str=dtypes.floataa , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : str=None , ) -> Optional[int]: __lowerCamelCase , __lowerCamelCase = random_seed.get_seed(SCREAMING_SNAKE_CASE__ ) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seeda if seed is None else seeda ) __lowerCamelCase = dtypes.as_dtype(SCREAMING_SNAKE_CASE__ ).base_dtype if dtype not in (dtypes.uinta, dtypes.floataa): raise TypeError('''Invalid image dtype %r, expected uint8 or float32''' % dtype ) if fake_data: __lowerCamelCase = 1_00_00 __lowerCamelCase = one_hot else: assert ( images.shape[0] == labels.shape[0] ), f'''images.shape: {images.shape} labels.shape: {labels.shape}''' __lowerCamelCase = images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 __lowerCamelCase = images.reshape( images.shape[0] , images.shape[1] * images.shape[2] ) if dtype == dtypes.floataa: # Convert from [0, 255] -> [0.0, 1.0]. __lowerCamelCase = images.astype(numpy.floataa ) __lowerCamelCase = numpy.multiply(SCREAMING_SNAKE_CASE__ , 1.0 / 255.0 ) __lowerCamelCase = images __lowerCamelCase = labels __lowerCamelCase = 0 __lowerCamelCase = 0 @property def __A ( self : str ) -> Optional[int]: return self._images @property def __A ( self : Any ) -> Dict: return self._labels @property def __A ( self : List[Any] ) -> int: return self._num_examples @property def __A ( self : str ) -> Any: return self._epochs_completed def __A ( self : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : str=True ) -> str: if fake_data: __lowerCamelCase = [1] * 7_84 __lowerCamelCase = [1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(SCREAMING_SNAKE_CASE__ )], [fake_label for _ in range(SCREAMING_SNAKE_CASE__ )], ) __lowerCamelCase = self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: __lowerCamelCase = numpy.arange(self._num_examples ) numpy.random.shuffle(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.images[perma] __lowerCamelCase = self.labels[perma] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch __lowerCamelCase = self._num_examples - start __lowerCamelCase = self._images[start : self._num_examples] __lowerCamelCase = self._labels[start : self._num_examples] # Shuffle the data if shuffle: __lowerCamelCase = numpy.arange(self._num_examples ) numpy.random.shuffle(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.images[perm] __lowerCamelCase = self.labels[perm] # Start next epoch __lowerCamelCase = 0 __lowerCamelCase = batch_size - rest_num_examples __lowerCamelCase = self._index_in_epoch __lowerCamelCase = self._images[start:end] __lowerCamelCase = self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part) , axis=0 ), numpy.concatenate((labels_rest_part, labels_new_part) , axis=0 ), ) else: self._index_in_epoch += batch_size __lowerCamelCase = self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(__lowerCAmelCase , '''Please write your own downloading logic.''' ) def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int , __lowerCAmelCase : Union[str, Any] ) -> List[Any]: if not gfile.Exists(__lowerCAmelCase ): gfile.MakeDirs(__lowerCAmelCase ) __lowerCamelCase = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) if not gfile.Exists(__lowerCAmelCase ): urllib.request.urlretrieve(__lowerCAmelCase , __lowerCAmelCase ) # noqa: S310 with gfile.GFile(__lowerCAmelCase ) as f: __lowerCamelCase = f.size() print('''Successfully downloaded''' , __lowerCAmelCase , __lowerCAmelCase , '''bytes.''' ) return filepath @deprecated( __lowerCAmelCase , '''Please use alternatives such as:''' ''' tensorflow_datasets.load(\'mnist\')''' ) def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[Any]=False , __lowerCAmelCase : Dict=False , __lowerCAmelCase : List[str]=dtypes.floataa , __lowerCAmelCase : Union[str, Any]=True , __lowerCAmelCase : int=5000 , __lowerCAmelCase : Any=None , __lowerCAmelCase : List[str]=DEFAULT_SOURCE_URL , ) -> Optional[Any]: if fake_data: def fake(): return _DataSet( [] , [] , fake_data=__lowerCAmelCase , one_hot=__lowerCAmelCase , dtype=__lowerCAmelCase , seed=__lowerCAmelCase ) __lowerCamelCase = fake() __lowerCamelCase = fake() __lowerCamelCase = fake() return _Datasets(train=__lowerCAmelCase , validation=__lowerCAmelCase , test=__lowerCAmelCase ) if not source_url: # empty string check __lowerCamelCase = DEFAULT_SOURCE_URL __lowerCamelCase = '''train-images-idx3-ubyte.gz''' __lowerCamelCase = '''train-labels-idx1-ubyte.gz''' __lowerCamelCase = '''t10k-images-idx3-ubyte.gz''' __lowerCamelCase = '''t10k-labels-idx1-ubyte.gz''' __lowerCamelCase = _maybe_download( __lowerCAmelCase , __lowerCAmelCase , source_url + train_images_file ) with gfile.Open(__lowerCAmelCase , '''rb''' ) as f: __lowerCamelCase = _extract_images(__lowerCAmelCase ) __lowerCamelCase = _maybe_download( __lowerCAmelCase , __lowerCAmelCase , source_url + train_labels_file ) with gfile.Open(__lowerCAmelCase , '''rb''' ) as f: __lowerCamelCase = _extract_labels(__lowerCAmelCase , one_hot=__lowerCAmelCase ) __lowerCamelCase = _maybe_download( __lowerCAmelCase , __lowerCAmelCase , source_url + test_images_file ) with gfile.Open(__lowerCAmelCase , '''rb''' ) as f: __lowerCamelCase = _extract_images(__lowerCAmelCase ) __lowerCamelCase = _maybe_download( __lowerCAmelCase , __lowerCAmelCase , source_url + test_labels_file ) with gfile.Open(__lowerCAmelCase , '''rb''' ) as f: __lowerCamelCase = _extract_labels(__lowerCAmelCase , one_hot=__lowerCAmelCase ) if not 0 <= validation_size <= len(__lowerCAmelCase ): __lowerCamelCase = ( '''Validation size should be between 0 and ''' f'''{len(__lowerCAmelCase )}. Received: {validation_size}.''' ) raise ValueError(__lowerCAmelCase ) __lowerCamelCase = train_images[:validation_size] __lowerCamelCase = train_labels[:validation_size] __lowerCamelCase = train_images[validation_size:] __lowerCamelCase = train_labels[validation_size:] __lowerCamelCase = {'''dtype''': dtype, '''reshape''': reshape, '''seed''': seed} __lowerCamelCase = _DataSet(__lowerCAmelCase , __lowerCAmelCase , **__lowerCAmelCase ) __lowerCamelCase = _DataSet(__lowerCAmelCase , __lowerCAmelCase , **__lowerCAmelCase ) __lowerCamelCase = _DataSet(__lowerCAmelCase , __lowerCAmelCase , **__lowerCAmelCase ) return _Datasets(train=__lowerCAmelCase , validation=__lowerCAmelCase , test=__lowerCAmelCase )
339
0
from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Sequence, Value from .base import TaskTemplate @dataclass(frozen=__lowercase ) class lowerCAmelCase__ ( __lowercase ): # `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization a__ : str = field(default="""question-answering-extractive""" , metadata={"""include_in_asdict_even_if_is_default""": True} ) a__ : ClassVar[Features] = Features({"""question""": Value("""string""" ), """context""": Value("""string""" )} ) a__ : ClassVar[Features] = Features( { """answers""": Sequence( { """text""": Value("""string""" ), """answer_start""": Value("""int32""" ), } ) } ) a__ : str = "question" a__ : str = "context" a__ : str = "answers" @property def __A ( self : str ) -> Dict[str, str]: return {self.question_column: "question", self.context_column: "context", self.answers_column: "answers"}
369
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_squeezebert import SqueezeBertTokenizer SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Dict = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "vocab_file": { "squeezebert/squeezebert-uncased": ( "https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt" ), "squeezebert/squeezebert-mnli": "https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt", "squeezebert/squeezebert-mnli-headless": ( "https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt" ), }, "tokenizer_file": { "squeezebert/squeezebert-uncased": ( "https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/tokenizer.json" ), "squeezebert/squeezebert-mnli": ( "https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/tokenizer.json" ), "squeezebert/squeezebert-mnli-headless": ( "https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/tokenizer.json" ), }, } SCREAMING_SNAKE_CASE__ : List[Any] = { "squeezebert/squeezebert-uncased": 512, "squeezebert/squeezebert-mnli": 512, "squeezebert/squeezebert-mnli-headless": 512, } SCREAMING_SNAKE_CASE__ : Dict = { "squeezebert/squeezebert-uncased": {"do_lower_case": True}, "squeezebert/squeezebert-mnli": {"do_lower_case": True}, "squeezebert/squeezebert-mnli-headless": {"do_lower_case": True}, } class lowerCAmelCase__ ( __lowercase ): a__ : Optional[int] = VOCAB_FILES_NAMES a__ : Any = PRETRAINED_VOCAB_FILES_MAP a__ : Union[str, Any] = PRETRAINED_INIT_CONFIGURATION a__ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ : Optional[Any] = SqueezeBertTokenizer def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[UNK]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[PAD]" , SCREAMING_SNAKE_CASE__ : Tuple="[CLS]" , SCREAMING_SNAKE_CASE__ : str="[MASK]" , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : int=None , **SCREAMING_SNAKE_CASE__ : Dict , ) -> Optional[Any]: super().__init__( SCREAMING_SNAKE_CASE__ , tokenizer_file=SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , tokenize_chinese_chars=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = 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 ): __lowerCamelCase = getattr(SCREAMING_SNAKE_CASE__ , normalizer_state.pop('''type''' ) ) __lowerCamelCase = do_lower_case __lowerCamelCase = strip_accents __lowerCamelCase = tokenize_chinese_chars __lowerCamelCase = normalizer_class(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = do_lower_case def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[str]=None ) -> str: __lowerCamelCase = [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 : Tuple , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: __lowerCamelCase = [self.sep_token_id] __lowerCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __A ( self : int , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: __lowerCamelCase = self._tokenizer.model.save(SCREAMING_SNAKE_CASE__ , name=SCREAMING_SNAKE_CASE__ ) return tuple(SCREAMING_SNAKE_CASE__ )
339
0
def __magic_name__ ( __lowerCAmelCase : dict ) -> set: __lowerCamelCase = set() # edges = list of graph's edges __lowerCamelCase = get_edges(__lowerCAmelCase ) # While there are still elements in edges list, take an arbitrary edge # (from_node, to_node) and add his extremity to chosen_vertices and then # remove all arcs adjacent to the from_node and to_node while edges: __lowerCamelCase , __lowerCamelCase = edges.pop() chosen_vertices.add(__lowerCAmelCase ) chosen_vertices.add(__lowerCAmelCase ) for edge in edges.copy(): if from_node in edge or to_node in edge: edges.discard(__lowerCAmelCase ) return chosen_vertices def __magic_name__ ( __lowerCAmelCase : dict ) -> set: __lowerCamelCase = set() for from_node, to_nodes in graph.items(): for to_node in to_nodes: edges.add((from_node, to_node) ) return edges if __name__ == "__main__": import doctest doctest.testmod() # graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} # print(f"Matching vertex cover:\n{matching_min_vertex_cover(graph)}")
370
from __future__ import annotations def __magic_name__ ( __lowerCAmelCase : list[int] ) -> bool: return len(set(__lowerCAmelCase ) ) == len(__lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
339
0
# This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny vocab first, and then a tiny model - so the outcome is truly tiny - # all files ~60KB. As compared to taking a full-size model, reducing to the minimum its layers and # emb dimensions, but keeping the full vocab + merges files, leading to ~3MB in total for all files. # The latter is done by `fsmt-make-super-tiny-model.py`. # # It will be used then as "stas/tiny-wmt19-en-ru" from pathlib import Path import json import tempfile from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ : str = "tiny-wmt19-en-ru" # Build # borrowed from a test SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "w</w>", "r</w>", "t</w>", "lo", "low", "er</w>", "low</w>", "lowest</w>", "newer</w>", "wider</w>", "<unk>", ] SCREAMING_SNAKE_CASE__ : Dict = dict(zip(vocab, range(len(vocab)))) SCREAMING_SNAKE_CASE__ : List[Any] = ["l o 123", "lo w 1456", "e r</w> 1789", ""] with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE__ : str = Path(tmpdirname) SCREAMING_SNAKE_CASE__ : List[Any] = build_dir / VOCAB_FILES_NAMES["src_vocab_file"] SCREAMING_SNAKE_CASE__ : Tuple = build_dir / VOCAB_FILES_NAMES["tgt_vocab_file"] SCREAMING_SNAKE_CASE__ : Union[str, Any] = build_dir / VOCAB_FILES_NAMES["merges_file"] with open(src_vocab_file, "w") as fp: fp.write(json.dumps(vocab_tokens)) with open(tgt_vocab_file, "w") as fp: fp.write(json.dumps(vocab_tokens)) with open(merges_file, "w") as fp: fp.write("\n".join(merges)) SCREAMING_SNAKE_CASE__ : Optional[int] = FSMTTokenizer( langs=["en", "ru"], src_vocab_size=len(vocab), tgt_vocab_size=len(vocab), src_vocab_file=src_vocab_file, tgt_vocab_file=tgt_vocab_file, merges_file=merges_file, ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = FSMTConfig( langs=["ru", "en"], src_vocab_size=1_000, tgt_vocab_size=1_000, d_model=4, encoder_layers=1, decoder_layers=1, encoder_ffn_dim=4, decoder_ffn_dim=4, encoder_attention_heads=1, decoder_attention_heads=1, ) SCREAMING_SNAKE_CASE__ : int = FSMTForConditionalGeneration(config) print(F'num of params {tiny_model.num_parameters()}') # Test SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer(["Making tiny model"], return_tensors="pt") SCREAMING_SNAKE_CASE__ : int = tiny_model(**batch) print("test output:", len(outputs.logits[0])) # Save tiny_model.half() # makes it smaller tiny_model.save_pretrained(mname_tiny) tokenizer.save_pretrained(mname_tiny) print(F'Generated {mname_tiny}') # Upload # transformers-cli upload tiny-wmt19-en-ru
371
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) SCREAMING_SNAKE_CASE__ : Dict = { "configuration_falcon": ["FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP", "FalconConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Tuple = [ "FALCON_PRETRAINED_MODEL_ARCHIVE_LIST", "FalconForCausalLM", "FalconModel", "FalconPreTrainedModel", "FalconForSequenceClassification", "FalconForTokenClassification", "FalconForQuestionAnswering", ] if TYPE_CHECKING: from .configuration_falcon import FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP, FalconConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_falcon import ( FALCON_PRETRAINED_MODEL_ARCHIVE_LIST, FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, FalconPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
339
0
import argparse import torch from torch import nn from transformers import SpeechaTextConfig, SpeechaTextForConditionalGeneration def __magic_name__ ( __lowerCAmelCase : Union[str, Any] ) -> Tuple: __lowerCamelCase = [ '''encoder.version''', '''decoder.version''', '''model.encoder.version''', '''model.decoder.version''', '''decoder.output_projection.weight''', '''_float_tensor''', '''encoder.embed_positions._float_tensor''', '''decoder.embed_positions._float_tensor''', ] for k in ignore_keys: state_dict.pop(__lowerCAmelCase , __lowerCAmelCase ) def __magic_name__ ( __lowerCAmelCase : List[str] ) -> Any: __lowerCamelCase = list(s_dict.keys() ) for key in keys: if "transformer_layers" in key: __lowerCamelCase = s_dict.pop(__lowerCAmelCase ) elif "subsample" in key: __lowerCamelCase = s_dict.pop(__lowerCAmelCase ) def __magic_name__ ( __lowerCAmelCase : Tuple ) -> Any: __lowerCamelCase , __lowerCamelCase = emb.weight.shape __lowerCamelCase = nn.Linear(__lowerCAmelCase , __lowerCAmelCase , bias=__lowerCAmelCase ) __lowerCamelCase = emb.weight.data return lin_layer def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[int] ) -> Optional[Any]: __lowerCamelCase = torch.load(__lowerCAmelCase , map_location='''cpu''' ) __lowerCamelCase = mam_aaa['''args'''] __lowerCamelCase = mam_aaa['''model'''] __lowerCamelCase = state_dict['''decoder.output_projection.weight'''] remove_ignore_keys_(__lowerCAmelCase ) rename_keys(__lowerCAmelCase ) __lowerCamelCase = state_dict['''decoder.embed_tokens.weight'''].shape[0] __lowerCamelCase = args.share_decoder_input_output_embed __lowerCamelCase = [int(__lowerCAmelCase ) for i in args.conv_kernel_sizes.split(''',''' )] __lowerCamelCase = SpeechaTextConfig( vocab_size=__lowerCAmelCase , max_source_positions=args.max_source_positions , max_target_positions=args.max_target_positions , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function='''relu''' , num_conv_layers=len(__lowerCAmelCase ) , conv_channels=args.conv_channels , conv_kernel_sizes=__lowerCAmelCase , input_feat_per_channel=args.input_feat_per_channel , input_channels=args.input_channels , tie_word_embeddings=__lowerCAmelCase , num_beams=5 , max_length=200 , use_cache=__lowerCAmelCase , decoder_start_token_id=2 , early_stopping=__lowerCAmelCase , ) __lowerCamelCase = SpeechaTextForConditionalGeneration(__lowerCAmelCase ) __lowerCamelCase , __lowerCamelCase = model.model.load_state_dict(__lowerCAmelCase , strict=__lowerCAmelCase ) if len(__lowerCAmelCase ) > 0 and not set(__lowerCAmelCase ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( '''Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,''' f''' but all the following weights are missing {missing}''' ) if tie_embeds: __lowerCamelCase = make_linear_from_emb(model.model.decoder.embed_tokens ) else: __lowerCamelCase = lm_head_weights model.save_pretrained(__lowerCAmelCase ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() # Required parameters parser.add_argument("--fairseq_path", type=str, help="Path to the fairseq model (.pt) file.") parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") SCREAMING_SNAKE_CASE__ = parser.parse_args() convert_fairseq_sat_checkpoint_to_tfms(args.fairseq_path, args.pytorch_dump_folder_path)
350
def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int ) -> int: return abs(__lowerCAmelCase ) if a == 0 else greatest_common_divisor(b % a , __lowerCAmelCase ) def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int ) -> int: while y: # --> when y=0 then loop will terminate and return x as final GCD. __lowerCamelCase , __lowerCamelCase = y, x % y return abs(__lowerCAmelCase ) def __magic_name__ ( ) -> Tuple: try: __lowerCamelCase = input('''Enter two integers separated by comma (,): ''' ).split(''',''' ) __lowerCamelCase = int(nums[0] ) __lowerCamelCase = int(nums[1] ) print( f'''greatest_common_divisor({num_a}, {num_a}) = ''' f'''{greatest_common_divisor(__lowerCAmelCase , __lowerCAmelCase )}''' ) print(f'''By iterative gcd({num_a}, {num_a}) = {gcd_by_iterative(__lowerCAmelCase , __lowerCAmelCase )}''' ) except (IndexError, UnboundLocalError, ValueError): print('''Wrong input''' ) if __name__ == "__main__": main()
339
0
"""simple docstring""" import flax.linen as nn import jax.numpy as jnp from .attention_flax import FlaxTransformeraDModel from .resnet_flax import FlaxDownsampleaD, FlaxResnetBlockaD, FlaxUpsampleaD class lowerCAmelCase__ ( nn.Module ): a__ : int a__ : int a__ : float = 0.0 a__ : int = 1 a__ : int = 1 a__ : bool = True a__ : bool = False a__ : bool = False a__ : bool = False a__ : jnp.dtype = jnp.floataa def __A ( self : int ) -> Optional[Any]: __lowerCamelCase = [] __lowerCamelCase = [] for i in range(self.num_layers ): __lowerCamelCase = self.in_channels if i == 0 else self.out_channels __lowerCamelCase = FlaxResnetBlockaD( in_channels=SCREAMING_SNAKE_CASE__ , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = FlaxTransformeraDModel( in_channels=self.out_channels , n_heads=self.num_attention_heads , d_head=self.out_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , only_cross_attention=self.only_cross_attention , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) attentions.append(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = resnets __lowerCamelCase = attentions if self.add_downsample: __lowerCamelCase = FlaxDownsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self : str , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Tuple=True ) -> Optional[int]: __lowerCamelCase = () for resnet, attn in zip(self.resnets , self.attentions ): __lowerCamelCase = resnet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , deterministic=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = attn(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , deterministic=SCREAMING_SNAKE_CASE__ ) output_states += (hidden_states,) if self.add_downsample: __lowerCamelCase = self.downsamplers_a(SCREAMING_SNAKE_CASE__ ) output_states += (hidden_states,) return hidden_states, output_states class lowerCAmelCase__ ( nn.Module ): a__ : int a__ : int a__ : float = 0.0 a__ : int = 1 a__ : bool = True a__ : jnp.dtype = jnp.floataa def __A ( self : Optional[Any] ) -> List[Any]: __lowerCamelCase = [] for i in range(self.num_layers ): __lowerCamelCase = self.in_channels if i == 0 else self.out_channels __lowerCamelCase = FlaxResnetBlockaD( in_channels=SCREAMING_SNAKE_CASE__ , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = resnets if self.add_downsample: __lowerCamelCase = FlaxDownsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any]=True ) -> Union[str, Any]: __lowerCamelCase = () for resnet in self.resnets: __lowerCamelCase = resnet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , deterministic=SCREAMING_SNAKE_CASE__ ) output_states += (hidden_states,) if self.add_downsample: __lowerCamelCase = self.downsamplers_a(SCREAMING_SNAKE_CASE__ ) output_states += (hidden_states,) return hidden_states, output_states class lowerCAmelCase__ ( nn.Module ): a__ : int a__ : int a__ : int a__ : float = 0.0 a__ : int = 1 a__ : int = 1 a__ : bool = True a__ : bool = False a__ : bool = False a__ : bool = False a__ : jnp.dtype = jnp.floataa def __A ( self : str ) -> Dict: __lowerCamelCase = [] __lowerCamelCase = [] for i in range(self.num_layers ): __lowerCamelCase = self.in_channels if (i == self.num_layers - 1) else self.out_channels __lowerCamelCase = self.prev_output_channel if i == 0 else self.out_channels __lowerCamelCase = FlaxResnetBlockaD( in_channels=resnet_in_channels + res_skip_channels , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = FlaxTransformeraDModel( in_channels=self.out_channels , n_heads=self.num_attention_heads , d_head=self.out_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , only_cross_attention=self.only_cross_attention , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) attentions.append(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = resnets __lowerCamelCase = attentions if self.add_upsample: __lowerCamelCase = FlaxUpsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Any=True ) -> List[str]: for resnet, attn in zip(self.resnets , self.attentions ): # pop res hidden states __lowerCamelCase = res_hidden_states_tuple[-1] __lowerCamelCase = res_hidden_states_tuple[:-1] __lowerCamelCase = jnp.concatenate((hidden_states, res_hidden_states) , axis=-1 ) __lowerCamelCase = resnet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , deterministic=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = attn(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , deterministic=SCREAMING_SNAKE_CASE__ ) if self.add_upsample: __lowerCamelCase = self.upsamplers_a(SCREAMING_SNAKE_CASE__ ) return hidden_states class lowerCAmelCase__ ( nn.Module ): a__ : int a__ : int a__ : int a__ : float = 0.0 a__ : int = 1 a__ : bool = True a__ : jnp.dtype = jnp.floataa def __A ( self : Tuple ) -> int: __lowerCamelCase = [] for i in range(self.num_layers ): __lowerCamelCase = self.in_channels if (i == self.num_layers - 1) else self.out_channels __lowerCamelCase = self.prev_output_channel if i == 0 else self.out_channels __lowerCamelCase = FlaxResnetBlockaD( in_channels=resnet_in_channels + res_skip_channels , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = resnets if self.add_upsample: __lowerCamelCase = FlaxUpsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self : Dict , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Tuple=True ) -> Dict: for resnet in self.resnets: # pop res hidden states __lowerCamelCase = res_hidden_states_tuple[-1] __lowerCamelCase = res_hidden_states_tuple[:-1] __lowerCamelCase = jnp.concatenate((hidden_states, res_hidden_states) , axis=-1 ) __lowerCamelCase = resnet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , deterministic=SCREAMING_SNAKE_CASE__ ) if self.add_upsample: __lowerCamelCase = self.upsamplers_a(SCREAMING_SNAKE_CASE__ ) return hidden_states class lowerCAmelCase__ ( nn.Module ): a__ : int a__ : float = 0.0 a__ : int = 1 a__ : int = 1 a__ : bool = False a__ : bool = False a__ : jnp.dtype = jnp.floataa def __A ( self : List[str] ) -> str: # there is always at least one resnet __lowerCamelCase = [ FlaxResnetBlockaD( in_channels=self.in_channels , out_channels=self.in_channels , dropout_prob=self.dropout , dtype=self.dtype , ) ] __lowerCamelCase = [] for _ in range(self.num_layers ): __lowerCamelCase = FlaxTransformeraDModel( in_channels=self.in_channels , n_heads=self.num_attention_heads , d_head=self.in_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) attentions.append(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = FlaxResnetBlockaD( in_channels=self.in_channels , out_channels=self.in_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = resnets __lowerCamelCase = attentions def __call__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str]=True ) -> Any: __lowerCamelCase = self.resnets[0](SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for attn, resnet in zip(self.attentions , self.resnets[1:] ): __lowerCamelCase = attn(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , deterministic=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = resnet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , deterministic=SCREAMING_SNAKE_CASE__ ) return hidden_states
351
import unittest from transformers import is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, require_torch, slow if is_flax_available(): import optax from flax.training.common_utils import onehot from transformers import AutoTokenizer, FlaxMTaForConditionalGeneration from transformers.models.ta.modeling_flax_ta import shift_tokens_right @require_torch @require_sentencepiece @require_tokenizers @require_flax class lowerCAmelCase__ ( unittest.TestCase ): @slow def __A ( self : Optional[int] ) -> Union[str, Any]: __lowerCamelCase = FlaxMTaForConditionalGeneration.from_pretrained('''google/mt5-small''' ) __lowerCamelCase = AutoTokenizer.from_pretrained('''google/mt5-small''' ) __lowerCamelCase = tokenizer('''Hello there''' , return_tensors='''np''' ).input_ids __lowerCamelCase = tokenizer('''Hi I am''' , return_tensors='''np''' ).input_ids __lowerCamelCase = shift_tokens_right(SCREAMING_SNAKE_CASE__ , model.config.pad_token_id , model.config.decoder_start_token_id ) __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ , decoder_input_ids=SCREAMING_SNAKE_CASE__ ).logits __lowerCamelCase = optax.softmax_cross_entropy(SCREAMING_SNAKE_CASE__ , onehot(SCREAMING_SNAKE_CASE__ , logits.shape[-1] ) ).mean() __lowerCamelCase = -(labels.shape[-1] * loss.item()) __lowerCamelCase = -84.9127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1e-4 )
339
0
import torch from diffusers import EulerDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class lowerCAmelCase__ ( __lowercase ): a__ : List[str] = (EulerDiscreteScheduler,) a__ : Any = 10 def __A ( self : Any , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Any: __lowerCamelCase = { '''num_train_timesteps''': 11_00, '''beta_start''': 0.0001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**SCREAMING_SNAKE_CASE__ ) return config def __A ( self : int ) -> Dict: for timesteps in [10, 50, 1_00, 10_00]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE__ ) def __A ( self : List[str] ) -> int: for beta_start, beta_end in zip([0.00001, 0.0001, 0.001] , [0.0002, 0.002, 0.02] ): self.check_over_configs(beta_start=SCREAMING_SNAKE_CASE__ , beta_end=SCREAMING_SNAKE_CASE__ ) def __A ( self : Any ) -> str: for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[int] ) -> int: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE__ ) def __A ( self : Dict ) -> str: __lowerCamelCase = self.scheduler_classes[0] __lowerCamelCase = self.get_scheduler_config() __lowerCamelCase = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(self.num_inference_steps ) __lowerCamelCase = torch.manual_seed(0 ) __lowerCamelCase = self.dummy_model() __lowerCamelCase = self.dummy_sample_deter * scheduler.init_noise_sigma __lowerCamelCase = sample.to(SCREAMING_SNAKE_CASE__ ) for i, t in enumerate(scheduler.timesteps ): __lowerCamelCase = scheduler.scale_model_input(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = output.prev_sample __lowerCamelCase = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 10.0807 ) < 1e-2 assert abs(result_mean.item() - 0.0131 ) < 1e-3 def __A ( self : Union[str, Any] ) -> str: __lowerCamelCase = self.scheduler_classes[0] __lowerCamelCase = self.get_scheduler_config(prediction_type='''v_prediction''' ) __lowerCamelCase = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(self.num_inference_steps ) __lowerCamelCase = torch.manual_seed(0 ) __lowerCamelCase = self.dummy_model() __lowerCamelCase = self.dummy_sample_deter * scheduler.init_noise_sigma __lowerCamelCase = sample.to(SCREAMING_SNAKE_CASE__ ) for i, t in enumerate(scheduler.timesteps ): __lowerCamelCase = scheduler.scale_model_input(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = output.prev_sample __lowerCamelCase = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 0.0002 ) < 1e-2 assert abs(result_mean.item() - 2.2_676e-06 ) < 1e-3 def __A ( self : Optional[Any] ) -> Tuple: __lowerCamelCase = self.scheduler_classes[0] __lowerCamelCase = self.get_scheduler_config() __lowerCamelCase = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(self.num_inference_steps , device=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = torch.manual_seed(0 ) __lowerCamelCase = self.dummy_model() __lowerCamelCase = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() __lowerCamelCase = sample.to(SCREAMING_SNAKE_CASE__ ) for t in scheduler.timesteps: __lowerCamelCase = scheduler.scale_model_input(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = output.prev_sample __lowerCamelCase = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 10.0807 ) < 1e-2 assert abs(result_mean.item() - 0.0131 ) < 1e-3 def __A ( self : int ) -> Optional[int]: __lowerCamelCase = self.scheduler_classes[0] __lowerCamelCase = self.get_scheduler_config() __lowerCamelCase = scheduler_class(**SCREAMING_SNAKE_CASE__ , use_karras_sigmas=SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(self.num_inference_steps , device=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = torch.manual_seed(0 ) __lowerCamelCase = self.dummy_model() __lowerCamelCase = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() __lowerCamelCase = sample.to(SCREAMING_SNAKE_CASE__ ) for t in scheduler.timesteps: __lowerCamelCase = scheduler.scale_model_input(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = output.prev_sample __lowerCamelCase = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 124.52299499511719 ) < 1e-2 assert abs(result_mean.item() - 0.16213932633399963 ) < 1e-3
352
import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer SCREAMING_SNAKE_CASE__ : Optional[int] = "bart" SCREAMING_SNAKE_CASE__ : Dict = True @st.cache(allow_output_mutation=__lowerCAmelCase ) def __magic_name__ ( ) -> str: if LOAD_DENSE_INDEX: __lowerCamelCase = AutoTokenizer.from_pretrained('''yjernite/retribert-base-uncased''' ) __lowerCamelCase = AutoModel.from_pretrained('''yjernite/retribert-base-uncased''' ).to('''cuda:0''' ) __lowerCamelCase = qar_model.eval() else: __lowerCamelCase , __lowerCamelCase = (None, None) if MODEL_TYPE == "bart": __lowerCamelCase = AutoTokenizer.from_pretrained('''yjernite/bart_eli5''' ) __lowerCamelCase = AutoModelForSeqaSeqLM.from_pretrained('''yjernite/bart_eli5''' ).to('''cuda:0''' ) __lowerCamelCase = torch.load('''seq2seq_models/eli5_bart_model_blm_2.pth''' ) sas_model.load_state_dict(save_dict['''model'''] ) __lowerCamelCase = sas_model.eval() else: __lowerCamelCase , __lowerCamelCase = make_qa_sas_model( model_name='''t5-small''' , from_file='''seq2seq_models/eli5_t5_model_1024_4.pth''' , device='''cuda:0''' ) return (qar_tokenizer, qar_model, sas_tokenizer, sas_model) @st.cache(allow_output_mutation=__lowerCAmelCase ) def __magic_name__ ( ) -> Optional[int]: if LOAD_DENSE_INDEX: __lowerCamelCase = faiss.StandardGpuResources() __lowerCamelCase = datasets.load_dataset(path='''wiki_snippets''' , name='''wiki40b_en_100_0''' )['''train'''] __lowerCamelCase = np.memmap( '''wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat''' , dtype='''float32''' , mode='''r''' , shape=(wikiaab_passages.num_rows, 128) , ) __lowerCamelCase = faiss.IndexFlatIP(128 ) __lowerCamelCase = faiss.index_cpu_to_gpu(__lowerCAmelCase , 1 , __lowerCAmelCase ) wikiaab_gpu_index_flat.add(__lowerCAmelCase ) # TODO fix for larger GPU else: __lowerCamelCase , __lowerCamelCase = (None, None) __lowerCamelCase = Elasticsearch([{'''host''': '''localhost''', '''port''': '''9200'''}] ) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=__lowerCAmelCase ) def __magic_name__ ( ) -> List[str]: __lowerCamelCase = datasets.load_dataset('''eli5''' , name='''LFQA_reddit''' ) __lowerCamelCase = elia['''train_eli5'''] __lowerCamelCase = np.memmap( '''eli5_questions_reps.dat''' , dtype='''float32''' , mode='''r''' , shape=(elia_train.num_rows, 128) ) __lowerCamelCase = faiss.IndexFlatIP(128 ) eli5_train_q_index.add(__lowerCAmelCase ) return (elia_train, eli5_train_q_index) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = load_indexes() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = load_models() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = load_train_data() def __magic_name__ ( __lowerCAmelCase : Dict , __lowerCAmelCase : List[str]=10 ) -> List[str]: __lowerCamelCase = embed_questions_for_retrieval([question] , __lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase , __lowerCamelCase = eli5_train_q_index.search(__lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase = [elia_train[int(__lowerCAmelCase )] for i in I[0]] return nn_examples def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : Dict="wiki40b" , __lowerCAmelCase : Any="dense" , __lowerCAmelCase : Dict=10 ) -> Union[str, Any]: if source == "none": __lowerCamelCase , __lowerCamelCase = (''' <P> '''.join(['''''' for _ in range(11 )] ).strip(), []) else: if method == "dense": __lowerCamelCase , __lowerCamelCase = query_qa_dense_index( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) else: __lowerCamelCase , __lowerCamelCase = query_es_index( __lowerCAmelCase , __lowerCAmelCase , index_name='''english_wiki40b_snippets_100w''' , n_results=__lowerCAmelCase , ) __lowerCamelCase = [ (res['''article_title'''], res['''section_title'''].strip(), res['''score'''], res['''passage_text''']) for res in hit_lst ] __lowerCamelCase = '''question: {} context: {}'''.format(__lowerCAmelCase , __lowerCAmelCase ) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda __lowerCAmelCase : None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda __lowerCAmelCase : None), } ) def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : Dict , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : str=64 , __lowerCAmelCase : Dict=256 , __lowerCAmelCase : Union[str, Any]=False , __lowerCAmelCase : Optional[int]=2 , __lowerCAmelCase : Optional[Any]=0.95 , __lowerCAmelCase : List[Any]=0.8 ) -> Any: with torch.no_grad(): __lowerCamelCase = qa_sas_generate( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , num_answers=1 , num_beams=__lowerCAmelCase , min_len=__lowerCAmelCase , max_len=__lowerCAmelCase , do_sample=__lowerCAmelCase , temp=__lowerCAmelCase , top_p=__lowerCAmelCase , top_k=__lowerCAmelCase , max_input_length=1024 , device='''cuda:0''' , )[0] return (answer, support_list) st.title("Long Form Question Answering with ELI5") # Start sidebar SCREAMING_SNAKE_CASE__ : List[str] = "<img src='https://huggingface.co/front/assets/huggingface_logo.svg'>" SCREAMING_SNAKE_CASE__ : Dict = "\n<html>\n <head>\n <style>\n .img-container {\n padding-left: 90px;\n padding-right: 90px;\n padding-top: 50px;\n padding-bottom: 50px;\n background-color: #f0f3f9;\n }\n </style>\n </head>\n <body>\n <span class=\"img-container\"> <!-- Inline parent element -->\n %s\n </span>\n </body>\n</html>\n" % ( header_html, ) st.sidebar.markdown( header_full, unsafe_allow_html=True, ) # Long Form QA with ELI5 and Wikipedia SCREAMING_SNAKE_CASE__ : int = "\nThis demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).\nFirst, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,\na pre-processed fixed snapshot of Wikipedia.\n" st.sidebar.markdown(description, unsafe_allow_html=True) SCREAMING_SNAKE_CASE__ : str = [ "Answer the question", "View the retrieved document only", "View the most similar ELI5 question and answer", "Show me everything, please!", ] SCREAMING_SNAKE_CASE__ : Optional[int] = st.sidebar.checkbox("Demo options") if demo_options: SCREAMING_SNAKE_CASE__ : Optional[int] = st.sidebar.selectbox( "", action_list, index=3, ) SCREAMING_SNAKE_CASE__ : Optional[Any] = action_list.index(action_st) SCREAMING_SNAKE_CASE__ : int = st.sidebar.selectbox( "", ["Show full text of passages", "Show passage section titles"], index=0, ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = show_type == "Show full text of passages" else: SCREAMING_SNAKE_CASE__ : Any = 3 SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : Union[str, Any] = st.sidebar.checkbox("Retrieval options") if retrieval_options: SCREAMING_SNAKE_CASE__ : Tuple = "\n ### Information retriever options\n\n The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding\n trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.\n The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.\n " st.sidebar.markdown(retriever_info) SCREAMING_SNAKE_CASE__ : Union[str, Any] = st.sidebar.selectbox("Which Wikipedia format should the model use?", ["wiki40b", "none"]) SCREAMING_SNAKE_CASE__ : int = st.sidebar.selectbox("Which Wikipedia indexer should the model use?", ["dense", "sparse", "mixed"]) else: SCREAMING_SNAKE_CASE__ : List[str] = "wiki40b" SCREAMING_SNAKE_CASE__ : Optional[Any] = "dense" SCREAMING_SNAKE_CASE__ : str = "beam" SCREAMING_SNAKE_CASE__ : List[Any] = 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = 64 SCREAMING_SNAKE_CASE__ : List[Any] = 256 SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : List[str] = st.sidebar.checkbox("Generation options") if generate_options: SCREAMING_SNAKE_CASE__ : Dict = "\n ### Answer generation options\n\n The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)\n weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with\n **beam** search, or **sample** from the decoder's output probabilities.\n " st.sidebar.markdown(generate_info) SCREAMING_SNAKE_CASE__ : List[str] = st.sidebar.selectbox("Would you like to use beam search or sample an answer?", ["beam", "sampled"]) SCREAMING_SNAKE_CASE__ : Any = st.sidebar.slider( "Minimum generation length", min_value=8, max_value=256, value=64, step=8, format=None, key=None ) SCREAMING_SNAKE_CASE__ : str = st.sidebar.slider( "Maximum generation length", min_value=64, max_value=512, value=256, step=16, format=None, key=None ) if sampled == "beam": SCREAMING_SNAKE_CASE__ : Union[str, Any] = st.sidebar.slider("Beam size", min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: SCREAMING_SNAKE_CASE__ : Any = st.sidebar.slider( "Nucleus sampling p", min_value=0.1, max_value=1.0, value=0.9_5, step=0.0_1, format=None, key=None ) SCREAMING_SNAKE_CASE__ : Dict = st.sidebar.slider( "Temperature", min_value=0.1, max_value=1.0, value=0.7, step=0.0_1, format=None, key=None ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = None # start main text SCREAMING_SNAKE_CASE__ : Any = [ "<MY QUESTION>", "How do people make chocolate?", "Why do we get a fever when we are sick?", "How can different animals perceive different colors?", "What is natural language processing?", "What's the best way to treat a sunburn?", "What exactly are vitamins ?", "How does nuclear energy provide electricity?", "What's the difference between viruses and bacteria?", "Why are flutes classified as woodwinds when most of them are made out of metal ?", "Why do people like drinking coffee even though it tastes so bad?", "What happens when wine ages? How does it make the wine taste better?", "If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?", "How can we set a date to the beginning or end of an artistic period? Doesn't the change happen gradually?", "How does New Zealand have so many large bird predators?", ] SCREAMING_SNAKE_CASE__ : List[str] = st.selectbox( "What would you like to ask? ---- select <MY QUESTION> to enter a new query", questions_list, index=1, ) if question_s == "<MY QUESTION>": SCREAMING_SNAKE_CASE__ : Union[str, Any] = st.text_input("Enter your question here:", "") else: SCREAMING_SNAKE_CASE__ : str = question_s if st.button("Show me!"): if action in [0, 1, 3]: if index_type == "mixed": SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = make_support(question, source=wiki_source, method="dense", n_results=10) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = make_support(question, source=wiki_source, method="sparse", n_results=10) SCREAMING_SNAKE_CASE__ : int = [] for res_d, res_s in zip(support_list_dense, support_list_sparse): if tuple(res_d) not in support_list: support_list += [tuple(res_d)] if tuple(res_s) not in support_list: support_list += [tuple(res_s)] SCREAMING_SNAKE_CASE__ : Optional[Any] = support_list[:10] SCREAMING_SNAKE_CASE__ : Tuple = "<P> " + " <P> ".join([res[-1] for res in support_list]) else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = answer_question( question_doc, sas_model, sas_tokenizer, min_len=min_len, max_len=int(max_len), sampling=(sampled == "sampled"), n_beams=n_beams, top_p=top_p, temp=temp, ) st.markdown("### The model generated answer is:") st.write(answer) if action in [0, 1, 3] and wiki_source != "none": st.markdown("--- \n ### The model is drawing information from the following Wikipedia passages:") for i, res in enumerate(support_list): SCREAMING_SNAKE_CASE__ : Optional[int] = "https://en.wikipedia.org/wiki/{}".format(res[0].replace(" ", "_")) SCREAMING_SNAKE_CASE__ : Tuple = res[1].strip() if sec_titles == "": SCREAMING_SNAKE_CASE__ : Union[str, Any] = "[{}]({})".format(res[0], wiki_url) else: SCREAMING_SNAKE_CASE__ : Dict = sec_titles.split(" & ") SCREAMING_SNAKE_CASE__ : int = " & ".join( ["[{}]({}#{})".format(sec.strip(), wiki_url, sec.strip().replace(" ", "_")) for sec in sec_list] ) st.markdown( "{0:02d} - **Article**: {1:<18} <br> _Section_: {2}".format(i + 1, res[0], sections), unsafe_allow_html=True, ) if show_passages: st.write( "> <span style=\"font-family:arial; font-size:10pt;\">" + res[-1] + "</span>", unsafe_allow_html=True ) if action in [2, 3]: SCREAMING_SNAKE_CASE__ : Any = find_nearest_training(question) SCREAMING_SNAKE_CASE__ : List[Any] = nn_train_list[0] st.markdown( "--- \n ### The most similar question in the ELI5 training set was: \n\n {}".format(train_exple["title"]) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ "{}. {}".format(i + 1, " \n".join([line.strip() for line in ans.split("\n") if line.strip() != ""])) for i, (ans, sc) in enumerate(zip(train_exple["answers"]["text"], train_exple["answers"]["score"])) if i == 0 or sc > 2 ] st.markdown("##### Its answers were: \n\n {}".format("\n".join(answers_st))) SCREAMING_SNAKE_CASE__ : List[Any] = "\n---\n\n**Disclaimer**\n\n*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.\nEvaluating biases of such a model and ensuring factual generations are still very much open research problems.\nTherefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*\n" st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
339
0
import glob import os import random from string import ascii_lowercase, digits import cva SCREAMING_SNAKE_CASE__ : str = "" SCREAMING_SNAKE_CASE__ : Any = "" SCREAMING_SNAKE_CASE__ : Optional[Any] = "" SCREAMING_SNAKE_CASE__ : Optional[Any] = 1 # (0 is vertical, 1 is horizontal) def __magic_name__ ( ) -> None: __lowerCamelCase , __lowerCamelCase = get_dataset(__lowerCAmelCase , __lowerCAmelCase ) print('''Processing...''' ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = update_image_and_anno(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) for index, image in enumerate(__lowerCAmelCase ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' __lowerCamelCase = random_chars(32 ) __lowerCamelCase = paths[index].split(os.sep )[-1].rsplit('''.''' , 1 )[0] __lowerCamelCase = f'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(f'''/{file_root}.jpg''' , __lowerCAmelCase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(f'''Success {index+1}/{len(__lowerCAmelCase )} with {file_name}''' ) __lowerCamelCase = [] for anno in new_annos[index]: __lowerCamelCase = f'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(__lowerCAmelCase ) with open(f'''/{file_root}.txt''' , '''w''' ) as outfile: outfile.write('''\n'''.join(line for line in annos_list ) ) def __magic_name__ ( __lowerCAmelCase : str , __lowerCAmelCase : str ) -> tuple[list, list]: __lowerCamelCase = [] __lowerCamelCase = [] for label_file in glob.glob(os.path.join(__lowerCAmelCase , '''*.txt''' ) ): __lowerCamelCase = label_file.split(os.sep )[-1].rsplit('''.''' , 1 )[0] with open(__lowerCAmelCase ) as in_file: __lowerCamelCase = in_file.readlines() __lowerCamelCase = os.path.join(__lowerCAmelCase , f'''{label_name}.jpg''' ) __lowerCamelCase = [] for obj_list in obj_lists: __lowerCamelCase = obj_list.rstrip('''\n''' ).split(''' ''' ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(__lowerCAmelCase ) labels.append(__lowerCAmelCase ) return img_paths, labels def __magic_name__ ( __lowerCAmelCase : list , __lowerCAmelCase : list , __lowerCAmelCase : int = 1 ) -> tuple[list, list, list]: __lowerCamelCase = [] __lowerCamelCase = [] __lowerCamelCase = [] for idx in range(len(__lowerCAmelCase ) ): __lowerCamelCase = [] __lowerCamelCase = img_list[idx] path_list.append(__lowerCAmelCase ) __lowerCamelCase = anno_list[idx] __lowerCamelCase = cva.imread(__lowerCAmelCase ) if flip_type == 1: __lowerCamelCase = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: __lowerCamelCase = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: __lowerCamelCase = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: __lowerCamelCase = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(__lowerCAmelCase ) new_imgs_list.append(__lowerCAmelCase ) return new_imgs_list, new_annos_lists, path_list def __magic_name__ ( __lowerCAmelCase : int = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" __lowerCamelCase = ascii_lowercase + digits return "".join(random.choice(__lowerCAmelCase ) for _ in range(__lowerCAmelCase ) ) if __name__ == "__main__": main() print("DONE ✅")
353
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : List[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : str = { "facebook/xmod-base": "https://huggingface.co/facebook/xmod-base/resolve/main/config.json", "facebook/xmod-large-prenorm": "https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json", "facebook/xmod-base-13-125k": "https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json", "facebook/xmod-base-30-125k": "https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json", "facebook/xmod-base-30-195k": "https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json", "facebook/xmod-base-60-125k": "https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json", "facebook/xmod-base-60-265k": "https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json", "facebook/xmod-base-75-125k": "https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json", "facebook/xmod-base-75-269k": "https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json", } class lowerCAmelCase__ ( __lowercase ): a__ : Dict = """xmod""" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3_05_22 , SCREAMING_SNAKE_CASE__ : str=7_68 , SCREAMING_SNAKE_CASE__ : int=12 , SCREAMING_SNAKE_CASE__ : Dict=12 , SCREAMING_SNAKE_CASE__ : List[str]=30_72 , SCREAMING_SNAKE_CASE__ : List[Any]="gelu" , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : int=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=5_12 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=0.02 , SCREAMING_SNAKE_CASE__ : Optional[Any]=1e-12 , SCREAMING_SNAKE_CASE__ : List[str]=1 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0 , SCREAMING_SNAKE_CASE__ : int=2 , SCREAMING_SNAKE_CASE__ : Any="absolute" , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : Tuple=2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Dict=("en_XX",) , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , **SCREAMING_SNAKE_CASE__ : int , ) -> str: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = vocab_size __lowerCamelCase = hidden_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = hidden_act __lowerCamelCase = intermediate_size __lowerCamelCase = hidden_dropout_prob __lowerCamelCase = attention_probs_dropout_prob __lowerCamelCase = max_position_embeddings __lowerCamelCase = type_vocab_size __lowerCamelCase = initializer_range __lowerCamelCase = layer_norm_eps __lowerCamelCase = position_embedding_type __lowerCamelCase = use_cache __lowerCamelCase = classifier_dropout __lowerCamelCase = pre_norm __lowerCamelCase = adapter_reduction_factor __lowerCamelCase = adapter_layer_norm __lowerCamelCase = adapter_reuse_layer_norm __lowerCamelCase = ln_before_adapter __lowerCamelCase = list(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = default_language class lowerCAmelCase__ ( __lowercase ): @property def __A ( self : Optional[Any] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": __lowerCamelCase = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: __lowerCamelCase = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
339
0
import gc import unittest from diffusers import FlaxDPMSolverMultistepScheduler, FlaxStableDiffusionPipeline from diffusers.utils import is_flax_available, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : List[str] ) -> Optional[Any]: # clean up the VRAM after each test super().tearDown() gc.collect() def __A ( self : Tuple ) -> List[Any]: __lowerCamelCase , __lowerCamelCase = FlaxStableDiffusionPipeline.from_pretrained( '''stabilityai/stable-diffusion-2''' , revision='''bf16''' , dtype=jnp.bfloataa , ) __lowerCamelCase = '''A painting of a squirrel eating a burger''' __lowerCamelCase = jax.device_count() __lowerCamelCase = num_samples * [prompt] __lowerCamelCase = sd_pipe.prepare_inputs(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = replicate(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = shard(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = jax.random.PRNGKey(0 ) __lowerCamelCase = jax.random.split(SCREAMING_SNAKE_CASE__ , jax.device_count() ) __lowerCamelCase = sd_pipe(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , num_inference_steps=25 , jit=SCREAMING_SNAKE_CASE__ )[0] assert images.shape == (jax.device_count(), 1, 7_68, 7_68, 3) __lowerCamelCase = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) __lowerCamelCase = images[0, 2_53:2_56, 2_53:2_56, -1] __lowerCamelCase = jnp.asarray(jax.device_get(image_slice.flatten() ) ) __lowerCamelCase = jnp.array([0.4238, 0.4414, 0.4395, 0.4453, 0.4629, 0.4590, 0.4531, 0.45508, 0.4512] ) print(f'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2 def __A ( self : List[str] ) -> Tuple: __lowerCamelCase = '''stabilityai/stable-diffusion-2''' __lowerCamelCase , __lowerCamelCase = FlaxDPMSolverMultistepScheduler.from_pretrained(SCREAMING_SNAKE_CASE__ , subfolder='''scheduler''' ) __lowerCamelCase , __lowerCamelCase = FlaxStableDiffusionPipeline.from_pretrained( SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ , revision='''bf16''' , dtype=jnp.bfloataa , ) __lowerCamelCase = scheduler_params __lowerCamelCase = '''A painting of a squirrel eating a burger''' __lowerCamelCase = jax.device_count() __lowerCamelCase = num_samples * [prompt] __lowerCamelCase = sd_pipe.prepare_inputs(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = replicate(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = shard(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = jax.random.PRNGKey(0 ) __lowerCamelCase = jax.random.split(SCREAMING_SNAKE_CASE__ , jax.device_count() ) __lowerCamelCase = sd_pipe(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , num_inference_steps=25 , jit=SCREAMING_SNAKE_CASE__ )[0] assert images.shape == (jax.device_count(), 1, 7_68, 7_68, 3) __lowerCamelCase = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) __lowerCamelCase = images[0, 2_53:2_56, 2_53:2_56, -1] __lowerCamelCase = jnp.asarray(jax.device_get(image_slice.flatten() ) ) __lowerCamelCase = jnp.array([0.4336, 0.42969, 0.4453, 0.4199, 0.4297, 0.4531, 0.4434, 0.4434, 0.4297] ) print(f'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
354
from collections import namedtuple import requests from lxml import html # type: ignore SCREAMING_SNAKE_CASE__ : List[Any] = namedtuple("covid_data", "cases deaths recovered") def __magic_name__ ( __lowerCAmelCase : str = "https://www.worldometers.info/coronavirus/" ) -> covid_data: __lowerCamelCase = '''//div[@class = "maincounter-number"]/span/text()''' return covid_data(*html.fromstring(requests.get(__lowerCAmelCase ).content ).xpath(__lowerCAmelCase ) ) SCREAMING_SNAKE_CASE__ : List[str] = "Total COVID-19 cases in the world: {}\nTotal deaths due to COVID-19 in the world: {}\nTotal COVID-19 patients recovered in the world: {}" print(fmt.format(*covid_stats()))
339
0
def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int ) -> bool: return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
355
import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer, HfArgumentParser, MBartTokenizer, MBartTokenizerFast, set_seed, ) from transformers.trainer_utils import EvaluationStrategy, is_main_process from transformers.training_args import ParallelMode from utils import ( SeqaSeqDataCollator, SeqaSeqDataset, assert_all_frozen, build_compute_metrics_fn, check_output_dir, freeze_embeds, freeze_params, lmap, save_json, use_task_specific_params, write_txt_file, ) SCREAMING_SNAKE_CASE__ : int = logging.getLogger(__name__) @dataclass class lowerCAmelCase__ : a__ : str = field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} ) a__ : Optional[str] = field( default=__lowercase , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) a__ : Optional[str] = field( default=__lowercase , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} ) a__ : Optional[str] = field( default=__lowercase , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) a__ : bool = field(default=__lowercase , metadata={"""help""": """Whether tp freeze the encoder."""} ) a__ : bool = field(default=__lowercase , metadata={"""help""": """Whether to freeze the embeddings."""} ) @dataclass class lowerCAmelCase__ : a__ : str = field( metadata={"""help""": """The input data dir. Should contain the .tsv files (or other data files) for the task."""} ) a__ : Optional[str] = field( default="""summarization""" , metadata={"""help""": """Task name, summarization (or summarization_{dataset} for pegasus) or translation"""} , ) a__ : Optional[int] = field( default=1_024 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) a__ : Optional[int] = field( default=128 , metadata={ """help""": ( """The maximum total sequence length for target text after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) a__ : Optional[int] = field( default=142 , metadata={ """help""": ( """The maximum total sequence length for validation target text after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded. """ """This argument is also used to override the ``max_length`` param of ``model.generate``, which is used """ """during ``evaluate`` and ``predict``.""" ) } , ) a__ : Optional[int] = field( default=142 , metadata={ """help""": ( """The maximum total sequence length for test target text after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) a__ : Optional[int] = field(default=-1 , metadata={"""help""": """# training examples. -1 means use all."""} ) a__ : Optional[int] = field(default=-1 , metadata={"""help""": """# validation examples. -1 means use all."""} ) a__ : Optional[int] = field(default=-1 , metadata={"""help""": """# test examples. -1 means use all."""} ) a__ : Optional[str] = field(default=__lowercase , metadata={"""help""": """Source language id for translation."""} ) a__ : Optional[str] = field(default=__lowercase , metadata={"""help""": """Target language id for translation."""} ) a__ : Optional[int] = field(default=__lowercase , metadata={"""help""": """# num_beams to use for evaluation."""} ) a__ : bool = field( default=__lowercase , metadata={"""help""": """If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined."""} , ) def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : str , __lowerCAmelCase : int ) -> Dict: logger.info(f'''***** {split} metrics *****''' ) for key in sorted(metrics.keys() ): logger.info(f''' {key} = {metrics[key]}''' ) save_json(__lowerCAmelCase , os.path.join(__lowerCAmelCase , f'''{split}_results.json''' ) ) def __magic_name__ ( ) -> Optional[Any]: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. __lowerCamelCase = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) ) 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. __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = parser.parse_args_into_dataclasses() check_output_dir(__lowerCAmelCase ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info('''Training/evaluation parameters %s''' , __lowerCAmelCase ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __lowerCamelCase = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) __lowerCamelCase = ('''encoder_layerdrop''', '''decoder_layerdrop''', '''dropout''', '''attention_dropout''') for p in extra_model_params: if getattr(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): assert hasattr(__lowerCAmelCase , __lowerCAmelCase ), f'''({config.__class__.__name__}) doesn\'t have a `{p}` attribute''' setattr(__lowerCAmelCase , __lowerCAmelCase , getattr(__lowerCAmelCase , __lowerCAmelCase ) ) __lowerCamelCase = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) __lowerCamelCase = AutoModelForSeqaSeqLM.from_pretrained( model_args.model_name_or_path , from_tf='''.ckpt''' in model_args.model_name_or_path , config=__lowerCAmelCase , cache_dir=model_args.cache_dir , ) # use task specific params use_task_specific_params(__lowerCAmelCase , data_args.task ) # set num_beams for evaluation if data_args.eval_beams is None: __lowerCamelCase = model.config.num_beams # set decoder_start_token_id for MBart if model.config.decoder_start_token_id is None and isinstance(__lowerCAmelCase , (MBartTokenizer, MBartTokenizerFast) ): assert ( data_args.tgt_lang is not None and data_args.src_lang is not None ), "mBart requires --tgt_lang and --src_lang" if isinstance(__lowerCAmelCase , __lowerCAmelCase ): __lowerCamelCase = tokenizer.lang_code_to_id[data_args.tgt_lang] else: __lowerCamelCase = tokenizer.convert_tokens_to_ids(data_args.tgt_lang ) if model_args.freeze_embeds: freeze_embeds(__lowerCAmelCase ) if model_args.freeze_encoder: freeze_params(model.get_encoder() ) assert_all_frozen(model.get_encoder() ) __lowerCamelCase = SeqaSeqDataset # Get datasets __lowerCamelCase = ( dataset_class( __lowerCAmelCase , type_path='''train''' , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_train else None ) __lowerCamelCase = ( dataset_class( __lowerCAmelCase , type_path='''val''' , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO else None ) __lowerCamelCase = ( dataset_class( __lowerCAmelCase , type_path='''test''' , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_predict else None ) # Initialize our Trainer __lowerCamelCase = ( build_compute_metrics_fn(data_args.task , __lowerCAmelCase ) if training_args.predict_with_generate else None ) __lowerCamelCase = SeqaSeqTrainer( model=__lowerCAmelCase , args=__lowerCAmelCase , data_args=__lowerCAmelCase , train_dataset=__lowerCAmelCase , eval_dataset=__lowerCAmelCase , data_collator=SeqaSeqDataCollator( __lowerCAmelCase , __lowerCAmelCase , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=__lowerCAmelCase , tokenizer=__lowerCAmelCase , ) __lowerCamelCase = {} # Training if training_args.do_train: logger.info('''*** Train ***''' ) __lowerCamelCase = trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) __lowerCamelCase = train_result.metrics __lowerCamelCase = data_args.n_train trainer.save_model() # this also saves the tokenizer if trainer.is_world_process_zero(): handle_metrics('''train''' , __lowerCAmelCase , training_args.output_dir ) all_metrics.update(__lowerCAmelCase ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , '''trainer_state.json''' ) ) # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) tokenizer.save_pretrained(training_args.output_dir ) # Evaluation if training_args.do_eval: logger.info('''*** Evaluate ***''' ) __lowerCamelCase = trainer.evaluate(metric_key_prefix='''val''' ) __lowerCamelCase = data_args.n_val __lowerCamelCase = round(metrics['''val_loss'''] , 4 ) if trainer.is_world_process_zero(): handle_metrics('''val''' , __lowerCAmelCase , training_args.output_dir ) all_metrics.update(__lowerCAmelCase ) if training_args.do_predict: logger.info('''*** Predict ***''' ) __lowerCamelCase = trainer.predict(test_dataset=__lowerCAmelCase , metric_key_prefix='''test''' ) __lowerCamelCase = test_output.metrics __lowerCamelCase = data_args.n_test if trainer.is_world_process_zero(): __lowerCamelCase = round(metrics['''test_loss'''] , 4 ) handle_metrics('''test''' , __lowerCAmelCase , training_args.output_dir ) all_metrics.update(__lowerCAmelCase ) if training_args.predict_with_generate: __lowerCamelCase = tokenizer.batch_decode( test_output.predictions , skip_special_tokens=__lowerCAmelCase , clean_up_tokenization_spaces=__lowerCAmelCase ) __lowerCamelCase = lmap(str.strip , __lowerCAmelCase ) write_txt_file(__lowerCAmelCase , os.path.join(training_args.output_dir , '''test_generations.txt''' ) ) if trainer.is_world_process_zero(): save_json(__lowerCAmelCase , os.path.join(training_args.output_dir , '''all_results.json''' ) ) return all_metrics def __magic_name__ ( __lowerCAmelCase : List[str] ) -> Union[str, Any]: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
339
0
import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer, GPTaConfig, GPTaLMHeadModel, GPTaTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer, ) from utils import git_log, init_gpu_params, logger, set_seed SCREAMING_SNAKE_CASE__ : Dict = { "distilbert": (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer), "roberta": (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer), "bert": (BertConfig, BertForMaskedLM, BertTokenizer), "gpt2": (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer), } def __magic_name__ ( __lowerCAmelCase : Optional[int] ) -> List[Any]: assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0) assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0) if args.mlm: assert os.path.isfile(args.token_counts ) assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"]) else: assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"]) assert args.teacher_type == args.student_type or ( args.student_type == "distilbert" and args.teacher_type == "bert" ) assert os.path.isfile(args.student_config ) if args.student_pretrained_weights is not None: assert os.path.isfile(args.student_pretrained_weights ) if args.freeze_token_type_embds: assert args.student_type in ["roberta"] assert args.alpha_ce >= 0.0 assert args.alpha_mlm >= 0.0 assert args.alpha_clm >= 0.0 assert args.alpha_mse >= 0.0 assert args.alpha_cos >= 0.0 assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0 def __magic_name__ ( __lowerCAmelCase : Dict , __lowerCAmelCase : Optional[int] ) -> Optional[Any]: if args.student_type == "roberta": __lowerCamelCase = False elif args.student_type == "gpt2": __lowerCamelCase = False def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : str ) -> List[Any]: if args.student_type == "roberta": __lowerCamelCase = False def __magic_name__ ( ) -> int: __lowerCamelCase = argparse.ArgumentParser(description='''Training''' ) parser.add_argument('''--force''' , action='''store_true''' , help='''Overwrite dump_path if it already exists.''' ) parser.add_argument( '''--dump_path''' , type=__lowerCAmelCase , required=__lowerCAmelCase , help='''The output directory (log, checkpoints, parameters, etc.)''' ) parser.add_argument( '''--data_file''' , type=__lowerCAmelCase , required=__lowerCAmelCase , help='''The binarized file (tokenized + tokens_to_ids) and grouped by sequence.''' , ) parser.add_argument( '''--student_type''' , type=__lowerCAmelCase , choices=['''distilbert''', '''roberta''', '''gpt2'''] , required=__lowerCAmelCase , help='''The student type (DistilBERT, RoBERTa).''' , ) parser.add_argument('''--student_config''' , type=__lowerCAmelCase , required=__lowerCAmelCase , help='''Path to the student configuration.''' ) parser.add_argument( '''--student_pretrained_weights''' , default=__lowerCAmelCase , type=__lowerCAmelCase , help='''Load student initialization checkpoint.''' ) parser.add_argument( '''--teacher_type''' , choices=['''bert''', '''roberta''', '''gpt2'''] , required=__lowerCAmelCase , help='''Teacher type (BERT, RoBERTa).''' ) parser.add_argument('''--teacher_name''' , type=__lowerCAmelCase , required=__lowerCAmelCase , help='''The teacher model.''' ) parser.add_argument('''--temperature''' , default=2.0 , type=__lowerCAmelCase , help='''Temperature for the softmax temperature.''' ) parser.add_argument( '''--alpha_ce''' , default=0.5 , type=__lowerCAmelCase , help='''Linear weight for the distillation loss. Must be >=0.''' ) parser.add_argument( '''--alpha_mlm''' , default=0.0 , type=__lowerCAmelCase , help='''Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag.''' , ) parser.add_argument('''--alpha_clm''' , default=0.5 , type=__lowerCAmelCase , help='''Linear weight for the CLM loss. Must be >=0.''' ) parser.add_argument('''--alpha_mse''' , default=0.0 , type=__lowerCAmelCase , help='''Linear weight of the MSE loss. Must be >=0.''' ) parser.add_argument( '''--alpha_cos''' , default=0.0 , type=__lowerCAmelCase , help='''Linear weight of the cosine embedding loss. Must be >=0.''' ) parser.add_argument( '''--mlm''' , action='''store_true''' , help='''The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM.''' ) parser.add_argument( '''--mlm_mask_prop''' , default=0.15 , type=__lowerCAmelCase , help='''Proportion of tokens for which we need to make a prediction.''' , ) parser.add_argument('''--word_mask''' , default=0.8 , type=__lowerCAmelCase , help='''Proportion of tokens to mask out.''' ) parser.add_argument('''--word_keep''' , default=0.1 , type=__lowerCAmelCase , help='''Proportion of tokens to keep.''' ) parser.add_argument('''--word_rand''' , default=0.1 , type=__lowerCAmelCase , help='''Proportion of tokens to randomly replace.''' ) parser.add_argument( '''--mlm_smoothing''' , default=0.7 , type=__lowerCAmelCase , help='''Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec).''' , ) parser.add_argument('''--token_counts''' , type=__lowerCAmelCase , help='''The token counts in the data_file for MLM.''' ) parser.add_argument( '''--restrict_ce_to_mask''' , action='''store_true''' , help='''If true, compute the distillation loss only the [MLM] prediction distribution.''' , ) parser.add_argument( '''--freeze_pos_embs''' , action='''store_true''' , help='''Freeze positional embeddings during distillation. For student_type in [\'roberta\', \'gpt2\'] only.''' , ) parser.add_argument( '''--freeze_token_type_embds''' , action='''store_true''' , help='''Freeze token type embeddings during distillation if existent. For student_type in [\'roberta\'] only.''' , ) parser.add_argument('''--n_epoch''' , type=__lowerCAmelCase , default=3 , help='''Number of pass on the whole dataset.''' ) parser.add_argument('''--batch_size''' , type=__lowerCAmelCase , default=5 , help='''Batch size (for each process).''' ) parser.add_argument( '''--group_by_size''' , action='''store_false''' , help='''If true, group sequences that have similar length into the same batch. Default is true.''' , ) parser.add_argument( '''--gradient_accumulation_steps''' , type=__lowerCAmelCase , default=50 , help='''Gradient accumulation for larger training batches.''' , ) parser.add_argument('''--warmup_prop''' , default=0.05 , type=__lowerCAmelCase , help='''Linear warmup proportion.''' ) parser.add_argument('''--weight_decay''' , default=0.0 , type=__lowerCAmelCase , help='''Weight decay if we apply some.''' ) parser.add_argument('''--learning_rate''' , default=5E-4 , type=__lowerCAmelCase , help='''The initial learning rate for Adam.''' ) parser.add_argument('''--adam_epsilon''' , default=1E-6 , type=__lowerCAmelCase , help='''Epsilon for Adam optimizer.''' ) parser.add_argument('''--max_grad_norm''' , default=5.0 , type=__lowerCAmelCase , help='''Max gradient norm.''' ) parser.add_argument('''--initializer_range''' , default=0.02 , type=__lowerCAmelCase , help='''Random initialization range.''' ) parser.add_argument( '''--fp16''' , action='''store_true''' , help='''Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit''' , ) parser.add_argument( '''--fp16_opt_level''' , type=__lowerCAmelCase , default='''O1''' , help=( '''For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\'].''' '''See details at https://nvidia.github.io/apex/amp.html''' ) , ) parser.add_argument('''--n_gpu''' , type=__lowerCAmelCase , default=1 , help='''Number of GPUs in the node.''' ) parser.add_argument('''--local_rank''' , type=__lowerCAmelCase , default=-1 , help='''Distributed training - Local rank''' ) parser.add_argument('''--seed''' , type=__lowerCAmelCase , default=56 , help='''Random seed''' ) parser.add_argument('''--log_interval''' , type=__lowerCAmelCase , default=500 , help='''Tensorboard logging interval.''' ) parser.add_argument('''--checkpoint_interval''' , type=__lowerCAmelCase , default=4000 , help='''Checkpoint interval.''' ) __lowerCamelCase = parser.parse_args() sanity_checks(__lowerCAmelCase ) # ARGS # init_gpu_params(__lowerCAmelCase ) set_seed(__lowerCAmelCase ) if args.is_master: if os.path.exists(args.dump_path ): if not args.force: raise ValueError( f'''Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite''' ''' itUse `--force` if you want to overwrite it''' ) else: shutil.rmtree(args.dump_path ) if not os.path.exists(args.dump_path ): os.makedirs(args.dump_path ) logger.info(f'''Experiment will be dumped and logged in {args.dump_path}''' ) # SAVE PARAMS # logger.info(f'''Param: {args}''' ) with open(os.path.join(args.dump_path , '''parameters.json''' ) , '''w''' ) as f: json.dump(vars(__lowerCAmelCase ) , __lowerCAmelCase , indent=4 ) git_log(args.dump_path ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = MODEL_CLASSES[args.student_type] __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = MODEL_CLASSES[args.teacher_type] # TOKENIZER # __lowerCamelCase = teacher_tokenizer_class.from_pretrained(args.teacher_name ) __lowerCamelCase = {} for tok_name, tok_symbol in tokenizer.special_tokens_map.items(): __lowerCamelCase = tokenizer.all_special_tokens.index(__lowerCAmelCase ) __lowerCamelCase = tokenizer.all_special_ids[idx] logger.info(f'''Special tokens {special_tok_ids}''' ) __lowerCamelCase = special_tok_ids __lowerCamelCase = tokenizer.max_model_input_sizes[args.teacher_name] # DATA LOADER # logger.info(f'''Loading data from {args.data_file}''' ) with open(args.data_file , '''rb''' ) as fp: __lowerCamelCase = pickle.load(__lowerCAmelCase ) if args.mlm: logger.info(f'''Loading token counts from {args.token_counts} (already pre-computed)''' ) with open(args.token_counts , '''rb''' ) as fp: __lowerCamelCase = pickle.load(__lowerCAmelCase ) __lowerCamelCase = np.maximum(__lowerCAmelCase , 1 ) ** -args.mlm_smoothing for idx in special_tok_ids.values(): __lowerCamelCase = 0.0 # do not predict special tokens __lowerCamelCase = torch.from_numpy(__lowerCAmelCase ) else: __lowerCamelCase = None __lowerCamelCase = LmSeqsDataset(params=__lowerCAmelCase , data=__lowerCAmelCase ) logger.info('''Data loader created.''' ) # STUDENT # logger.info(f'''Loading student config from {args.student_config}''' ) __lowerCamelCase = student_config_class.from_pretrained(args.student_config ) __lowerCamelCase = True if args.student_pretrained_weights is not None: logger.info(f'''Loading pretrained weights from {args.student_pretrained_weights}''' ) __lowerCamelCase = student_model_class.from_pretrained(args.student_pretrained_weights , config=__lowerCAmelCase ) else: __lowerCamelCase = student_model_class(__lowerCAmelCase ) if args.n_gpu > 0: student.to(f'''cuda:{args.local_rank}''' ) logger.info('''Student loaded.''' ) # TEACHER # __lowerCamelCase = teacher_model_class.from_pretrained(args.teacher_name , output_hidden_states=__lowerCAmelCase ) if args.n_gpu > 0: teacher.to(f'''cuda:{args.local_rank}''' ) logger.info(f'''Teacher loaded from {args.teacher_name}.''' ) # FREEZING # if args.freeze_pos_embs: freeze_pos_embeddings(__lowerCAmelCase , __lowerCAmelCase ) if args.freeze_token_type_embds: freeze_token_type_embeddings(__lowerCAmelCase , __lowerCAmelCase ) # SANITY CHECKS # assert student.config.vocab_size == teacher.config.vocab_size assert student.config.hidden_size == teacher.config.hidden_size assert student.config.max_position_embeddings == teacher.config.max_position_embeddings if args.mlm: assert token_probs.size(0 ) == stu_architecture_config.vocab_size # DISTILLER # torch.cuda.empty_cache() __lowerCamelCase = Distiller( params=__lowerCAmelCase , dataset=__lowerCAmelCase , token_probs=__lowerCAmelCase , student=__lowerCAmelCase , teacher=__lowerCAmelCase ) distiller.train() logger.info('''Let\'s go get some drinks.''' ) if __name__ == "__main__": main()
356
import unittest import numpy as np import torch from diffusers import ScoreSdeVePipeline, ScoreSdeVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class lowerCAmelCase__ ( unittest.TestCase ): @property def __A ( self : List[Any] ) -> Optional[Any]: torch.manual_seed(0 ) __lowerCamelCase = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) return model def __A ( self : Optional[int] ) -> Optional[Any]: __lowerCamelCase = self.dummy_uncond_unet __lowerCamelCase = ScoreSdeVeScheduler() __lowerCamelCase = ScoreSdeVePipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) sde_ve.to(SCREAMING_SNAKE_CASE__ ) sde_ve.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = torch.manual_seed(0 ) __lowerCamelCase = sde_ve(num_inference_steps=2 , output_type='''numpy''' , generator=SCREAMING_SNAKE_CASE__ ).images __lowerCamelCase = torch.manual_seed(0 ) __lowerCamelCase = sde_ve(num_inference_steps=2 , output_type='''numpy''' , generator=SCREAMING_SNAKE_CASE__ , return_dict=SCREAMING_SNAKE_CASE__ )[ 0 ] __lowerCamelCase = image[0, -3:, -3:, -1] __lowerCamelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __lowerCamelCase = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Tuple ) -> str: __lowerCamelCase = '''google/ncsnpp-church-256''' __lowerCamelCase = UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = ScoreSdeVeScheduler.from_pretrained(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = ScoreSdeVePipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) sde_ve.to(SCREAMING_SNAKE_CASE__ ) sde_ve.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = torch.manual_seed(0 ) __lowerCamelCase = sde_ve(num_inference_steps=10 , output_type='''numpy''' , generator=SCREAMING_SNAKE_CASE__ ).images __lowerCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 2_56, 2_56, 3) __lowerCamelCase = np.array([0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
339
0
# 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 SCREAMING_SNAKE_CASE__ : Union[str, Any] = subprocess.check_output("git merge-base main HEAD".split()).decode("utf-8") SCREAMING_SNAKE_CASE__ : Dict = subprocess.check_output(F'git diff --name-only {fork_point_sha}'.split()).decode("utf-8").split() SCREAMING_SNAKE_CASE__ : Optional[int] = "|".join(sys.argv[1:]) SCREAMING_SNAKE_CASE__ : List[str] = re.compile(rF'^({joined_dirs}).*?\.py$') SCREAMING_SNAKE_CASE__ : Optional[int] = [x for x in modified_files if regex.match(x)] print(" ".join(relevant_modified_files), end="")
357
from functools import lru_cache def __magic_name__ ( __lowerCAmelCase : int ) -> set: __lowerCamelCase = 2 __lowerCamelCase = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(__lowerCAmelCase ) if n > 1: factors.add(__lowerCAmelCase ) return factors @lru_cache def __magic_name__ ( __lowerCAmelCase : int ) -> int: return len(unique_prime_factors(__lowerCAmelCase ) ) def __magic_name__ ( __lowerCAmelCase : list ) -> bool: return len(set(__lowerCAmelCase ) ) in (0, 1) def __magic_name__ ( __lowerCAmelCase : int ) -> list: __lowerCamelCase = 2 while True: # Increment each value of a generated range __lowerCamelCase = [base + i for i in range(__lowerCAmelCase )] # Run elements through out unique_prime_factors function # Append our target number to the end. __lowerCamelCase = [upf_len(__lowerCAmelCase ) for x in group] checker.append(__lowerCAmelCase ) # If all numbers in the list are equal, return the group variable. if equality(__lowerCAmelCase ): return group # Increment our base variable by 1 base += 1 def __magic_name__ ( __lowerCAmelCase : int = 4 ) -> int: __lowerCamelCase = run(__lowerCAmelCase ) return results[0] if len(__lowerCAmelCase ) else None if __name__ == "__main__": print(solution())
339
0
import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Dict ) -> List[Any]: __lowerCamelCase = '''ylacombe/bark-small''' __lowerCamelCase = tempfile.mkdtemp() __lowerCamelCase = '''en_speaker_1''' __lowerCamelCase = '''This is a test string''' __lowerCamelCase = '''speaker_embeddings_path.json''' __lowerCamelCase = '''speaker_embeddings''' def __A ( self : Optional[int] , **SCREAMING_SNAKE_CASE__ : Tuple ) -> str: return AutoTokenizer.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE__ ) def __A ( self : str ) -> int: shutil.rmtree(self.tmpdirname ) def __A ( self : Optional[Any] ) -> Optional[int]: __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = BarkProcessor(tokenizer=SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) __lowerCamelCase = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def __A ( self : Union[str, Any] ) -> Tuple: __lowerCamelCase = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) __lowerCamelCase = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __lowerCamelCase = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token='''(BOS)''' , eos_token='''(EOS)''' , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def __A ( self : Union[str, Any] ) -> Tuple: __lowerCamelCase = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) __lowerCamelCase = 35 __lowerCamelCase = 2 __lowerCamelCase = 8 __lowerCamelCase = { '''semantic_prompt''': np.ones(SCREAMING_SNAKE_CASE__ ), '''coarse_prompt''': np.ones((nb_codebooks_coarse, seq_len) ), '''fine_prompt''': np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset __lowerCamelCase = processor(text=self.input_string , voice_preset=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = inputs['''history_prompt'''] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(SCREAMING_SNAKE_CASE__ , np.array([] ) ).tolist() ) # test loading voice preset from npz file __lowerCamelCase = os.path.join(self.tmpdirname , '''file.npz''' ) np.savez(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = processor(text=self.input_string , voice_preset=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = inputs['''history_prompt'''] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(SCREAMING_SNAKE_CASE__ , np.array([] ) ).tolist() ) # test loading voice preset from the hub __lowerCamelCase = processor(text=self.input_string , voice_preset=self.voice_preset ) def __A ( self : Union[str, Any] ) -> List[str]: __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = BarkProcessor(tokenizer=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = processor(text=self.input_string ) __lowerCamelCase = tokenizer( self.input_string , padding='''max_length''' , max_length=2_56 , add_special_tokens=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , return_token_type_ids=SCREAMING_SNAKE_CASE__ , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
358
import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel class lowerCAmelCase__ : def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any]=99 , SCREAMING_SNAKE_CASE__ : List[Any]=13 , SCREAMING_SNAKE_CASE__ : Tuple=7 , SCREAMING_SNAKE_CASE__ : int=9 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Dict=False , SCREAMING_SNAKE_CASE__ : int=32 , SCREAMING_SNAKE_CASE__ : Tuple=5 , SCREAMING_SNAKE_CASE__ : List[str]=4 , SCREAMING_SNAKE_CASE__ : str=37 , SCREAMING_SNAKE_CASE__ : int=8 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.002 , SCREAMING_SNAKE_CASE__ : str=1 , SCREAMING_SNAKE_CASE__ : Tuple=0 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0 , SCREAMING_SNAKE_CASE__ : int=None , SCREAMING_SNAKE_CASE__ : Dict=None , ) -> Optional[Any]: __lowerCamelCase = parent __lowerCamelCase = batch_size __lowerCamelCase = encoder_seq_length __lowerCamelCase = decoder_seq_length # For common tests __lowerCamelCase = self.decoder_seq_length __lowerCamelCase = is_training __lowerCamelCase = use_attention_mask __lowerCamelCase = use_labels __lowerCamelCase = vocab_size __lowerCamelCase = hidden_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = d_ff __lowerCamelCase = relative_attention_num_buckets __lowerCamelCase = dropout_rate __lowerCamelCase = initializer_factor __lowerCamelCase = eos_token_id __lowerCamelCase = pad_token_id __lowerCamelCase = decoder_start_token_id __lowerCamelCase = None __lowerCamelCase = decoder_layers def __A ( self : Any ) -> Tuple: return TaConfig.from_pretrained('''google/umt5-base''' ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , ) -> Optional[int]: if attention_mask is None: __lowerCamelCase = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: __lowerCamelCase = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: __lowerCamelCase = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=SCREAMING_SNAKE_CASE__ ) if decoder_head_mask is None: __lowerCamelCase = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=SCREAMING_SNAKE_CASE__ ) if cross_attn_head_mask is None: __lowerCamelCase = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=SCREAMING_SNAKE_CASE__ ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } def __A ( self : List[Any] ) -> Tuple: __lowerCamelCase = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) __lowerCamelCase = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for NllbMoe the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input __lowerCamelCase = input_ids.clamp(self.pad_token_id + 1 ) __lowerCamelCase = decoder_input_ids.clamp(self.pad_token_id + 1 ) __lowerCamelCase = self.get_config() __lowerCamelCase = config.num_attention_heads __lowerCamelCase = self.prepare_inputs_dict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return config, input_dict def __A ( self : Tuple ) -> List[str]: __lowerCamelCase , __lowerCamelCase = self.prepare_config_and_inputs() return config, inputs_dict def __A ( self : Optional[Any] ) -> Any: return TaConfig( vocab_size=1_66 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def __A ( self : List[Any] ) -> Any: return TaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> int: __lowerCamelCase = UMTaModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __lowerCamelCase = model( input_ids=SCREAMING_SNAKE_CASE__ , decoder_input_ids=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , decoder_attention_mask=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = model(input_ids=SCREAMING_SNAKE_CASE__ , decoder_input_ids=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = result.last_hidden_state __lowerCamelCase = result.past_key_values __lowerCamelCase = result.encoder_last_hidden_state self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) ) self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) ) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , config.num_layers ) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0] ) , 4 ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple , ) -> Dict: __lowerCamelCase = UMTaModel(config=SCREAMING_SNAKE_CASE__ ).get_decoder().to(SCREAMING_SNAKE_CASE__ ).eval() # first forward pass __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ , use_cache=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ , use_cache=SCREAMING_SNAKE_CASE__ ) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE__ ) == len(SCREAMING_SNAKE_CASE__ ) ) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE__ ) == len(SCREAMING_SNAKE_CASE__ ) + 1 ) __lowerCamelCase , __lowerCamelCase = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids __lowerCamelCase = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and __lowerCamelCase = torch.cat([input_ids, next_tokens] , dim=-1 ) __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ )['''last_hidden_state'''] __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ , past_key_values=SCREAMING_SNAKE_CASE__ )['''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(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple , ) -> Optional[int]: __lowerCamelCase = UMTaModel(config=SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ ).half().eval() __lowerCamelCase = model(**SCREAMING_SNAKE_CASE__ )['''last_hidden_state'''] self.parent.assertFalse(torch.isnan(SCREAMING_SNAKE_CASE__ ).any().item() ) @require_torch class lowerCAmelCase__ ( __lowercase , __lowercase , __lowercase , unittest.TestCase ): a__ : List[Any] = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) a__ : Union[str, Any] = (UMTaForConditionalGeneration,) if is_torch_available() else () a__ : Tuple = ( { """conversational""": UMTaForConditionalGeneration, """feature-extraction""": UMTaModel, """summarization""": UMTaForConditionalGeneration, """text2text-generation""": UMTaForConditionalGeneration, """translation""": UMTaForConditionalGeneration, """question-answering""": UMTaForQuestionAnswering, } if is_torch_available() else {} ) a__ : int = True a__ : int = False a__ : Tuple = False a__ : Optional[int] = True a__ : Optional[int] = True # The small UMT5 model needs higher percentages for CPU/MP tests a__ : Tuple = [0.8, 0.9] def __A ( self : Tuple ) -> Tuple: __lowerCamelCase = UMTaModelTester(self ) @unittest.skip('''Test has a segmentation fault on torch 1.8.0''' ) def __A ( self : List[str] ) -> Union[str, Any]: __lowerCamelCase = self.model_tester.prepare_config_and_inputs() __lowerCamelCase = UMTaModel(config_and_inputs[0] ).to(SCREAMING_SNAKE_CASE__ ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( SCREAMING_SNAKE_CASE__ , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , f'''{tmpdirname}/t5_test.onnx''' , export_params=SCREAMING_SNAKE_CASE__ , opset_version=9 , input_names=['''input_ids''', '''decoder_input_ids'''] , ) @unittest.skipIf(torch_device == '''cpu''' , '''Cant do half precision''' ) def __A ( self : Union[str, Any] ) -> Any: __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*SCREAMING_SNAKE_CASE__ ) def __A ( self : Any ) -> Any: __lowerCamelCase = ['''encoder_attentions''', '''decoder_attentions''', '''cross_attentions'''] __lowerCamelCase = self.model_tester.prepare_config_and_inputs() __lowerCamelCase = config_and_inputs[0] __lowerCamelCase = UMTaForConditionalGeneration(SCREAMING_SNAKE_CASE__ ).eval() model.to(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = { '''head_mask''': torch.zeros(config.num_layers , config.num_heads , device=SCREAMING_SNAKE_CASE__ ), '''decoder_head_mask''': torch.zeros(config.num_decoder_layers , config.num_heads , device=SCREAMING_SNAKE_CASE__ ), '''cross_attn_head_mask''': torch.zeros(config.num_decoder_layers , config.num_heads , device=SCREAMING_SNAKE_CASE__ ), } for attn_name, (name, mask) in zip(SCREAMING_SNAKE_CASE__ , head_masking.items() ): __lowerCamelCase = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": __lowerCamelCase = torch.ones( config.num_decoder_layers , config.num_heads , device=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model.generate( config_and_inputs[1]['''input_ids'''] , num_beams=1 , max_length=3 , output_attentions=SCREAMING_SNAKE_CASE__ , return_dict_in_generate=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) # We check the state of decoder_attentions and cross_attentions just from the last step __lowerCamelCase = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 ) @unittest.skip('''Does not work on the tiny model as we keep hitting edge cases.''' ) def __A ( self : Tuple ) -> Optional[Any]: pass @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): @slow @unittest.skip( '''Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged''' ) def __A ( self : int ) -> Optional[Any]: __lowerCamelCase = UMTaForConditionalGeneration.from_pretrained('''google/umt5-small''' , return_dict=SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = AutoTokenizer.from_pretrained('''google/umt5-small''' , use_fast=SCREAMING_SNAKE_CASE__ , legacy=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = [ '''Bonjour monsieur <extra_id_0> bien <extra_id_1>.''', '''No se como puedo <extra_id_0>.''', '''This is the reason why we <extra_id_0> them.''', '''The <extra_id_0> walks in <extra_id_1>, seats''', '''A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.''', ] __lowerCamelCase = tokenizer(SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , padding=SCREAMING_SNAKE_CASE__ ).input_ids # fmt: off __lowerCamelCase = torch.tensor( [ [ 3_85_30, 21_07_03, 25_62_99, 14_10, 25_62_98, 2_74, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 8_26, 3_21, 6_71, 2_59_22, 25_62_99, 2_74, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 14_60, 3_39, 3_12, 1_90_14, 1_06_20, 7_58, 25_62_99, 23_55,2_74, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 5_17, 25_62_99, 1_48_69, 2_81, 3_01, 25_62_98, 2_75, 11_99_83,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 3_20, 25_62_99, 1_48_69, 2_81, 22_34, 2_89, 22_75, 3_33,6_13_91, 2_89, 25_62_98, 5_43, 25_62_97, 16_87_14, 3_29, 25_62_96,2_74, 1], ] ) # fmt: on torch.testing.assert_allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model.generate(input_ids.to(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = [ '''<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>''', '''<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', ] __lowerCamelCase = tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
339
0
import doctest import glob import importlib import inspect import os import re from contextlib import contextmanager from functools import wraps from unittest.mock import patch import numpy as np import pytest from absl.testing import parameterized import datasets from datasets import load_metric from .utils import for_all_test_methods, local, slow # mark all tests as integration SCREAMING_SNAKE_CASE__ : List[Any] = pytest.mark.integration SCREAMING_SNAKE_CASE__ : Dict = {"comet"} SCREAMING_SNAKE_CASE__ : Union[str, Any] = importlib.util.find_spec("fairseq") is not None SCREAMING_SNAKE_CASE__ : Optional[Any] = {"code_eval"} SCREAMING_SNAKE_CASE__ : str = os.name == "nt" SCREAMING_SNAKE_CASE__ : Optional[int] = {"bertscore", "frugalscore", "perplexity"} SCREAMING_SNAKE_CASE__ : Tuple = importlib.util.find_spec("transformers") is not None def __magic_name__ ( __lowerCAmelCase : Union[str, Any] ) -> Optional[int]: @wraps(__lowerCAmelCase ) def wrapper(self : Tuple , __lowerCAmelCase : int ): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest('''"test requires Fairseq"''' ) else: test_case(self , __lowerCAmelCase ) return wrapper def __magic_name__ ( __lowerCAmelCase : Dict ) -> List[Any]: @wraps(__lowerCAmelCase ) def wrapper(self : Tuple , __lowerCAmelCase : Tuple ): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest('''"test requires transformers"''' ) else: test_case(self , __lowerCAmelCase ) return wrapper def __magic_name__ ( __lowerCAmelCase : Union[str, Any] ) -> Union[str, Any]: @wraps(__lowerCAmelCase ) def wrapper(self : Optional[int] , __lowerCAmelCase : Any ): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest('''"test not supported on Windows"''' ) else: test_case(self , __lowerCAmelCase ) return wrapper def __magic_name__ ( ) -> str: __lowerCamelCase = [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob('''./metrics/*/''' )] return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished @parameterized.named_parameters(get_local_metric_names() ) @for_all_test_methods( __lowercase , __lowercase , __lowercase ) @local class lowerCAmelCase__ ( parameterized.TestCase ): a__ : str = {} a__ : str = None @pytest.mark.filterwarnings('''ignore:metric_module_factory is deprecated:FutureWarning''' ) @pytest.mark.filterwarnings('''ignore:load_metric is deprecated:FutureWarning''' ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : str ) -> Tuple: __lowerCamelCase = '''[...]''' __lowerCamelCase = importlib.import_module( datasets.load.metric_module_factory(os.path.join('''metrics''' , SCREAMING_SNAKE_CASE__ ) ).module_path ) __lowerCamelCase = datasets.load.import_main_class(metric_module.__name__ , dataset=SCREAMING_SNAKE_CASE__ ) # check parameters __lowerCamelCase = inspect.signature(metric._compute ).parameters self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values() ) ) # no **kwargs # run doctest with self.patch_intensive_calls(SCREAMING_SNAKE_CASE__ , metric_module.__name__ ): with self.use_local_metrics(): try: __lowerCamelCase = doctest.testmod(SCREAMING_SNAKE_CASE__ , verbose=SCREAMING_SNAKE_CASE__ , raise_on_error=SCREAMING_SNAKE_CASE__ ) except doctest.UnexpectedException as e: raise e.exc_info[1] # raise the exception that doctest caught self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @slow def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : int ) -> Optional[Any]: __lowerCamelCase = '''[...]''' __lowerCamelCase = importlib.import_module( datasets.load.metric_module_factory(os.path.join('''metrics''' , SCREAMING_SNAKE_CASE__ ) ).module_path ) # run doctest with self.use_local_metrics(): __lowerCamelCase = doctest.testmod(SCREAMING_SNAKE_CASE__ , verbose=SCREAMING_SNAKE_CASE__ , raise_on_error=SCREAMING_SNAKE_CASE__ ) self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @contextmanager def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Any ) -> str: if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](SCREAMING_SNAKE_CASE__ ): yield else: yield @contextmanager def __A ( self : Optional[Any] ) -> Optional[Any]: def load_local_metric(SCREAMING_SNAKE_CASE__ : Union[str, Any] , *SCREAMING_SNAKE_CASE__ : Dict , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ): return load_metric(os.path.join('''metrics''' , SCREAMING_SNAKE_CASE__ ) , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) with patch('''datasets.load_metric''' ) as mock_load_metric: __lowerCamelCase = load_local_metric yield @classmethod def __A ( cls : Dict , SCREAMING_SNAKE_CASE__ : Dict ) -> Tuple: def wrapper(SCREAMING_SNAKE_CASE__ : List[Any] ): __lowerCamelCase = contextmanager(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher('''bleurt''' ) def __magic_name__ ( __lowerCAmelCase : int ) -> Optional[Any]: import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string('''sv''' , '''''' , '''''' ) # handle pytest cli flags class lowerCAmelCase__ ( __lowercase ): def __A ( self : int , SCREAMING_SNAKE_CASE__ : Tuple ) -> List[Any]: assert len(input_dict['''input_ids'''] ) == 2 return np.array([1.03, 1.04] ) # mock predict_fn which is supposed to do a forward pass with a bleurt model with patch('''bleurt.score._create_predictor''' ) as mock_create_predictor: __lowerCamelCase = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher('''bertscore''' ) def __magic_name__ ( __lowerCAmelCase : List[str] ) -> List[str]: import torch def bert_cos_score_idf(__lowerCAmelCase : Dict , __lowerCAmelCase : int , *__lowerCAmelCase : List[str] , **__lowerCAmelCase : Optional[int] ): return torch.tensor([[1.0, 1.0, 1.0]] * len(__lowerCAmelCase ) ) # mock get_model which is supposed to do download a bert model # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model with patch('''bert_score.scorer.get_model''' ), patch( '''bert_score.scorer.bert_cos_score_idf''' ) as mock_bert_cos_score_idf: __lowerCamelCase = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher('''comet''' ) def __magic_name__ ( __lowerCAmelCase : List[Any] ) -> Optional[Any]: def load_from_checkpoint(__lowerCAmelCase : Optional[int] ): class lowerCAmelCase__ : def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : int , *SCREAMING_SNAKE_CASE__ : Dict , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> Tuple: assert len(SCREAMING_SNAKE_CASE__ ) == 2 __lowerCamelCase = [0.19, 0.92] return scores, sum(SCREAMING_SNAKE_CASE__ ) / len(SCREAMING_SNAKE_CASE__ ) return Model() # mock load_from_checkpoint which is supposed to do download a bert model # mock load_from_checkpoint which is supposed to do download a bert model with patch('''comet.download_model''' ) as mock_download_model: __lowerCamelCase = None with patch('''comet.load_from_checkpoint''' ) as mock_load_from_checkpoint: __lowerCamelCase = load_from_checkpoint yield def __magic_name__ ( ) -> Union[str, Any]: __lowerCamelCase = load_metric(os.path.join('''metrics''' , '''seqeval''' ) ) __lowerCamelCase = '''ERROR''' __lowerCamelCase = f'''Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}''' with pytest.raises(__lowerCAmelCase , match=re.escape(__lowerCAmelCase ) ): metric.compute(predictions=[] , references=[] , scheme=__lowerCAmelCase )
359
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : Union[str, Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Tuple = { "s-JoL/Open-Llama-V1": "https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/config.json", } class lowerCAmelCase__ ( __lowercase ): a__ : Union[str, Any] = """open-llama""" def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Any=10_00_00 , SCREAMING_SNAKE_CASE__ : Any=40_96 , SCREAMING_SNAKE_CASE__ : Any=1_10_08 , SCREAMING_SNAKE_CASE__ : Tuple=32 , SCREAMING_SNAKE_CASE__ : str=32 , SCREAMING_SNAKE_CASE__ : Any="silu" , SCREAMING_SNAKE_CASE__ : Union[str, Any]=20_48 , SCREAMING_SNAKE_CASE__ : List[str]=0.02 , SCREAMING_SNAKE_CASE__ : List[Any]=1e-6 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Dict=0 , SCREAMING_SNAKE_CASE__ : Tuple=1 , SCREAMING_SNAKE_CASE__ : str=2 , SCREAMING_SNAKE_CASE__ : List[Any]=False , SCREAMING_SNAKE_CASE__ : Any=True , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Any=0.1 , SCREAMING_SNAKE_CASE__ : Any=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : List[str]=None , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> Dict: __lowerCamelCase = vocab_size __lowerCamelCase = max_position_embeddings __lowerCamelCase = hidden_size __lowerCamelCase = intermediate_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = hidden_act __lowerCamelCase = initializer_range __lowerCamelCase = rms_norm_eps __lowerCamelCase = use_cache __lowerCamelCase = kwargs.pop( '''use_memorry_efficient_attention''' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = hidden_dropout_prob __lowerCamelCase = attention_dropout_prob __lowerCamelCase = use_stable_embedding __lowerCamelCase = shared_input_output_embedding __lowerCamelCase = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , tie_word_embeddings=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) def __A ( self : Dict ) -> Optional[int]: if self.rope_scaling is None: return if not isinstance(self.rope_scaling , SCREAMING_SNAKE_CASE__ ) or len(self.rope_scaling ) != 2: raise ValueError( '''`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ''' f'''got {self.rope_scaling}''' ) __lowerCamelCase = self.rope_scaling.get('''type''' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.rope_scaling.get('''factor''' , SCREAMING_SNAKE_CASE__ ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' ) if rope_scaling_factor is None or not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or rope_scaling_factor <= 1.0: raise ValueError(f'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
339
0
# This code is adapted from OpenAI's release # https://github.com/openai/human-eval/blob/master/human_eval/execution.py import contextlib import faulthandler import io import multiprocessing import os import platform import signal import tempfile def __magic_name__ ( __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Tuple , __lowerCAmelCase : List[str] ) -> List[Any]: __lowerCamelCase = multiprocessing.Manager() __lowerCamelCase = manager.list() __lowerCamelCase = multiprocessing.Process(target=__lowerCAmelCase , args=(check_program, result, timeout) ) p.start() p.join(timeout=timeout + 1 ) if p.is_alive(): p.kill() if not result: result.append('''timed out''' ) return { "task_id": task_id, "passed": result[0] == "passed", "result": result[0], "completion_id": completion_id, } def __magic_name__ ( __lowerCAmelCase : Dict , __lowerCAmelCase : int , __lowerCAmelCase : List[str] ) -> Dict: with create_tempdir(): # These system calls are needed when cleaning up tempdir. import os import shutil __lowerCamelCase = shutil.rmtree __lowerCamelCase = os.rmdir __lowerCamelCase = os.chdir # Disable functionalities that can make destructive changes to the test. reliability_guard() # Run program. try: __lowerCamelCase = {} with swallow_io(): with time_limit(__lowerCAmelCase ): exec(__lowerCAmelCase , __lowerCAmelCase ) result.append('''passed''' ) except TimeoutException: result.append('''timed out''' ) except BaseException as e: result.append(f'''failed: {e}''' ) # Needed for cleaning up. __lowerCamelCase = rmtree __lowerCamelCase = rmdir __lowerCamelCase = chdir @contextlib.contextmanager def __magic_name__ ( __lowerCAmelCase : Any ) -> str: def signal_handler(__lowerCAmelCase : Tuple , __lowerCAmelCase : List[Any] ): raise TimeoutException('''Timed out!''' ) signal.setitimer(signal.ITIMER_REAL , __lowerCAmelCase ) signal.signal(signal.SIGALRM , __lowerCAmelCase ) try: yield finally: signal.setitimer(signal.ITIMER_REAL , 0 ) @contextlib.contextmanager def __magic_name__ ( ) -> List[str]: __lowerCamelCase = WriteOnlyStringIO() with contextlib.redirect_stdout(__lowerCAmelCase ): with contextlib.redirect_stderr(__lowerCAmelCase ): with redirect_stdin(__lowerCAmelCase ): yield @contextlib.contextmanager def __magic_name__ ( ) -> Tuple: with tempfile.TemporaryDirectory() as dirname: with chdir(__lowerCAmelCase ): yield dirname class lowerCAmelCase__ ( __lowercase ): pass class lowerCAmelCase__ ( io.StringIO ): def __A ( self : List[str] , *SCREAMING_SNAKE_CASE__ : Optional[Any] , **SCREAMING_SNAKE_CASE__ : Any ) -> Optional[Any]: raise OSError def __A ( self : List[Any] , *SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> int: raise OSError def __A ( self : Optional[int] , *SCREAMING_SNAKE_CASE__ : Any , **SCREAMING_SNAKE_CASE__ : str ) -> str: raise OSError def __A ( self : Optional[int] , *SCREAMING_SNAKE_CASE__ : Any , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> List[str]: return False class lowerCAmelCase__ ( contextlib._RedirectStream ): # type: ignore a__ : Dict = """stdin""" @contextlib.contextmanager def __magic_name__ ( __lowerCAmelCase : List[str] ) -> List[Any]: if root == ".": yield return __lowerCamelCase = os.getcwd() os.chdir(__lowerCAmelCase ) try: yield except BaseException as exc: raise exc finally: os.chdir(__lowerCAmelCase ) def __magic_name__ ( __lowerCAmelCase : Optional[int]=None ) -> str: if maximum_memory_bytes is not None: import resource resource.setrlimit(resource.RLIMIT_AS , (maximum_memory_bytes, maximum_memory_bytes) ) resource.setrlimit(resource.RLIMIT_DATA , (maximum_memory_bytes, maximum_memory_bytes) ) if not platform.uname().system == "Darwin": resource.setrlimit(resource.RLIMIT_STACK , (maximum_memory_bytes, maximum_memory_bytes) ) faulthandler.disable() import builtins __lowerCamelCase = None __lowerCamelCase = None import os __lowerCamelCase = '''1''' __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None import shutil __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None import subprocess __lowerCamelCase = None # type: ignore __lowerCamelCase = None import sys __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None
360
from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar SCREAMING_SNAKE_CASE__ : Any = TypeVar("KEY") SCREAMING_SNAKE_CASE__ : Dict = TypeVar("VAL") @dataclass(frozen=__lowercase , slots=__lowercase ) class lowerCAmelCase__ ( Generic[KEY, VAL] ): a__ : KEY a__ : VAL class lowerCAmelCase__ ( _Item ): def __init__( self : str ) -> None: super().__init__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __bool__( self : Tuple ) -> bool: return False SCREAMING_SNAKE_CASE__ : List[Any] = _DeletedItem() class lowerCAmelCase__ ( MutableMapping[KEY, VAL] ): def __init__( self : int , SCREAMING_SNAKE_CASE__ : int = 8 , SCREAMING_SNAKE_CASE__ : float = 0.75 ) -> None: __lowerCamelCase = initial_block_size __lowerCamelCase = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 __lowerCamelCase = capacity_factor __lowerCamelCase = 0 def __A ( self : Any , SCREAMING_SNAKE_CASE__ : KEY ) -> int: return hash(SCREAMING_SNAKE_CASE__ ) % len(self._buckets ) def __A ( self : Any , SCREAMING_SNAKE_CASE__ : int ) -> int: return (ind + 1) % len(self._buckets ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : KEY , SCREAMING_SNAKE_CASE__ : VAL ) -> bool: __lowerCamelCase = self._buckets[ind] if not stored: __lowerCamelCase = _Item(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self._len += 1 return True elif stored.key == key: __lowerCamelCase = _Item(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return True else: return False def __A ( self : Any ) -> bool: __lowerCamelCase = len(self._buckets ) * self._capacity_factor return len(self ) >= int(SCREAMING_SNAKE_CASE__ ) def __A ( self : List[Any] ) -> bool: if len(self._buckets ) <= self._initial_block_size: return False __lowerCamelCase = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def __A ( self : int , SCREAMING_SNAKE_CASE__ : int ) -> None: __lowerCamelCase = self._buckets __lowerCamelCase = [None] * new_size __lowerCamelCase = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def __A ( self : str ) -> None: self._resize(len(self._buckets ) * 2 ) def __A ( self : Dict ) -> None: self._resize(len(self._buckets ) // 2 ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : KEY ) -> Iterator[int]: __lowerCamelCase = self._get_bucket_index(SCREAMING_SNAKE_CASE__ ) for _ in range(len(self._buckets ) ): yield ind __lowerCamelCase = self._get_next_ind(SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : KEY , SCREAMING_SNAKE_CASE__ : VAL ) -> None: for ind in self._iterate_buckets(SCREAMING_SNAKE_CASE__ ): if self._try_set(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): break def __setitem__( self : Tuple , SCREAMING_SNAKE_CASE__ : KEY , SCREAMING_SNAKE_CASE__ : VAL ) -> None: if self._is_full(): self._size_up() self._add_item(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __delitem__( self : List[Any] , SCREAMING_SNAKE_CASE__ : KEY ) -> None: for ind in self._iterate_buckets(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = self._buckets[ind] if item is None: raise KeyError(SCREAMING_SNAKE_CASE__ ) if item is _deleted: continue if item.key == key: __lowerCamelCase = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : KEY ) -> VAL: for ind in self._iterate_buckets(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(SCREAMING_SNAKE_CASE__ ) def __len__( self : int ) -> int: return self._len def __iter__( self : Tuple ) -> Iterator[KEY]: yield from (item.key for item in self._buckets if item) def __repr__( self : Optional[Any] ) -> str: __lowerCamelCase = ''' ,'''.join( f'''{item.key}: {item.val}''' for item in self._buckets if item ) return f'''HashMap({val_string})'''
339
0
import gc import random import unittest import torch from diffusers import ( IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ) from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference from . import IFPipelineTesterMixin @skip_mps class lowerCAmelCase__ ( __lowercase , __lowercase , unittest.TestCase ): a__ : str = IFPipeline a__ : Union[str, Any] = TEXT_TO_IMAGE_PARAMS - {"""width""", """height""", """latents"""} a__ : Optional[int] = TEXT_TO_IMAGE_BATCH_PARAMS a__ : Optional[Any] = PipelineTesterMixin.required_optional_params - {"""latents"""} def __A ( self : Optional[Any] ) -> Tuple: return self._get_dummy_components() def __A ( self : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict=0 ) -> Optional[Any]: if str(SCREAMING_SNAKE_CASE__ ).startswith('''mps''' ): __lowerCamelCase = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: __lowerCamelCase = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def __A ( self : Any ) -> Tuple: self._test_save_load_optional_components() @unittest.skipIf(torch_device != '''cuda''' , reason='''float16 requires CUDA''' ) def __A ( self : Dict ) -> List[Any]: # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder super().test_save_load_floataa(expected_max_diff=1e-1 ) def __A ( self : Dict ) -> Any: self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def __A ( self : Any ) -> str: self._test_save_load_local() def __A ( self : Tuple ) -> Optional[int]: self._test_inference_batch_single_identical( expected_max_diff=1e-2 , ) @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def __A ( self : List[str] ) -> Optional[Any]: self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Dict ) -> str: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self : List[Any] ) -> Optional[int]: # if __lowerCamelCase = IFPipeline.from_pretrained('''DeepFloyd/IF-I-XL-v1.0''' , variant='''fp16''' , torch_dtype=torch.floataa ) __lowerCamelCase = IFSuperResolutionPipeline.from_pretrained( '''DeepFloyd/IF-II-L-v1.0''' , variant='''fp16''' , torch_dtype=torch.floataa , text_encoder=SCREAMING_SNAKE_CASE__ , tokenizer=SCREAMING_SNAKE_CASE__ ) # pre compute text embeddings and remove T5 to save memory pipe_a.text_encoder.to('''cuda''' ) __lowerCamelCase , __lowerCamelCase = pipe_a.encode_prompt('''anime turtle''' , device='''cuda''' ) del pipe_a.tokenizer del pipe_a.text_encoder gc.collect() __lowerCamelCase = None __lowerCamelCase = None pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # img2img __lowerCamelCase = IFImgaImgPipeline(**pipe_a.components ) __lowerCamelCase = IFImgaImgSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_imgaimg(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # inpainting __lowerCamelCase = IFInpaintingPipeline(**pipe_a.components ) __lowerCamelCase = IFInpaintingSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_inpainting(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple ) -> Union[str, Any]: # pipeline 1 _start_torch_memory_measurement() __lowerCamelCase = torch.Generator(device='''cpu''' ).manual_seed(0 ) __lowerCamelCase = pipe_a( prompt_embeds=SCREAMING_SNAKE_CASE__ , negative_prompt_embeds=SCREAMING_SNAKE_CASE__ , num_inference_steps=2 , generator=SCREAMING_SNAKE_CASE__ , output_type='''np''' , ) __lowerCamelCase = output.images[0] assert image.shape == (64, 64, 3) __lowerCamelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 13 * 10**9 __lowerCamelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy''' ) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # pipeline 2 _start_torch_memory_measurement() __lowerCamelCase = torch.Generator(device='''cpu''' ).manual_seed(0 ) __lowerCamelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe_a( prompt_embeds=SCREAMING_SNAKE_CASE__ , negative_prompt_embeds=SCREAMING_SNAKE_CASE__ , image=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=2 , output_type='''np''' , ) __lowerCamelCase = output.images[0] assert image.shape == (2_56, 2_56, 3) __lowerCamelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 __lowerCamelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Optional[int]: # pipeline 1 _start_torch_memory_measurement() __lowerCamelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = torch.Generator(device='''cpu''' ).manual_seed(0 ) __lowerCamelCase = pipe_a( prompt_embeds=SCREAMING_SNAKE_CASE__ , negative_prompt_embeds=SCREAMING_SNAKE_CASE__ , image=SCREAMING_SNAKE_CASE__ , num_inference_steps=2 , generator=SCREAMING_SNAKE_CASE__ , output_type='''np''' , ) __lowerCamelCase = output.images[0] assert image.shape == (64, 64, 3) __lowerCamelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 __lowerCamelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy''' ) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # pipeline 2 _start_torch_memory_measurement() __lowerCamelCase = torch.Generator(device='''cpu''' ).manual_seed(0 ) __lowerCamelCase = floats_tensor((1, 3, 2_56, 2_56) , rng=random.Random(0 ) ).to(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe_a( prompt_embeds=SCREAMING_SNAKE_CASE__ , negative_prompt_embeds=SCREAMING_SNAKE_CASE__ , image=SCREAMING_SNAKE_CASE__ , original_image=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=2 , output_type='''np''' , ) __lowerCamelCase = output.images[0] assert image.shape == (2_56, 2_56, 3) __lowerCamelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 __lowerCamelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Optional[Any]: # pipeline 1 _start_torch_memory_measurement() __lowerCamelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(1 ) ).to(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = torch.Generator(device='''cpu''' ).manual_seed(0 ) __lowerCamelCase = pipe_a( prompt_embeds=SCREAMING_SNAKE_CASE__ , negative_prompt_embeds=SCREAMING_SNAKE_CASE__ , image=SCREAMING_SNAKE_CASE__ , mask_image=SCREAMING_SNAKE_CASE__ , num_inference_steps=2 , generator=SCREAMING_SNAKE_CASE__ , output_type='''np''' , ) __lowerCamelCase = output.images[0] assert image.shape == (64, 64, 3) __lowerCamelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 __lowerCamelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy''' ) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # pipeline 2 _start_torch_memory_measurement() __lowerCamelCase = torch.Generator(device='''cpu''' ).manual_seed(0 ) __lowerCamelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = floats_tensor((1, 3, 2_56, 2_56) , rng=random.Random(0 ) ).to(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = floats_tensor((1, 3, 2_56, 2_56) , rng=random.Random(1 ) ).to(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe_a( prompt_embeds=SCREAMING_SNAKE_CASE__ , negative_prompt_embeds=SCREAMING_SNAKE_CASE__ , image=SCREAMING_SNAKE_CASE__ , mask_image=SCREAMING_SNAKE_CASE__ , original_image=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=2 , output_type='''np''' , ) __lowerCamelCase = output.images[0] assert image.shape == (2_56, 2_56, 3) __lowerCamelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 __lowerCamelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __magic_name__ ( ) -> int: torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats()
361
from datetime import datetime as dt import os from github import Github SCREAMING_SNAKE_CASE__ : Any = [ "good first issue", "good second issue", "good difficult issue", "feature request", "new model", "wip", ] def __magic_name__ ( ) -> Any: __lowerCamelCase = Github(os.environ['''GITHUB_TOKEN'''] ) __lowerCamelCase = g.get_repo('''huggingface/transformers''' ) __lowerCamelCase = repo.get_issues(state='''open''' ) for issue in open_issues: __lowerCamelCase = sorted([comment for comment in issue.get_comments()] , key=lambda __lowerCAmelCase : i.created_at , reverse=__lowerCAmelCase ) __lowerCamelCase = comments[0] if len(__lowerCAmelCase ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # print(f"Would close issue {issue.number} since it has been 7 days of inactivity since bot mention.") issue.edit(state='''closed''' ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # print(f"Would add stale comment to {issue.number}") issue.create_comment( '''This issue has been automatically marked as stale because it has not had ''' '''recent activity. If you think this still needs to be addressed ''' '''please comment on this thread.\n\nPlease note that issues that do not follow the ''' '''[contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) ''' '''are likely to be ignored.''' ) if __name__ == "__main__": main()
339
0
def __magic_name__ ( __lowerCAmelCase : str ) -> bool: return credit_card_number.startswith(('''34''', '''35''', '''37''', '''4''', '''5''', '''6''') ) def __magic_name__ ( __lowerCAmelCase : str ) -> bool: __lowerCamelCase = credit_card_number __lowerCamelCase = 0 __lowerCamelCase = len(__lowerCAmelCase ) - 2 for i in range(__lowerCAmelCase , -1 , -2 ): # double the value of every second digit __lowerCamelCase = int(cc_number[i] ) digit *= 2 # If doubling of a number results in a two digit number # i.e greater than 9(e.g., 6 × 2 = 12), # then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6), # to get a single digit number. if digit > 9: digit %= 10 digit += 1 __lowerCamelCase = cc_number[:i] + str(__lowerCAmelCase ) + cc_number[i + 1 :] total += digit # Sum up the remaining digits for i in range(len(__lowerCAmelCase ) - 1 , -1 , -2 ): total += int(cc_number[i] ) return total % 10 == 0 def __magic_name__ ( __lowerCAmelCase : str ) -> bool: __lowerCamelCase = f'''{credit_card_number} is an invalid credit card number because''' if not credit_card_number.isdigit(): print(f'''{error_message} it has nonnumerical characters.''' ) return False if not 13 <= len(__lowerCAmelCase ) <= 16: print(f'''{error_message} of its length.''' ) return False if not validate_initial_digits(__lowerCAmelCase ): print(f'''{error_message} of its first two digits.''' ) return False if not luhn_validation(__lowerCAmelCase ): print(f'''{error_message} it fails the Luhn check.''' ) return False print(f'''{credit_card_number} is a valid credit card number.''' ) return True if __name__ == "__main__": import doctest doctest.testmod() validate_credit_card_number("4111111111111111") validate_credit_card_number("32323")
362
def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int ) -> str: if a < 0 or b < 0: raise ValueError('''the value of both inputs must be positive''' ) __lowerCamelCase = str(bin(__lowerCAmelCase ) )[2:] # remove the leading "0b" __lowerCamelCase = str(bin(__lowerCAmelCase ) )[2:] # remove the leading "0b" __lowerCamelCase = max(len(__lowerCAmelCase ) , len(__lowerCAmelCase ) ) return "0b" + "".join( str(int(char_a == '''1''' and char_b == '''1''' ) ) for char_a, char_b in zip(a_binary.zfill(__lowerCAmelCase ) , b_binary.zfill(__lowerCAmelCase ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
339
0
from ...configuration_utils import PretrainedConfig class lowerCAmelCase__ ( __lowercase ): a__ : List[Any] = """bert-generation""" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict=5_03_58 , SCREAMING_SNAKE_CASE__ : List[Any]=10_24 , SCREAMING_SNAKE_CASE__ : Dict=24 , SCREAMING_SNAKE_CASE__ : List[str]=16 , SCREAMING_SNAKE_CASE__ : Optional[int]=40_96 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Any=0.1 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=5_12 , SCREAMING_SNAKE_CASE__ : Tuple=0.02 , SCREAMING_SNAKE_CASE__ : str=1e-12 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0 , SCREAMING_SNAKE_CASE__ : int=2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=1 , SCREAMING_SNAKE_CASE__ : int="absolute" , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , **SCREAMING_SNAKE_CASE__ : Optional[int] , ) -> Dict: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = vocab_size __lowerCamelCase = hidden_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = hidden_act __lowerCamelCase = intermediate_size __lowerCamelCase = hidden_dropout_prob __lowerCamelCase = attention_probs_dropout_prob __lowerCamelCase = max_position_embeddings __lowerCamelCase = initializer_range __lowerCamelCase = layer_norm_eps __lowerCamelCase = position_embedding_type __lowerCamelCase = use_cache
363
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPSegProcessor, ViTImageProcessor @require_vision class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : List[str] ) -> Dict: __lowerCamelCase = tempfile.mkdtemp() # fmt: off __lowerCamelCase = ['''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''lo''', '''l</w>''', '''w</w>''', '''r</w>''', '''t</w>''', '''low</w>''', '''er</w>''', '''lowest</w>''', '''newer</w>''', '''wider''', '''<unk>''', '''<|startoftext|>''', '''<|endoftext|>'''] # fmt: on __lowerCamelCase = dict(zip(SCREAMING_SNAKE_CASE__ , range(len(SCREAMING_SNAKE_CASE__ ) ) ) ) __lowerCamelCase = ['''#version: 0.2''', '''l o''', '''lo w</w>''', '''e r</w>''', ''''''] __lowerCamelCase = {'''unk_token''': '''<unk>'''} __lowerCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) __lowerCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE__ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = { '''do_resize''': True, '''size''': 20, '''do_center_crop''': True, '''crop_size''': 18, '''do_normalize''': True, '''image_mean''': [0.48145466, 0.4578275, 0.40821073], '''image_std''': [0.26862954, 0.26130258, 0.27577711], } __lowerCamelCase = os.path.join(self.tmpdirname , SCREAMING_SNAKE_CASE__ ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : int , **SCREAMING_SNAKE_CASE__ : int ) -> Any: return CLIPTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def __A ( self : Dict , **SCREAMING_SNAKE_CASE__ : Dict ) -> Union[str, Any]: return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[int] , **SCREAMING_SNAKE_CASE__ : Any ) -> List[Any]: return ViTImageProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def __A ( self : Dict ) -> Dict: shutil.rmtree(self.tmpdirname ) def __A ( self : str ) -> Any: __lowerCamelCase = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] __lowerCamelCase = [Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def __A ( self : List[Any] ) -> List[str]: __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = self.get_rust_tokenizer() __lowerCamelCase = self.get_image_processor() __lowerCamelCase = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) processor_slow.save_pretrained(self.tmpdirname ) __lowerCamelCase = CLIPSegProcessor.from_pretrained(self.tmpdirname , use_fast=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) processor_fast.save_pretrained(self.tmpdirname ) __lowerCamelCase = 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 , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor_fast.tokenizer , SCREAMING_SNAKE_CASE__ ) 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 , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor_fast.image_processor , SCREAMING_SNAKE_CASE__ ) def __A ( self : Union[str, Any] ) -> int: __lowerCamelCase = CLIPSegProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __lowerCamelCase = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __lowerCamelCase = self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) __lowerCamelCase = CLIPSegProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , SCREAMING_SNAKE_CASE__ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[Any] ) -> Union[str, Any]: __lowerCamelCase = self.get_image_processor() __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.prepare_image_inputs() __lowerCamelCase = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='''np''' ) __lowerCamelCase = processor(images=SCREAMING_SNAKE_CASE__ , 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 __A ( self : List[Any] ) -> Optional[int]: __lowerCamelCase = self.get_image_processor() __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = '''lower newer''' __lowerCamelCase = processor(text=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = tokenizer(SCREAMING_SNAKE_CASE__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __A ( self : List[Any] ) -> Any: __lowerCamelCase = self.get_image_processor() __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = '''lower newer''' __lowerCamelCase = self.prepare_image_inputs() __lowerCamelCase = processor(text=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE__ ): processor() def __A ( self : Optional[Any] ) -> List[str]: __lowerCamelCase = self.get_image_processor() __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.prepare_image_inputs() __lowerCamelCase = self.prepare_image_inputs() __lowerCamelCase = processor(images=SCREAMING_SNAKE_CASE__ , visual_prompt=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , ['''pixel_values''', '''conditional_pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE__ ): processor() def __A ( self : List[Any] ) -> Any: __lowerCamelCase = self.get_image_processor() __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __lowerCamelCase = processor.batch_decode(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
339
0
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, ClassLabel, Features from .base import TaskTemplate @dataclass(frozen=__lowercase ) class lowerCAmelCase__ ( __lowercase ): a__ : str = field(default="""audio-classification""" , metadata={"""include_in_asdict_even_if_is_default""": True} ) a__ : ClassVar[Features] = Features({"""audio""": Audio()} ) a__ : ClassVar[Features] = Features({"""labels""": ClassLabel} ) a__ : str = "audio" a__ : str = "labels" def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[Any]: if self.label_column not in features: raise ValueError(f'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] , SCREAMING_SNAKE_CASE__ ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) __lowerCamelCase = copy.deepcopy(self ) __lowerCamelCase = self.label_schema.copy() __lowerCamelCase = features[self.label_column] __lowerCamelCase = label_schema return task_template @property def __A ( self : Union[str, Any] ) -> Dict[str, str]: return { self.audio_column: "audio", self.label_column: "labels", }
364
from __future__ import annotations def __magic_name__ ( __lowerCAmelCase : list , __lowerCAmelCase : int | None = None , __lowerCAmelCase : int | None = None ) -> None: if start is None: __lowerCamelCase = 0 if end is None: __lowerCamelCase = len(__lowerCAmelCase ) - 1 if start >= end: return __lowerCamelCase = (start + end) // 2 slowsort(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) slowsort(__lowerCAmelCase , mid + 1 , __lowerCAmelCase ) if sequence[end] < sequence[mid]: __lowerCamelCase , __lowerCamelCase = sequence[mid], sequence[end] slowsort(__lowerCAmelCase , __lowerCAmelCase , end - 1 ) if __name__ == "__main__": from doctest import testmod testmod()
339
0
def __magic_name__ ( __lowerCAmelCase : int ) -> bool: if not isinstance(__lowerCAmelCase , __lowerCAmelCase ): raise ValueError('''check_bouncy() accepts only integer arguments''' ) __lowerCamelCase = str(__lowerCAmelCase ) __lowerCamelCase = ''''''.join(sorted(__lowerCAmelCase ) ) return sorted_str_n != str_n and sorted_str_n[::-1] != str_n def __magic_name__ ( __lowerCAmelCase : float = 99 ) -> int: if not 0 < percent < 100: raise ValueError('''solution() only accepts values from 0 to 100''' ) __lowerCamelCase = 0 __lowerCamelCase = 1 while True: if check_bouncy(__lowerCAmelCase ): bouncy_num += 1 if (bouncy_num / num) * 100 >= percent: return num num += 1 if __name__ == "__main__": from doctest import testmod testmod() print(F'{solution(99)}')
365
import json import os from typing import Dict, List, Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE__ : Any = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Optional[Any] = { "vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_config_file": "tokenizer_config.json", } SCREAMING_SNAKE_CASE__ : str = { "vocab_file": { "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json" }, "merges_file": { "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt" }, "tokenizer_config_file": { "facebook/blenderbot_small-90M": ( "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json" ) }, } SCREAMING_SNAKE_CASE__ : int = {"facebook/blenderbot_small-90M": 512} def __magic_name__ ( __lowerCAmelCase : List[str] ) -> Tuple: __lowerCamelCase = set() __lowerCamelCase = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __lowerCamelCase = char __lowerCamelCase = set(__lowerCAmelCase ) return pairs class lowerCAmelCase__ ( __lowercase ): a__ : List[Any] = VOCAB_FILES_NAMES a__ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP a__ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ : Dict = ["""input_ids""", """attention_mask"""] def __init__( self : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple="__start__" , SCREAMING_SNAKE_CASE__ : Tuple="__end__" , SCREAMING_SNAKE_CASE__ : List[str]="__unk__" , SCREAMING_SNAKE_CASE__ : str="__null__" , **SCREAMING_SNAKE_CASE__ : Optional[Any] , ) -> Optional[Any]: super().__init__(unk_token=SCREAMING_SNAKE_CASE__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) with open(SCREAMING_SNAKE_CASE__ , encoding='''utf-8''' ) as vocab_handle: __lowerCamelCase = json.load(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = {v: k for k, v in self.encoder.items()} with open(SCREAMING_SNAKE_CASE__ , encoding='''utf-8''' ) as merges_handle: __lowerCamelCase = merges_handle.read().split('''\n''' )[1:-1] __lowerCamelCase = [tuple(merge.split() ) for merge in merges] __lowerCamelCase = dict(zip(SCREAMING_SNAKE_CASE__ , range(len(SCREAMING_SNAKE_CASE__ ) ) ) ) __lowerCamelCase = {} @property def __A ( self : Dict ) -> int: return len(self.encoder ) def __A ( self : str ) -> Dict: return dict(self.encoder , **self.added_tokens_encoder ) def __A ( self : Any , SCREAMING_SNAKE_CASE__ : str ) -> str: if token in self.cache: return self.cache[token] __lowerCamelCase = re.sub('''([.,!?()])''' , R''' \1''' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = re.sub('''(\')''' , R''' \1 ''' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = re.sub(R'''\s{2,}''' , ''' ''' , SCREAMING_SNAKE_CASE__ ) if "\n" in token: __lowerCamelCase = token.replace('''\n''' , ''' __newln__''' ) __lowerCamelCase = token.split(''' ''' ) __lowerCamelCase = [] for token in tokens: if not len(SCREAMING_SNAKE_CASE__ ): continue __lowerCamelCase = token.lower() __lowerCamelCase = tuple(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = tuple(list(word[:-1] ) + [word[-1] + '''</w>'''] ) __lowerCamelCase = get_pairs(SCREAMING_SNAKE_CASE__ ) if not pairs: words.append(SCREAMING_SNAKE_CASE__ ) continue while True: __lowerCamelCase = min(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : self.bpe_ranks.get(SCREAMING_SNAKE_CASE__ , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break __lowerCamelCase , __lowerCamelCase = bigram __lowerCamelCase = [] __lowerCamelCase = 0 while i < len(SCREAMING_SNAKE_CASE__ ): try: __lowerCamelCase = word.index(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) new_word.extend(word[i:j] ) __lowerCamelCase = j except ValueError: new_word.extend(word[i:] ) break if word[i] == first and i < len(SCREAMING_SNAKE_CASE__ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 __lowerCamelCase = tuple(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = new_word if len(SCREAMING_SNAKE_CASE__ ) == 1: break else: __lowerCamelCase = get_pairs(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = '''@@ '''.join(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = word[:-4] __lowerCamelCase = word words.append(SCREAMING_SNAKE_CASE__ ) return " ".join(SCREAMING_SNAKE_CASE__ ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: __lowerCamelCase = [] __lowerCamelCase = re.findall(R'''\S+\n?''' , SCREAMING_SNAKE_CASE__ ) for token in words: split_tokens.extend(list(self.bpe(SCREAMING_SNAKE_CASE__ ).split(''' ''' ) ) ) return split_tokens def __A ( self : str , SCREAMING_SNAKE_CASE__ : str ) -> int: __lowerCamelCase = token.lower() return self.encoder.get(SCREAMING_SNAKE_CASE__ , self.encoder.get(self.unk_token ) ) def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : int ) -> str: return self.decoder.get(SCREAMING_SNAKE_CASE__ , self.unk_token ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] ) -> str: __lowerCamelCase = ''' '''.join(SCREAMING_SNAKE_CASE__ ).replace('''@@ ''' , '''''' ).strip() return out_string def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __lowerCamelCase = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) __lowerCamelCase = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(SCREAMING_SNAKE_CASE__ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=SCREAMING_SNAKE_CASE__ , ensure_ascii=SCREAMING_SNAKE_CASE__ ) + '''\n''' ) __lowerCamelCase = 0 with open(SCREAMING_SNAKE_CASE__ , '''w''' , encoding='''utf-8''' ) as writer: writer.write('''#version: 0.2\n''' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda SCREAMING_SNAKE_CASE__ : kv[1] ): if index != token_index: logger.warning( f'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.''' ''' Please check that the tokenizer is not corrupted!''' ) __lowerCamelCase = token_index writer.write(''' '''.join(SCREAMING_SNAKE_CASE__ ) + '''\n''' ) index += 1 return vocab_file, merge_file
339
0
# coding=utf-8 # Copyright 2023 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # this script dumps information about the environment import os import platform import sys SCREAMING_SNAKE_CASE__ : List[Any] = "3" print("Python version:", sys.version) print("OS platform:", platform.platform()) print("OS architecture:", platform.machine()) try: import torch print("Torch version:", torch.__version__) print("Cuda available:", torch.cuda.is_available()) print("Cuda version:", torch.version.cuda) print("CuDNN version:", torch.backends.cudnn.version()) print("Number of GPUs available:", torch.cuda.device_count()) except ImportError: print("Torch version:", None) try: import transformers print("transformers version:", transformers.__version__) except ImportError: print("transformers version:", None)
366
import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class lowerCAmelCase__ ( __lowercase , unittest.TestCase ): a__ : str = ShapEImgaImgPipeline a__ : Union[str, Any] = ["""image"""] a__ : Optional[int] = ["""image"""] a__ : Union[str, Any] = [ """num_images_per_prompt""", """num_inference_steps""", """generator""", """latents""", """guidance_scale""", """frame_size""", """output_type""", """return_dict""", ] a__ : List[str] = False @property def __A ( self : Dict ) -> Optional[Any]: return 32 @property def __A ( self : Optional[int] ) -> Optional[int]: return 32 @property def __A ( self : Optional[int] ) -> List[Any]: return self.time_input_dim * 4 @property def __A ( self : str ) -> List[Any]: return 8 @property def __A ( self : Optional[Any] ) -> Union[str, Any]: torch.manual_seed(0 ) __lowerCamelCase = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) __lowerCamelCase = CLIPVisionModel(SCREAMING_SNAKE_CASE__ ) return model @property def __A ( self : Union[str, Any] ) -> Union[str, Any]: __lowerCamelCase = CLIPImageProcessor( crop_size=2_24 , do_center_crop=SCREAMING_SNAKE_CASE__ , do_normalize=SCREAMING_SNAKE_CASE__ , do_resize=SCREAMING_SNAKE_CASE__ , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=2_24 , ) return image_processor @property def __A ( self : Dict ) -> int: torch.manual_seed(0 ) __lowerCamelCase = { '''num_attention_heads''': 2, '''attention_head_dim''': 16, '''embedding_dim''': self.time_input_dim, '''num_embeddings''': 32, '''embedding_proj_dim''': self.text_embedder_hidden_size, '''time_embed_dim''': self.time_embed_dim, '''num_layers''': 1, '''clip_embed_dim''': self.time_input_dim * 2, '''additional_embeddings''': 0, '''time_embed_act_fn''': '''gelu''', '''norm_in_type''': '''layer''', '''embedding_proj_norm_type''': '''layer''', '''encoder_hid_proj_type''': None, '''added_emb_type''': None, } __lowerCamelCase = PriorTransformer(**SCREAMING_SNAKE_CASE__ ) return model @property def __A ( self : Tuple ) -> Dict: torch.manual_seed(0 ) __lowerCamelCase = { '''param_shapes''': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), '''d_latent''': self.time_input_dim, '''d_hidden''': self.renderer_dim, '''n_output''': 12, '''background''': ( 0.1, 0.1, 0.1, ), } __lowerCamelCase = ShapERenderer(**SCREAMING_SNAKE_CASE__ ) return model def __A ( self : Optional[int] ) -> List[str]: __lowerCamelCase = self.dummy_prior __lowerCamelCase = self.dummy_image_encoder __lowerCamelCase = self.dummy_image_processor __lowerCamelCase = self.dummy_renderer __lowerCamelCase = HeunDiscreteScheduler( beta_schedule='''exp''' , num_train_timesteps=10_24 , prediction_type='''sample''' , use_karras_sigmas=SCREAMING_SNAKE_CASE__ , clip_sample=SCREAMING_SNAKE_CASE__ , clip_sample_range=1.0 , ) __lowerCamelCase = { '''prior''': prior, '''image_encoder''': image_encoder, '''image_processor''': image_processor, '''renderer''': renderer, '''scheduler''': scheduler, } return components def __A ( self : str , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any=0 ) -> int: __lowerCamelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) if str(SCREAMING_SNAKE_CASE__ ).startswith('''mps''' ): __lowerCamelCase = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: __lowerCamelCase = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = { '''image''': input_image, '''generator''': generator, '''num_inference_steps''': 1, '''frame_size''': 32, '''output_type''': '''np''', } return inputs def __A ( self : Union[str, Any] ) -> Dict: __lowerCamelCase = '''cpu''' __lowerCamelCase = self.get_dummy_components() __lowerCamelCase = self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe(**self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = output.images[0] __lowerCamelCase = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __lowerCamelCase = np.array( [ 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __A ( self : str ) -> Tuple: # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def __A ( self : Optional[Any] ) -> str: __lowerCamelCase = torch_device == '''cpu''' __lowerCamelCase = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=SCREAMING_SNAKE_CASE__ , relax_max_difference=SCREAMING_SNAKE_CASE__ , ) def __A ( self : Dict ) -> Optional[int]: __lowerCamelCase = self.get_dummy_components() __lowerCamelCase = self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = 1 __lowerCamelCase = 2 __lowerCamelCase = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) for key in inputs.keys(): if key in self.batch_params: __lowerCamelCase = batch_size * [inputs[key]] __lowerCamelCase = pipe(**SCREAMING_SNAKE_CASE__ , num_images_per_prompt=SCREAMING_SNAKE_CASE__ )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : str ) -> Union[str, Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self : str ) -> Union[str, Any]: __lowerCamelCase = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/corgi.png''' ) __lowerCamelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/test_shap_e_img2img_out.npy''' ) __lowerCamelCase = ShapEImgaImgPipeline.from_pretrained('''openai/shap-e-img2img''' ) __lowerCamelCase = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(0 ) __lowerCamelCase = pipe( SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type='''np''' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
339
0
import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import ( DiffusionPipeline, UnCLIPImageVariationPipeline, UnCLIPScheduler, UNetaDConditionModel, UNetaDModel, ) from diffusers.pipelines.unclip.text_proj import UnCLIPTextProjModel from diffusers.utils import floats_tensor, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, load_image, require_torch_gpu, skip_mps from ..pipeline_params import IMAGE_VARIATION_BATCH_PARAMS, IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class lowerCAmelCase__ ( __lowercase , unittest.TestCase ): a__ : Optional[int] = UnCLIPImageVariationPipeline a__ : Optional[Any] = IMAGE_VARIATION_PARAMS - {"""height""", """width""", """guidance_scale"""} a__ : Union[str, Any] = IMAGE_VARIATION_BATCH_PARAMS a__ : int = [ """generator""", """return_dict""", """decoder_num_inference_steps""", """super_res_num_inference_steps""", ] a__ : int = False @property def __A ( self : Optional[Any] ) -> Optional[Any]: return 32 @property def __A ( self : Tuple ) -> str: return 32 @property def __A ( self : Optional[int] ) -> Tuple: return self.time_input_dim @property def __A ( self : Dict ) -> Optional[Any]: return self.time_input_dim * 4 @property def __A ( self : Optional[Any] ) -> List[Any]: return 1_00 @property def __A ( self : int ) -> Optional[Any]: __lowerCamelCase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) return tokenizer @property def __A ( self : int ) -> Optional[Any]: torch.manual_seed(0 ) __lowerCamelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) return CLIPTextModelWithProjection(SCREAMING_SNAKE_CASE__ ) @property def __A ( self : Any ) -> str: torch.manual_seed(0 ) __lowerCamelCase = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , ) return CLIPVisionModelWithProjection(SCREAMING_SNAKE_CASE__ ) @property def __A ( self : Dict ) -> Tuple: torch.manual_seed(0 ) __lowerCamelCase = { '''clip_embeddings_dim''': self.text_embedder_hidden_size, '''time_embed_dim''': self.time_embed_dim, '''cross_attention_dim''': self.cross_attention_dim, } __lowerCamelCase = UnCLIPTextProjModel(**SCREAMING_SNAKE_CASE__ ) return model @property def __A ( self : str ) -> Optional[int]: torch.manual_seed(0 ) __lowerCamelCase = { '''sample_size''': 32, # RGB in channels '''in_channels''': 3, # Out channels is double in channels because predicts mean and variance '''out_channels''': 6, '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''), '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''), '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''', '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2), '''layers_per_block''': 1, '''cross_attention_dim''': self.cross_attention_dim, '''attention_head_dim''': 4, '''resnet_time_scale_shift''': '''scale_shift''', '''class_embed_type''': '''identity''', } __lowerCamelCase = UNetaDConditionModel(**SCREAMING_SNAKE_CASE__ ) return model @property def __A ( self : Optional[int] ) -> List[Any]: return { "sample_size": 64, "layers_per_block": 1, "down_block_types": ("ResnetDownsampleBlock2D", "ResnetDownsampleBlock2D"), "up_block_types": ("ResnetUpsampleBlock2D", "ResnetUpsampleBlock2D"), "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "in_channels": 6, "out_channels": 3, } @property def __A ( self : int ) -> List[str]: torch.manual_seed(0 ) __lowerCamelCase = UNetaDModel(**self.dummy_super_res_kwargs ) return model @property def __A ( self : List[str] ) -> List[Any]: # seeded differently to get different unet than `self.dummy_super_res_first` torch.manual_seed(1 ) __lowerCamelCase = UNetaDModel(**self.dummy_super_res_kwargs ) return model def __A ( self : Union[str, Any] ) -> List[str]: __lowerCamelCase = self.dummy_decoder __lowerCamelCase = self.dummy_text_proj __lowerCamelCase = self.dummy_text_encoder __lowerCamelCase = self.dummy_tokenizer __lowerCamelCase = self.dummy_super_res_first __lowerCamelCase = self.dummy_super_res_last __lowerCamelCase = UnCLIPScheduler( variance_type='''learned_range''' , prediction_type='''epsilon''' , num_train_timesteps=10_00 , ) __lowerCamelCase = UnCLIPScheduler( variance_type='''fixed_small_log''' , prediction_type='''epsilon''' , num_train_timesteps=10_00 , ) __lowerCamelCase = CLIPImageProcessor(crop_size=32 , size=32 ) __lowerCamelCase = self.dummy_image_encoder return { "decoder": decoder, "text_encoder": text_encoder, "tokenizer": tokenizer, "text_proj": text_proj, "feature_extractor": feature_extractor, "image_encoder": image_encoder, "super_res_first": super_res_first, "super_res_last": super_res_last, "decoder_scheduler": decoder_scheduler, "super_res_scheduler": super_res_scheduler, } def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple=0 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True ) -> List[Any]: __lowerCamelCase = floats_tensor((1, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) if str(SCREAMING_SNAKE_CASE__ ).startswith('''mps''' ): __lowerCamelCase = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: __lowerCamelCase = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) if pil_image: __lowerCamelCase = input_image * 0.5 + 0.5 __lowerCamelCase = input_image.clamp(0 , 1 ) __lowerCamelCase = input_image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() __lowerCamelCase = DiffusionPipeline.numpy_to_pil(SCREAMING_SNAKE_CASE__ )[0] return { "image": input_image, "generator": generator, "decoder_num_inference_steps": 2, "super_res_num_inference_steps": 2, "output_type": "np", } def __A ( self : Dict ) -> Optional[Any]: __lowerCamelCase = '''cpu''' __lowerCamelCase = self.get_dummy_components() __lowerCamelCase = self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ , pil_image=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = output.images __lowerCamelCase = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ , pil_image=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe( **SCREAMING_SNAKE_CASE__ , return_dict=SCREAMING_SNAKE_CASE__ , )[0] __lowerCamelCase = image[0, -3:, -3:, -1] __lowerCamelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __lowerCamelCase = np.array( [ 0.9997, 0.0002, 0.9997, 0.9997, 0.9969, 0.0023, 0.9997, 0.9969, 0.9970, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def __A ( self : Optional[int] ) -> Dict: __lowerCamelCase = '''cpu''' __lowerCamelCase = self.get_dummy_components() __lowerCamelCase = self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ , pil_image=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = output.images __lowerCamelCase = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ , pil_image=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe( **SCREAMING_SNAKE_CASE__ , return_dict=SCREAMING_SNAKE_CASE__ , )[0] __lowerCamelCase = image[0, -3:, -3:, -1] __lowerCamelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __lowerCamelCase = np.array([0.9997, 0.0003, 0.9997, 0.9997, 0.9970, 0.0024, 0.9997, 0.9971, 0.9971] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def __A ( self : List[Any] ) -> str: __lowerCamelCase = '''cpu''' __lowerCamelCase = self.get_dummy_components() __lowerCamelCase = self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ , pil_image=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = [ pipeline_inputs['''image'''], pipeline_inputs['''image'''], ] __lowerCamelCase = pipe(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = output.images __lowerCamelCase = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ , pil_image=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = [ tuple_pipeline_inputs['''image'''], tuple_pipeline_inputs['''image'''], ] __lowerCamelCase = pipe( **SCREAMING_SNAKE_CASE__ , return_dict=SCREAMING_SNAKE_CASE__ , )[0] __lowerCamelCase = image[0, -3:, -3:, -1] __lowerCamelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (2, 64, 64, 3) __lowerCamelCase = np.array( [ 0.9997, 0.9989, 0.0008, 0.0021, 0.9960, 0.0018, 0.0014, 0.0002, 0.9933, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def __A ( self : List[Any] ) -> str: __lowerCamelCase = torch.device('''cpu''' ) class lowerCAmelCase__ : a__ : List[Any] = 1 __lowerCamelCase = self.get_dummy_components() __lowerCamelCase = self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(0 ) __lowerCamelCase = pipe.decoder.dtype __lowerCamelCase = 1 __lowerCamelCase = ( batch_size, pipe.decoder.config.in_channels, pipe.decoder.config.sample_size, pipe.decoder.config.sample_size, ) __lowerCamelCase = pipe.prepare_latents( SCREAMING_SNAKE_CASE__ , dtype=SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , latents=SCREAMING_SNAKE_CASE__ , scheduler=DummyScheduler() ) __lowerCamelCase = ( batch_size, pipe.super_res_first.config.in_channels // 2, pipe.super_res_first.config.sample_size, pipe.super_res_first.config.sample_size, ) __lowerCamelCase = pipe.prepare_latents( SCREAMING_SNAKE_CASE__ , dtype=SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , latents=SCREAMING_SNAKE_CASE__ , scheduler=DummyScheduler() ) __lowerCamelCase = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ , pil_image=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe( **SCREAMING_SNAKE_CASE__ , decoder_latents=SCREAMING_SNAKE_CASE__ , super_res_latents=SCREAMING_SNAKE_CASE__ ).images __lowerCamelCase = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ , pil_image=SCREAMING_SNAKE_CASE__ ) # Don't pass image, instead pass embedding __lowerCamelCase = pipeline_inputs.pop('''image''' ) __lowerCamelCase = pipe.image_encoder(SCREAMING_SNAKE_CASE__ ).image_embeds __lowerCamelCase = pipe( **SCREAMING_SNAKE_CASE__ , decoder_latents=SCREAMING_SNAKE_CASE__ , super_res_latents=SCREAMING_SNAKE_CASE__ , image_embeddings=SCREAMING_SNAKE_CASE__ , ).images # make sure passing text embeddings manually is identical assert np.abs(img_out_a - img_out_a ).max() < 1e-4 @skip_mps def __A ( self : List[Any] ) -> int: __lowerCamelCase = torch_device == '''cpu''' # Check is relaxed because there is not a torch 2.0 sliced attention added kv processor __lowerCamelCase = 1e-2 self._test_attention_slicing_forward_pass( test_max_difference=SCREAMING_SNAKE_CASE__ , expected_max_diff=SCREAMING_SNAKE_CASE__ ) @skip_mps def __A ( self : Union[str, Any] ) -> Tuple: __lowerCamelCase = torch_device == '''cpu''' __lowerCamelCase = True __lowerCamelCase = [ '''decoder_num_inference_steps''', '''super_res_num_inference_steps''', ] self._test_inference_batch_single_identical( test_max_difference=SCREAMING_SNAKE_CASE__ , relax_max_difference=SCREAMING_SNAKE_CASE__ , additional_params_copy_to_batched_inputs=SCREAMING_SNAKE_CASE__ , ) def __A ( self : Tuple ) -> Any: __lowerCamelCase = [ '''decoder_num_inference_steps''', '''super_res_num_inference_steps''', ] if torch_device == "mps": # TODO: MPS errors with larger batch sizes __lowerCamelCase = [2, 3] self._test_inference_batch_consistent( batch_sizes=SCREAMING_SNAKE_CASE__ , additional_params_copy_to_batched_inputs=SCREAMING_SNAKE_CASE__ , ) else: self._test_inference_batch_consistent( additional_params_copy_to_batched_inputs=SCREAMING_SNAKE_CASE__ ) @skip_mps def __A ( self : int ) -> int: return super().test_dict_tuple_outputs_equivalent() @skip_mps def __A ( self : List[Any] ) -> Any: return super().test_save_load_local() @skip_mps def __A ( self : Tuple ) -> str: return super().test_save_load_optional_components() @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : List[Any] ) -> List[Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self : Optional[int] ) -> Union[str, Any]: __lowerCamelCase = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/unclip/cat.png''' ) __lowerCamelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/unclip/karlo_v1_alpha_cat_variation_fp16.npy''' ) __lowerCamelCase = UnCLIPImageVariationPipeline.from_pretrained( '''kakaobrain/karlo-v1-alpha-image-variations''' , torch_dtype=torch.floataa ) __lowerCamelCase = pipeline.to(SCREAMING_SNAKE_CASE__ ) pipeline.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = torch.Generator(device='''cpu''' ).manual_seed(0 ) __lowerCamelCase = pipeline( SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , output_type='''np''' , ) __lowerCamelCase = output.images[0] assert image.shape == (2_56, 2_56, 3) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 15 )
367
import glob import os import random from string import ascii_lowercase, digits import cva SCREAMING_SNAKE_CASE__ : str = "" SCREAMING_SNAKE_CASE__ : Any = "" SCREAMING_SNAKE_CASE__ : Optional[Any] = "" SCREAMING_SNAKE_CASE__ : Optional[Any] = 1 # (0 is vertical, 1 is horizontal) def __magic_name__ ( ) -> None: __lowerCamelCase , __lowerCamelCase = get_dataset(__lowerCAmelCase , __lowerCAmelCase ) print('''Processing...''' ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = update_image_and_anno(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) for index, image in enumerate(__lowerCAmelCase ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' __lowerCamelCase = random_chars(32 ) __lowerCamelCase = paths[index].split(os.sep )[-1].rsplit('''.''' , 1 )[0] __lowerCamelCase = f'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(f'''/{file_root}.jpg''' , __lowerCAmelCase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(f'''Success {index+1}/{len(__lowerCAmelCase )} with {file_name}''' ) __lowerCamelCase = [] for anno in new_annos[index]: __lowerCamelCase = f'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(__lowerCAmelCase ) with open(f'''/{file_root}.txt''' , '''w''' ) as outfile: outfile.write('''\n'''.join(line for line in annos_list ) ) def __magic_name__ ( __lowerCAmelCase : str , __lowerCAmelCase : str ) -> tuple[list, list]: __lowerCamelCase = [] __lowerCamelCase = [] for label_file in glob.glob(os.path.join(__lowerCAmelCase , '''*.txt''' ) ): __lowerCamelCase = label_file.split(os.sep )[-1].rsplit('''.''' , 1 )[0] with open(__lowerCAmelCase ) as in_file: __lowerCamelCase = in_file.readlines() __lowerCamelCase = os.path.join(__lowerCAmelCase , f'''{label_name}.jpg''' ) __lowerCamelCase = [] for obj_list in obj_lists: __lowerCamelCase = obj_list.rstrip('''\n''' ).split(''' ''' ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(__lowerCAmelCase ) labels.append(__lowerCAmelCase ) return img_paths, labels def __magic_name__ ( __lowerCAmelCase : list , __lowerCAmelCase : list , __lowerCAmelCase : int = 1 ) -> tuple[list, list, list]: __lowerCamelCase = [] __lowerCamelCase = [] __lowerCamelCase = [] for idx in range(len(__lowerCAmelCase ) ): __lowerCamelCase = [] __lowerCamelCase = img_list[idx] path_list.append(__lowerCAmelCase ) __lowerCamelCase = anno_list[idx] __lowerCamelCase = cva.imread(__lowerCAmelCase ) if flip_type == 1: __lowerCamelCase = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: __lowerCamelCase = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: __lowerCamelCase = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: __lowerCamelCase = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(__lowerCAmelCase ) new_imgs_list.append(__lowerCAmelCase ) return new_imgs_list, new_annos_lists, path_list def __magic_name__ ( __lowerCAmelCase : int = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" __lowerCamelCase = ascii_lowercase + digits return "".join(random.choice(__lowerCAmelCase ) for _ in range(__lowerCAmelCase ) ) if __name__ == "__main__": main() print("DONE ✅")
339
0
import os import sys import unittest SCREAMING_SNAKE_CASE__ : Any = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, "utils")) import check_dummies # noqa: E402 from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init # noqa: E402 # Align TRANSFORMERS_PATH in check_dummies with the current path SCREAMING_SNAKE_CASE__ : Any = os.path.join(git_repo_path, "src", "diffusers") class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Dict ) -> str: __lowerCamelCase = find_backend(''' if not is_torch_available():''' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , '''torch''' ) # backend_with_underscore = find_backend(" if not is_tensorflow_text_available():") # self.assertEqual(backend_with_underscore, "tensorflow_text") __lowerCamelCase = find_backend(''' if not (is_torch_available() and is_transformers_available()):''' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , '''torch_and_transformers''' ) # double_backend_with_underscore = find_backend( # " if not (is_sentencepiece_available() and is_tensorflow_text_available()):" # ) # self.assertEqual(double_backend_with_underscore, "sentencepiece_and_tensorflow_text") __lowerCamelCase = find_backend( ''' if not (is_torch_available() and is_transformers_available() and is_onnx_available()):''' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , '''torch_and_transformers_and_onnx''' ) def __A ( self : Optional[int] ) -> Union[str, Any]: __lowerCamelCase = read_init() # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects self.assertIn('''torch''' , SCREAMING_SNAKE_CASE__ ) self.assertIn('''torch_and_transformers''' , SCREAMING_SNAKE_CASE__ ) self.assertIn('''flax_and_transformers''' , SCREAMING_SNAKE_CASE__ ) self.assertIn('''torch_and_transformers_and_onnx''' , SCREAMING_SNAKE_CASE__ ) # Likewise, we can't assert on the exact content of a key self.assertIn('''UNet2DModel''' , objects['''torch'''] ) self.assertIn('''FlaxUNet2DConditionModel''' , objects['''flax'''] ) self.assertIn('''StableDiffusionPipeline''' , objects['''torch_and_transformers'''] ) self.assertIn('''FlaxStableDiffusionPipeline''' , objects['''flax_and_transformers'''] ) self.assertIn('''LMSDiscreteScheduler''' , objects['''torch_and_scipy'''] ) self.assertIn('''OnnxStableDiffusionPipeline''' , objects['''torch_and_transformers_and_onnx'''] ) def __A ( self : Tuple ) -> List[Any]: __lowerCamelCase = create_dummy_object('''CONSTANT''' , '''\'torch\'''' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , '''\nCONSTANT = None\n''' ) __lowerCamelCase = create_dummy_object('''function''' , '''\'torch\'''' ) self.assertEqual( SCREAMING_SNAKE_CASE__ , '''\ndef function(*args, **kwargs):\n requires_backends(function, \'torch\')\n''' ) __lowerCamelCase = ''' class FakeClass(metaclass=DummyObject): _backends = \'torch\' def __init__(self, *args, **kwargs): requires_backends(self, \'torch\') @classmethod def from_config(cls, *args, **kwargs): requires_backends(cls, \'torch\') @classmethod def from_pretrained(cls, *args, **kwargs): requires_backends(cls, \'torch\') ''' __lowerCamelCase = create_dummy_object('''FakeClass''' , '''\'torch\'''' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[Any] ) -> Union[str, Any]: __lowerCamelCase = '''# This file is autogenerated by the command `make fix-copies`, do not edit. from ..utils import DummyObject, requires_backends CONSTANT = None def function(*args, **kwargs): requires_backends(function, ["torch"]) class FakeClass(metaclass=DummyObject): _backends = ["torch"] def __init__(self, *args, **kwargs): requires_backends(self, ["torch"]) @classmethod def from_config(cls, *args, **kwargs): requires_backends(cls, ["torch"]) @classmethod def from_pretrained(cls, *args, **kwargs): requires_backends(cls, ["torch"]) ''' __lowerCamelCase = create_dummy_files({'''torch''': ['''CONSTANT''', '''function''', '''FakeClass''']} ) self.assertEqual(dummy_files['''torch'''] , SCREAMING_SNAKE_CASE__ )
368
import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated SCREAMING_SNAKE_CASE__ : Tuple = collections.namedtuple("_Datasets", ["train", "validation", "test"]) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ SCREAMING_SNAKE_CASE__ : List[str] = "https://storage.googleapis.com/cvdf-datasets/mnist/" def __magic_name__ ( __lowerCAmelCase : Any ) -> int: __lowerCamelCase = numpy.dtype(numpy.uintaa ).newbyteorder('''>''' ) return numpy.frombuffer(bytestream.read(4 ) , dtype=__lowerCAmelCase )[0] @deprecated(__lowerCAmelCase , '''Please use tf.data to implement this functionality.''' ) def __magic_name__ ( __lowerCAmelCase : List[Any] ) -> str: print('''Extracting''' , f.name ) with gzip.GzipFile(fileobj=__lowerCAmelCase ) as bytestream: __lowerCamelCase = _readaa(__lowerCAmelCase ) if magic != 2051: raise ValueError( '''Invalid magic number %d in MNIST image file: %s''' % (magic, f.name) ) __lowerCamelCase = _readaa(__lowerCAmelCase ) __lowerCamelCase = _readaa(__lowerCAmelCase ) __lowerCamelCase = _readaa(__lowerCAmelCase ) __lowerCamelCase = bytestream.read(rows * cols * num_images ) __lowerCamelCase = numpy.frombuffer(__lowerCAmelCase , dtype=numpy.uinta ) __lowerCamelCase = data.reshape(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , 1 ) return data @deprecated(__lowerCAmelCase , '''Please use tf.one_hot on tensors.''' ) def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : List[Any] ) -> Dict: __lowerCamelCase = labels_dense.shape[0] __lowerCamelCase = numpy.arange(__lowerCAmelCase ) * num_classes __lowerCamelCase = numpy.zeros((num_labels, num_classes) ) __lowerCamelCase = 1 return labels_one_hot @deprecated(__lowerCAmelCase , '''Please use tf.data to implement this functionality.''' ) def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : str=False , __lowerCAmelCase : List[str]=10 ) -> List[str]: print('''Extracting''' , f.name ) with gzip.GzipFile(fileobj=__lowerCAmelCase ) as bytestream: __lowerCamelCase = _readaa(__lowerCAmelCase ) if magic != 2049: raise ValueError( '''Invalid magic number %d in MNIST label file: %s''' % (magic, f.name) ) __lowerCamelCase = _readaa(__lowerCAmelCase ) __lowerCamelCase = bytestream.read(__lowerCAmelCase ) __lowerCamelCase = numpy.frombuffer(__lowerCAmelCase , dtype=numpy.uinta ) if one_hot: return _dense_to_one_hot(__lowerCAmelCase , __lowerCAmelCase ) return labels class lowerCAmelCase__ : @deprecated( SCREAMING_SNAKE_CASE__ , '''Please use alternatives such as official/mnist/_DataSet.py''' ''' from tensorflow/models.''' , ) def __init__( self : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : List[str]=False , SCREAMING_SNAKE_CASE__ : str=dtypes.floataa , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : str=None , ) -> Optional[int]: __lowerCamelCase , __lowerCamelCase = random_seed.get_seed(SCREAMING_SNAKE_CASE__ ) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seeda if seed is None else seeda ) __lowerCamelCase = dtypes.as_dtype(SCREAMING_SNAKE_CASE__ ).base_dtype if dtype not in (dtypes.uinta, dtypes.floataa): raise TypeError('''Invalid image dtype %r, expected uint8 or float32''' % dtype ) if fake_data: __lowerCamelCase = 1_00_00 __lowerCamelCase = one_hot else: assert ( images.shape[0] == labels.shape[0] ), f'''images.shape: {images.shape} labels.shape: {labels.shape}''' __lowerCamelCase = images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 __lowerCamelCase = images.reshape( images.shape[0] , images.shape[1] * images.shape[2] ) if dtype == dtypes.floataa: # Convert from [0, 255] -> [0.0, 1.0]. __lowerCamelCase = images.astype(numpy.floataa ) __lowerCamelCase = numpy.multiply(SCREAMING_SNAKE_CASE__ , 1.0 / 255.0 ) __lowerCamelCase = images __lowerCamelCase = labels __lowerCamelCase = 0 __lowerCamelCase = 0 @property def __A ( self : str ) -> Optional[int]: return self._images @property def __A ( self : Any ) -> Dict: return self._labels @property def __A ( self : List[Any] ) -> int: return self._num_examples @property def __A ( self : str ) -> Any: return self._epochs_completed def __A ( self : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : str=True ) -> str: if fake_data: __lowerCamelCase = [1] * 7_84 __lowerCamelCase = [1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(SCREAMING_SNAKE_CASE__ )], [fake_label for _ in range(SCREAMING_SNAKE_CASE__ )], ) __lowerCamelCase = self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: __lowerCamelCase = numpy.arange(self._num_examples ) numpy.random.shuffle(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.images[perma] __lowerCamelCase = self.labels[perma] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch __lowerCamelCase = self._num_examples - start __lowerCamelCase = self._images[start : self._num_examples] __lowerCamelCase = self._labels[start : self._num_examples] # Shuffle the data if shuffle: __lowerCamelCase = numpy.arange(self._num_examples ) numpy.random.shuffle(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.images[perm] __lowerCamelCase = self.labels[perm] # Start next epoch __lowerCamelCase = 0 __lowerCamelCase = batch_size - rest_num_examples __lowerCamelCase = self._index_in_epoch __lowerCamelCase = self._images[start:end] __lowerCamelCase = self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part) , axis=0 ), numpy.concatenate((labels_rest_part, labels_new_part) , axis=0 ), ) else: self._index_in_epoch += batch_size __lowerCamelCase = self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(__lowerCAmelCase , '''Please write your own downloading logic.''' ) def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int , __lowerCAmelCase : Union[str, Any] ) -> List[Any]: if not gfile.Exists(__lowerCAmelCase ): gfile.MakeDirs(__lowerCAmelCase ) __lowerCamelCase = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) if not gfile.Exists(__lowerCAmelCase ): urllib.request.urlretrieve(__lowerCAmelCase , __lowerCAmelCase ) # noqa: S310 with gfile.GFile(__lowerCAmelCase ) as f: __lowerCamelCase = f.size() print('''Successfully downloaded''' , __lowerCAmelCase , __lowerCAmelCase , '''bytes.''' ) return filepath @deprecated( __lowerCAmelCase , '''Please use alternatives such as:''' ''' tensorflow_datasets.load(\'mnist\')''' ) def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[Any]=False , __lowerCAmelCase : Dict=False , __lowerCAmelCase : List[str]=dtypes.floataa , __lowerCAmelCase : Union[str, Any]=True , __lowerCAmelCase : int=5000 , __lowerCAmelCase : Any=None , __lowerCAmelCase : List[str]=DEFAULT_SOURCE_URL , ) -> Optional[Any]: if fake_data: def fake(): return _DataSet( [] , [] , fake_data=__lowerCAmelCase , one_hot=__lowerCAmelCase , dtype=__lowerCAmelCase , seed=__lowerCAmelCase ) __lowerCamelCase = fake() __lowerCamelCase = fake() __lowerCamelCase = fake() return _Datasets(train=__lowerCAmelCase , validation=__lowerCAmelCase , test=__lowerCAmelCase ) if not source_url: # empty string check __lowerCamelCase = DEFAULT_SOURCE_URL __lowerCamelCase = '''train-images-idx3-ubyte.gz''' __lowerCamelCase = '''train-labels-idx1-ubyte.gz''' __lowerCamelCase = '''t10k-images-idx3-ubyte.gz''' __lowerCamelCase = '''t10k-labels-idx1-ubyte.gz''' __lowerCamelCase = _maybe_download( __lowerCAmelCase , __lowerCAmelCase , source_url + train_images_file ) with gfile.Open(__lowerCAmelCase , '''rb''' ) as f: __lowerCamelCase = _extract_images(__lowerCAmelCase ) __lowerCamelCase = _maybe_download( __lowerCAmelCase , __lowerCAmelCase , source_url + train_labels_file ) with gfile.Open(__lowerCAmelCase , '''rb''' ) as f: __lowerCamelCase = _extract_labels(__lowerCAmelCase , one_hot=__lowerCAmelCase ) __lowerCamelCase = _maybe_download( __lowerCAmelCase , __lowerCAmelCase , source_url + test_images_file ) with gfile.Open(__lowerCAmelCase , '''rb''' ) as f: __lowerCamelCase = _extract_images(__lowerCAmelCase ) __lowerCamelCase = _maybe_download( __lowerCAmelCase , __lowerCAmelCase , source_url + test_labels_file ) with gfile.Open(__lowerCAmelCase , '''rb''' ) as f: __lowerCamelCase = _extract_labels(__lowerCAmelCase , one_hot=__lowerCAmelCase ) if not 0 <= validation_size <= len(__lowerCAmelCase ): __lowerCamelCase = ( '''Validation size should be between 0 and ''' f'''{len(__lowerCAmelCase )}. Received: {validation_size}.''' ) raise ValueError(__lowerCAmelCase ) __lowerCamelCase = train_images[:validation_size] __lowerCamelCase = train_labels[:validation_size] __lowerCamelCase = train_images[validation_size:] __lowerCamelCase = train_labels[validation_size:] __lowerCamelCase = {'''dtype''': dtype, '''reshape''': reshape, '''seed''': seed} __lowerCamelCase = _DataSet(__lowerCAmelCase , __lowerCAmelCase , **__lowerCAmelCase ) __lowerCamelCase = _DataSet(__lowerCAmelCase , __lowerCAmelCase , **__lowerCAmelCase ) __lowerCamelCase = _DataSet(__lowerCAmelCase , __lowerCAmelCase , **__lowerCAmelCase ) return _Datasets(train=__lowerCAmelCase , validation=__lowerCAmelCase , test=__lowerCAmelCase )
339
0
import math from collections import defaultdict 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 KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def __magic_name__ ( __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : List[str]=0.999 , __lowerCAmelCase : int="cosine" , ) -> int: if alpha_transform_type == "cosine": def alpha_bar_fn(__lowerCAmelCase : int ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(__lowerCAmelCase : List[Any] ): return math.exp(t * -12.0 ) else: raise ValueError(f'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) __lowerCamelCase = [] for i in range(__lowerCAmelCase ): __lowerCamelCase = i / num_diffusion_timesteps __lowerCamelCase = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(__lowerCAmelCase ) / alpha_bar_fn(__lowerCAmelCase ) , __lowerCAmelCase ) ) return torch.tensor(__lowerCAmelCase , dtype=torch.floataa ) class lowerCAmelCase__ ( __lowercase , __lowercase ): a__ : Any = [e.name for e in KarrasDiffusionSchedulers] a__ : Tuple = 2 @register_to_config def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : int = 10_00 , SCREAMING_SNAKE_CASE__ : float = 0.00085 , SCREAMING_SNAKE_CASE__ : float = 0.012 , SCREAMING_SNAKE_CASE__ : str = "linear" , SCREAMING_SNAKE_CASE__ : Optional[Union[np.ndarray, List[float]]] = None , SCREAMING_SNAKE_CASE__ : str = "epsilon" , SCREAMING_SNAKE_CASE__ : Optional[bool] = False , SCREAMING_SNAKE_CASE__ : Optional[bool] = False , SCREAMING_SNAKE_CASE__ : float = 1.0 , SCREAMING_SNAKE_CASE__ : str = "linspace" , SCREAMING_SNAKE_CASE__ : int = 0 , ) -> List[str]: if trained_betas is not None: __lowerCamelCase = torch.tensor(SCREAMING_SNAKE_CASE__ , dtype=torch.floataa ) elif beta_schedule == "linear": __lowerCamelCase = torch.linspace(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. __lowerCamelCase = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , SCREAMING_SNAKE_CASE__ , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule __lowerCamelCase = betas_for_alpha_bar(SCREAMING_SNAKE_CASE__ , alpha_transform_type='''cosine''' ) elif beta_schedule == "exp": __lowerCamelCase = betas_for_alpha_bar(SCREAMING_SNAKE_CASE__ , alpha_transform_type='''exp''' ) else: raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}''' ) __lowerCamelCase = 1.0 - self.betas __lowerCamelCase = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = use_karras_sigmas def __A ( self : int , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int=None ) -> Optional[int]: if schedule_timesteps is None: __lowerCamelCase = self.timesteps __lowerCamelCase = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: __lowerCamelCase = 1 if len(SCREAMING_SNAKE_CASE__ ) > 1 else 0 else: __lowerCamelCase = timestep.cpu().item() if torch.is_tensor(SCREAMING_SNAKE_CASE__ ) else timestep __lowerCamelCase = self._index_counter[timestep_int] return indices[pos].item() @property def __A ( self : Union[str, Any] ) -> Any: # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def __A ( self : List[str] , SCREAMING_SNAKE_CASE__ : torch.FloatTensor , SCREAMING_SNAKE_CASE__ : Union[float, torch.FloatTensor] , ) -> torch.FloatTensor: __lowerCamelCase = self.index_for_timestep(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.sigmas[step_index] __lowerCamelCase = sample / ((sigma**2 + 1) ** 0.5) return sample def __A ( self : Any , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Union[str, torch.device] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , ) -> Any: __lowerCamelCase = num_inference_steps __lowerCamelCase = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": __lowerCamelCase = np.linspace(0 , num_train_timesteps - 1 , SCREAMING_SNAKE_CASE__ , dtype=SCREAMING_SNAKE_CASE__ )[::-1].copy() elif self.config.timestep_spacing == "leading": __lowerCamelCase = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 __lowerCamelCase = (np.arange(0 , SCREAMING_SNAKE_CASE__ ) * step_ratio).round()[::-1].copy().astype(SCREAMING_SNAKE_CASE__ ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": __lowerCamelCase = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 __lowerCamelCase = (np.arange(SCREAMING_SNAKE_CASE__ , 0 , -step_ratio )).round().copy().astype(SCREAMING_SNAKE_CASE__ ) timesteps -= 1 else: raise ValueError( f'''{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.''' ) __lowerCamelCase = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) __lowerCamelCase = np.log(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = np.interp(SCREAMING_SNAKE_CASE__ , np.arange(0 , len(SCREAMING_SNAKE_CASE__ ) ) , SCREAMING_SNAKE_CASE__ ) if self.config.use_karras_sigmas: __lowerCamelCase = self._convert_to_karras(in_sigmas=SCREAMING_SNAKE_CASE__ , num_inference_steps=self.num_inference_steps ) __lowerCamelCase = np.array([self._sigma_to_t(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for sigma in sigmas] ) __lowerCamelCase = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) __lowerCamelCase = torch.from_numpy(SCREAMING_SNAKE_CASE__ ).to(device=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] ) __lowerCamelCase = torch.from_numpy(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] ) if str(SCREAMING_SNAKE_CASE__ ).startswith('''mps''' ): # mps does not support float64 __lowerCamelCase = timesteps.to(SCREAMING_SNAKE_CASE__ , dtype=torch.floataa ) else: __lowerCamelCase = timesteps.to(device=SCREAMING_SNAKE_CASE__ ) # empty dt and derivative __lowerCamelCase = None __lowerCamelCase = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter __lowerCamelCase = defaultdict(SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple ) -> Union[str, Any]: # get log sigma __lowerCamelCase = np.log(SCREAMING_SNAKE_CASE__ ) # get distribution __lowerCamelCase = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range __lowerCamelCase = np.cumsum((dists >= 0) , axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 ) __lowerCamelCase = low_idx + 1 __lowerCamelCase = log_sigmas[low_idx] __lowerCamelCase = log_sigmas[high_idx] # interpolate sigmas __lowerCamelCase = (low - log_sigma) / (low - high) __lowerCamelCase = np.clip(SCREAMING_SNAKE_CASE__ , 0 , 1 ) # transform interpolation to time range __lowerCamelCase = (1 - w) * low_idx + w * high_idx __lowerCamelCase = t.reshape(sigma.shape ) return t def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : torch.FloatTensor , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> torch.FloatTensor: __lowerCamelCase = in_sigmas[-1].item() __lowerCamelCase = in_sigmas[0].item() __lowerCamelCase = 7.0 # 7.0 is the value used in the paper __lowerCamelCase = np.linspace(0 , 1 , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = sigma_min ** (1 / rho) __lowerCamelCase = sigma_max ** (1 / rho) __lowerCamelCase = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas @property def __A ( self : str ) -> Tuple: return self.dt is None def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[torch.FloatTensor, np.ndarray] , SCREAMING_SNAKE_CASE__ : Union[float, torch.FloatTensor] , SCREAMING_SNAKE_CASE__ : Union[torch.FloatTensor, np.ndarray] , SCREAMING_SNAKE_CASE__ : bool = True , ) -> Union[SchedulerOutput, Tuple]: __lowerCamelCase = self.index_for_timestep(SCREAMING_SNAKE_CASE__ ) # advance index counter by 1 __lowerCamelCase = timestep.cpu().item() if torch.is_tensor(SCREAMING_SNAKE_CASE__ ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: __lowerCamelCase = self.sigmas[step_index] __lowerCamelCase = self.sigmas[step_index + 1] else: # 2nd order / Heun's method __lowerCamelCase = self.sigmas[step_index - 1] __lowerCamelCase = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API __lowerCamelCase = 0 __lowerCamelCase = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": __lowerCamelCase = sigma_hat if self.state_in_first_order else sigma_next __lowerCamelCase = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": __lowerCamelCase = sigma_hat if self.state_in_first_order else sigma_next __lowerCamelCase = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": __lowerCamelCase = model_output else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`''' ) if self.config.clip_sample: __lowerCamelCase = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order __lowerCamelCase = (sample - pred_original_sample) / sigma_hat # 3. delta timestep __lowerCamelCase = sigma_next - sigma_hat # store for 2nd order step __lowerCamelCase = derivative __lowerCamelCase = dt __lowerCamelCase = sample else: # 2. 2nd order / Heun's method __lowerCamelCase = (sample - pred_original_sample) / sigma_next __lowerCamelCase = (self.prev_derivative + derivative) / 2 # 3. take prev timestep & sample __lowerCamelCase = self.dt __lowerCamelCase = self.sample # free dt and derivative # Note, this puts the scheduler in "first order mode" __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=SCREAMING_SNAKE_CASE__ ) def __A ( self : Any , SCREAMING_SNAKE_CASE__ : torch.FloatTensor , SCREAMING_SNAKE_CASE__ : torch.FloatTensor , SCREAMING_SNAKE_CASE__ : torch.FloatTensor , ) -> torch.FloatTensor: # Make sure sigmas and timesteps have the same device and dtype as original_samples __lowerCamelCase = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(SCREAMING_SNAKE_CASE__ ): # mps does not support float64 __lowerCamelCase = self.timesteps.to(original_samples.device , dtype=torch.floataa ) __lowerCamelCase = timesteps.to(original_samples.device , dtype=torch.floataa ) else: __lowerCamelCase = self.timesteps.to(original_samples.device ) __lowerCamelCase = timesteps.to(original_samples.device ) __lowerCamelCase = [self.index_for_timestep(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for t in timesteps] __lowerCamelCase = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): __lowerCamelCase = sigma.unsqueeze(-1 ) __lowerCamelCase = original_samples + noise * sigma return noisy_samples def __len__( self : List[Any] ) -> Tuple: return self.config.num_train_timesteps
369
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_squeezebert import SqueezeBertTokenizer SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Dict = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "vocab_file": { "squeezebert/squeezebert-uncased": ( "https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt" ), "squeezebert/squeezebert-mnli": "https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt", "squeezebert/squeezebert-mnli-headless": ( "https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt" ), }, "tokenizer_file": { "squeezebert/squeezebert-uncased": ( "https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/tokenizer.json" ), "squeezebert/squeezebert-mnli": ( "https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/tokenizer.json" ), "squeezebert/squeezebert-mnli-headless": ( "https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/tokenizer.json" ), }, } SCREAMING_SNAKE_CASE__ : List[Any] = { "squeezebert/squeezebert-uncased": 512, "squeezebert/squeezebert-mnli": 512, "squeezebert/squeezebert-mnli-headless": 512, } SCREAMING_SNAKE_CASE__ : Dict = { "squeezebert/squeezebert-uncased": {"do_lower_case": True}, "squeezebert/squeezebert-mnli": {"do_lower_case": True}, "squeezebert/squeezebert-mnli-headless": {"do_lower_case": True}, } class lowerCAmelCase__ ( __lowercase ): a__ : Optional[int] = VOCAB_FILES_NAMES a__ : Any = PRETRAINED_VOCAB_FILES_MAP a__ : Union[str, Any] = PRETRAINED_INIT_CONFIGURATION a__ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ : Optional[Any] = SqueezeBertTokenizer def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[UNK]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[PAD]" , SCREAMING_SNAKE_CASE__ : Tuple="[CLS]" , SCREAMING_SNAKE_CASE__ : str="[MASK]" , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : int=None , **SCREAMING_SNAKE_CASE__ : Dict , ) -> Optional[Any]: super().__init__( SCREAMING_SNAKE_CASE__ , tokenizer_file=SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , tokenize_chinese_chars=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = 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 ): __lowerCamelCase = getattr(SCREAMING_SNAKE_CASE__ , normalizer_state.pop('''type''' ) ) __lowerCamelCase = do_lower_case __lowerCamelCase = strip_accents __lowerCamelCase = tokenize_chinese_chars __lowerCamelCase = normalizer_class(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = do_lower_case def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[str]=None ) -> str: __lowerCamelCase = [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 : Tuple , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: __lowerCamelCase = [self.sep_token_id] __lowerCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __A ( self : int , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: __lowerCamelCase = self._tokenizer.model.save(SCREAMING_SNAKE_CASE__ , name=SCREAMING_SNAKE_CASE__ ) return tuple(SCREAMING_SNAKE_CASE__ )
339
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) SCREAMING_SNAKE_CASE__ : List[Any] = { "configuration_gpt_bigcode": ["GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTBigCodeConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Any = [ "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 SCREAMING_SNAKE_CASE__ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
370
from __future__ import annotations def __magic_name__ ( __lowerCAmelCase : list[int] ) -> bool: return len(set(__lowerCAmelCase ) ) == len(__lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
339
0
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCAmelCase__ ( __lowercase ): a__ : List[Any] = """ClapFeatureExtractor""" a__ : int = ("""RobertaTokenizer""", """RobertaTokenizerFast""") def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: super().__init__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __call__( self : List[str] , SCREAMING_SNAKE_CASE__ : Tuple=None , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : Tuple=None , **SCREAMING_SNAKE_CASE__ : int ) -> Any: __lowerCamelCase = kwargs.pop('''sampling_rate''' , SCREAMING_SNAKE_CASE__ ) if text is None and audios is None: raise ValueError('''You have to specify either text or audios. Both cannot be none.''' ) if text is not None: __lowerCamelCase = self.tokenizer(SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if audios is not None: __lowerCamelCase = self.feature_extractor( SCREAMING_SNAKE_CASE__ , sampling_rate=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if text is not None and audios is not None: __lowerCamelCase = audio_features.input_features return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**SCREAMING_SNAKE_CASE__ ) , tensor_type=SCREAMING_SNAKE_CASE__ ) def __A ( self : str , *SCREAMING_SNAKE_CASE__ : List[str] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[str]: return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def __A ( self : str , *SCREAMING_SNAKE_CASE__ : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : Dict ) -> List[Any]: return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) @property def __A ( self : List[Any] ) -> Optional[Any]: __lowerCamelCase = self.tokenizer.model_input_names __lowerCamelCase = self.feature_extractor.model_input_names return list(dict.fromkeys(tokenizer_input_names + feature_extractor_input_names ) )
371
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) SCREAMING_SNAKE_CASE__ : Dict = { "configuration_falcon": ["FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP", "FalconConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Tuple = [ "FALCON_PRETRAINED_MODEL_ARCHIVE_LIST", "FalconForCausalLM", "FalconModel", "FalconPreTrainedModel", "FalconForSequenceClassification", "FalconForTokenClassification", "FalconForQuestionAnswering", ] if TYPE_CHECKING: from .configuration_falcon import FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP, FalconConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_falcon import ( FALCON_PRETRAINED_MODEL_ARCHIVE_LIST, FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, FalconPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
339
0
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class A_ ( _a ): lowerCAmelCase__ = ['image_processor', 'tokenizer'] lowerCAmelCase__ = 'CLIPImageProcessor' lowerCAmelCase__ = ('CLIPTokenizer', 'CLIPTokenizerFast') def __init__( self: int ,__lowerCAmelCase: List[Any]=None ,__lowerCAmelCase: Any=None ,**__lowerCAmelCase: Optional[int] ): '''simple docstring''' _lowerCamelCase : Union[str, Any] = None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." ,__lowerCAmelCase ,) _lowerCamelCase : List[str] = 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__(__lowerCAmelCase ,__lowerCAmelCase ) def __call__( self: Optional[int] ,__lowerCAmelCase: Any=None ,__lowerCAmelCase: int=None ,__lowerCAmelCase: int=None ,**__lowerCAmelCase: Union[str, Any] ): '''simple docstring''' if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none." ) if text is not None: _lowerCamelCase : List[Any] = self.tokenizer(__lowerCAmelCase ,return_tensors=__lowerCAmelCase ,**__lowerCAmelCase ) if images is not None: _lowerCamelCase : str = self.image_processor(__lowerCAmelCase ,return_tensors=__lowerCAmelCase ,**__lowerCAmelCase ) if text is not None and images is not None: _lowerCamelCase : List[Any] = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__lowerCAmelCase ) ,tensor_type=__lowerCAmelCase ) def _lowercase ( self: int ,*__lowerCAmelCase: List[str] ,**__lowerCAmelCase: Any ): '''simple docstring''' return self.tokenizer.batch_decode(*__lowerCAmelCase ,**__lowerCAmelCase ) def _lowercase ( self: Any ,*__lowerCAmelCase: Optional[int] ,**__lowerCAmelCase: List[str] ): '''simple docstring''' return self.tokenizer.decode(*__lowerCAmelCase ,**__lowerCAmelCase ) @property def _lowercase ( self: List[str] ): '''simple docstring''' _lowerCamelCase : Tuple = self.tokenizer.model_input_names _lowerCamelCase : List[str] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def _lowercase ( self: Optional[Any] ): '''simple docstring''' warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." ,__lowerCAmelCase ,) return self.image_processor_class @property def _lowercase ( self: Union[str, Any] ): '''simple docstring''' warnings.warn( "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead." ,__lowerCAmelCase ,) return self.image_processor
340
"""simple docstring""" from collections import defaultdict def lowerCamelCase_( _lowerCamelCase ) -> int: '''simple docstring''' _lowerCamelCase : Optional[int] = 1 _lowerCamelCase : str = True for v in tree[start]: if v not in visited: ret += dfs(_lowerCamelCase ) if ret % 2 == 0: cuts.append(_lowerCamelCase ) return ret def lowerCamelCase_( ) -> int: '''simple docstring''' dfs(1 ) if __name__ == "__main__": _lowerCAmelCase , _lowerCAmelCase : Optional[Any] = 10, 9 _lowerCAmelCase : str = defaultdict(list) _lowerCAmelCase : dict[int, bool] = {} _lowerCAmelCase : list[int] = [] _lowerCAmelCase : Any = 0 _lowerCAmelCase : Any = [(2, 1), (3, 1), (4, 3), (5, 2), (6, 1), (7, 2), (8, 6), (9, 8), (10, 8)] for u, v in edges: tree[u].append(v) tree[v].append(u) even_tree() print(len(cuts) - 1)
340
1
"""simple docstring""" import json import os import pickle import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers import is_faiss_available from transformers.models.bart.configuration_bart import BartConfig from transformers.models.bart.tokenization_bart import BartTokenizer from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES from transformers.models.dpr.configuration_dpr import DPRConfig from transformers.models.dpr.tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer from transformers.models.rag.configuration_rag import RagConfig from transformers.models.rag.retrieval_rag import CustomHFIndex, RagRetriever from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES from transformers.testing_utils import require_faiss, require_sentencepiece, require_tokenizers, require_torch if is_faiss_available(): import faiss @require_faiss class A_ ( _a ): def _lowercase ( self: Optional[int] ): '''simple docstring''' _lowerCamelCase : Dict = tempfile.mkdtemp() _lowerCamelCase : List[str] = 8 # DPR tok _lowerCamelCase : List[Any] = [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] _lowerCamelCase : Any = os.path.join(self.tmpdirname ,"dpr_tokenizer" ) os.makedirs(__lowerCAmelCase ,exist_ok=__lowerCAmelCase ) _lowerCamelCase : Tuple = os.path.join(__lowerCAmelCase ,DPR_VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file ,"w" ,encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) # BART tok _lowerCamelCase : Union[str, Any] = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "\u0120", "\u0120l", "\u0120n", "\u0120lo", "\u0120low", "er", "\u0120lowest", "\u0120newer", "\u0120wider", "<unk>", ] _lowerCamelCase : Optional[Any] = dict(zip(__lowerCAmelCase ,range(len(__lowerCAmelCase ) ) ) ) _lowerCamelCase : int = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""] _lowerCamelCase : List[str] = {"unk_token": "<unk>"} _lowerCamelCase : Optional[int] = os.path.join(self.tmpdirname ,"bart_tokenizer" ) os.makedirs(__lowerCAmelCase ,exist_ok=__lowerCAmelCase ) _lowerCamelCase : Optional[Any] = os.path.join(__lowerCAmelCase ,BART_VOCAB_FILES_NAMES["vocab_file"] ) _lowerCamelCase : Dict = os.path.join(__lowerCAmelCase ,BART_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 ) ) def _lowercase ( self: List[str] ): '''simple docstring''' return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname ,"dpr_tokenizer" ) ) def _lowercase ( self: Optional[Any] ): '''simple docstring''' return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname ,"dpr_tokenizer" ) ) def _lowercase ( self: List[Any] ): '''simple docstring''' return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname ,"bart_tokenizer" ) ) def _lowercase ( self: Any ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def _lowercase ( self: List[str] ): '''simple docstring''' _lowerCamelCase : Any = Dataset.from_dict( { "id": ["0", "1"], "text": ["foo", "bar"], "title": ["Foo", "Bar"], "embeddings": [np.ones(self.retrieval_vector_size ), 2 * np.ones(self.retrieval_vector_size )], } ) dataset.add_faiss_index("embeddings" ,string_factory="Flat" ,metric_type=faiss.METRIC_INNER_PRODUCT ) return dataset def _lowercase ( self: int ): '''simple docstring''' _lowerCamelCase : int = self.get_dummy_dataset() _lowerCamelCase : str = RagConfig( retrieval_vector_size=self.retrieval_vector_size ,question_encoder=DPRConfig().to_dict() ,generator=BartConfig().to_dict() ,) with patch("transformers.models.rag.retrieval_rag.load_dataset" ) as mock_load_dataset: _lowerCamelCase : List[Any] = dataset _lowerCamelCase : Dict = RagRetriever( __lowerCAmelCase ,question_encoder_tokenizer=self.get_dpr_tokenizer() ,generator_tokenizer=self.get_bart_tokenizer() ,) return retriever def _lowercase ( self: List[Any] ,__lowerCAmelCase: bool ): '''simple docstring''' _lowerCamelCase : List[Any] = self.get_dummy_dataset() _lowerCamelCase : Optional[int] = RagConfig( retrieval_vector_size=self.retrieval_vector_size ,question_encoder=DPRConfig().to_dict() ,generator=BartConfig().to_dict() ,index_name="custom" ,) if from_disk: _lowerCamelCase : Union[str, Any] = os.path.join(self.tmpdirname ,"dataset" ) _lowerCamelCase : Optional[int] = os.path.join(self.tmpdirname ,"index.faiss" ) dataset.get_index("embeddings" ).save(os.path.join(self.tmpdirname ,"index.faiss" ) ) dataset.drop_index("embeddings" ) dataset.save_to_disk(os.path.join(self.tmpdirname ,"dataset" ) ) del dataset _lowerCamelCase : Optional[Any] = RagRetriever( __lowerCAmelCase ,question_encoder_tokenizer=self.get_dpr_tokenizer() ,generator_tokenizer=self.get_bart_tokenizer() ,) else: _lowerCamelCase : Optional[Any] = RagRetriever( __lowerCAmelCase ,question_encoder_tokenizer=self.get_dpr_tokenizer() ,generator_tokenizer=self.get_bart_tokenizer() ,index=CustomHFIndex(config.retrieval_vector_size ,__lowerCAmelCase ) ,) return retriever def _lowercase ( self: Union[str, Any] ): '''simple docstring''' _lowerCamelCase : int = Dataset.from_dict( { "id": ["0", "1"], "text": ["foo", "bar"], "title": ["Foo", "Bar"], "embeddings": [np.ones(self.retrieval_vector_size + 1 ), 2 * np.ones(self.retrieval_vector_size + 1 )], } ) dataset.add_faiss_index("embeddings" ,string_factory="Flat" ,metric_type=faiss.METRIC_INNER_PRODUCT ) _lowerCamelCase : str = os.path.join(self.tmpdirname ,"hf_bert_base.hnswSQ8_correct_phi_128.c_index" ) dataset.save_faiss_index("embeddings" ,index_file_name + ".index.dpr" ) pickle.dump(dataset["id"] ,open(index_file_name + ".index_meta.dpr" ,"wb" ) ) _lowerCamelCase : Optional[Any] = os.path.join(self.tmpdirname ,"psgs_w100.tsv.pkl" ) _lowerCamelCase : Optional[int] = {sample["id"]: [sample["text"], sample["title"]] for sample in dataset} pickle.dump(__lowerCAmelCase ,open(__lowerCAmelCase ,"wb" ) ) _lowerCamelCase : Dict = RagConfig( retrieval_vector_size=self.retrieval_vector_size ,question_encoder=DPRConfig().to_dict() ,generator=BartConfig().to_dict() ,index_name="legacy" ,index_path=self.tmpdirname ,) _lowerCamelCase : Optional[Any] = RagRetriever( __lowerCAmelCase ,question_encoder_tokenizer=self.get_dpr_tokenizer() ,generator_tokenizer=self.get_bart_tokenizer() ) return retriever def _lowercase ( self: Tuple ): '''simple docstring''' _lowerCamelCase : str = 1 _lowerCamelCase : Optional[Any] = self.get_dummy_canonical_hf_index_retriever() _lowerCamelCase : int = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] ,dtype=np.floataa ) _lowerCamelCase, _lowerCamelCase, _lowerCamelCase : Optional[Any] = retriever.retrieve(__lowerCAmelCase ,n_docs=__lowerCAmelCase ) self.assertEqual(retrieved_doc_embeds.shape ,(2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(__lowerCAmelCase ) ,2 ) self.assertEqual(sorted(doc_dicts[0] ) ,["embeddings", "id", "text", "title"] ) self.assertEqual(len(doc_dicts[0]["id"] ) ,__lowerCAmelCase ) self.assertEqual(doc_dicts[0]["id"][0] ,"1" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["id"][0] ,"0" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() ,[[1], [0]] ) def _lowercase ( self: str ): '''simple docstring''' _lowerCamelCase : Union[str, Any] = self.get_dummy_canonical_hf_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: with patch("transformers.models.rag.retrieval_rag.load_dataset" ) as mock_load_dataset: _lowerCamelCase : Union[str, Any] = self.get_dummy_dataset() retriever.save_pretrained(__lowerCAmelCase ) _lowerCamelCase : List[Any] = RagRetriever.from_pretrained(__lowerCAmelCase ) self.assertIsInstance(__lowerCAmelCase ,__lowerCAmelCase ) _lowerCamelCase : Tuple = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] ,dtype=np.floataa ) _lowerCamelCase : Any = retriever.retrieve(__lowerCAmelCase ,n_docs=1 ) self.assertTrue(out is not None ) def _lowercase ( self: Dict ): '''simple docstring''' _lowerCamelCase : Tuple = 1 _lowerCamelCase : Union[str, Any] = self.get_dummy_custom_hf_index_retriever(from_disk=__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] ,dtype=np.floataa ) _lowerCamelCase, _lowerCamelCase, _lowerCamelCase : List[Any] = retriever.retrieve(__lowerCAmelCase ,n_docs=__lowerCAmelCase ) self.assertEqual(retrieved_doc_embeds.shape ,(2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(__lowerCAmelCase ) ,2 ) self.assertEqual(sorted(doc_dicts[0] ) ,["embeddings", "id", "text", "title"] ) self.assertEqual(len(doc_dicts[0]["id"] ) ,__lowerCAmelCase ) self.assertEqual(doc_dicts[0]["id"][0] ,"1" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["id"][0] ,"0" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() ,[[1], [0]] ) def _lowercase ( self: Union[str, Any] ): '''simple docstring''' _lowerCamelCase : str = self.get_dummy_custom_hf_index_retriever(from_disk=__lowerCAmelCase ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(__lowerCAmelCase ) _lowerCamelCase : int = RagRetriever.from_pretrained(__lowerCAmelCase ) self.assertIsInstance(__lowerCAmelCase ,__lowerCAmelCase ) _lowerCamelCase : int = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] ,dtype=np.floataa ) _lowerCamelCase : Optional[Any] = retriever.retrieve(__lowerCAmelCase ,n_docs=1 ) self.assertTrue(out is not None ) def _lowercase ( self: Any ): '''simple docstring''' _lowerCamelCase : Optional[int] = 1 _lowerCamelCase : Union[str, Any] = self.get_dummy_custom_hf_index_retriever(from_disk=__lowerCAmelCase ) _lowerCamelCase : Optional[int] = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] ,dtype=np.floataa ) _lowerCamelCase, _lowerCamelCase, _lowerCamelCase : List[Any] = retriever.retrieve(__lowerCAmelCase ,n_docs=__lowerCAmelCase ) self.assertEqual(retrieved_doc_embeds.shape ,(2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(__lowerCAmelCase ) ,2 ) self.assertEqual(sorted(doc_dicts[0] ) ,["embeddings", "id", "text", "title"] ) self.assertEqual(len(doc_dicts[0]["id"] ) ,__lowerCAmelCase ) self.assertEqual(doc_dicts[0]["id"][0] ,"1" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["id"][0] ,"0" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() ,[[1], [0]] ) def _lowercase ( self: Optional[Any] ): '''simple docstring''' _lowerCamelCase : int = self.get_dummy_custom_hf_index_retriever(from_disk=__lowerCAmelCase ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(__lowerCAmelCase ) _lowerCamelCase : str = RagRetriever.from_pretrained(__lowerCAmelCase ) self.assertIsInstance(__lowerCAmelCase ,__lowerCAmelCase ) _lowerCamelCase : Any = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] ,dtype=np.floataa ) _lowerCamelCase : int = retriever.retrieve(__lowerCAmelCase ,n_docs=1 ) self.assertTrue(out is not None ) def _lowercase ( self: Tuple ): '''simple docstring''' _lowerCamelCase : Dict = 1 _lowerCamelCase : Union[str, Any] = self.get_dummy_legacy_index_retriever() _lowerCamelCase : Tuple = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] ,dtype=np.floataa ) _lowerCamelCase, _lowerCamelCase, _lowerCamelCase : str = retriever.retrieve(__lowerCAmelCase ,n_docs=__lowerCAmelCase ) self.assertEqual(retrieved_doc_embeds.shape ,(2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(__lowerCAmelCase ) ,2 ) self.assertEqual(sorted(doc_dicts[0] ) ,["text", "title"] ) self.assertEqual(len(doc_dicts[0]["text"] ) ,__lowerCAmelCase ) self.assertEqual(doc_dicts[0]["text"][0] ,"bar" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["text"][0] ,"foo" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() ,[[1], [0]] ) def _lowercase ( self: Tuple ): '''simple docstring''' _lowerCamelCase : List[str] = self.get_dummy_legacy_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(__lowerCAmelCase ) _lowerCamelCase : int = RagRetriever.from_pretrained(__lowerCAmelCase ) self.assertIsInstance(__lowerCAmelCase ,__lowerCAmelCase ) _lowerCamelCase : int = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] ,dtype=np.floataa ) _lowerCamelCase : List[Any] = retriever.retrieve(__lowerCAmelCase ,n_docs=1 ) self.assertTrue(out is not None ) @require_torch @require_tokenizers @require_sentencepiece def _lowercase ( self: str ): '''simple docstring''' import torch _lowerCamelCase : List[Any] = 1 _lowerCamelCase : Tuple = self.get_dummy_canonical_hf_index_retriever() _lowerCamelCase : List[str] = [[5, 7], [10, 11]] _lowerCamelCase : str = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] ,dtype=np.floataa ) _lowerCamelCase : List[str] = retriever(__lowerCAmelCase ,__lowerCAmelCase ,prefix=retriever.config.generator.prefix ,n_docs=__lowerCAmelCase ) _lowerCamelCase, _lowerCamelCase, _lowerCamelCase : Tuple = ( out["context_input_ids"], out["context_attention_mask"], out["retrieved_doc_embeds"], ) self.assertEqual(retrieved_doc_embeds.shape ,(2, n_docs, self.retrieval_vector_size) ) self.assertIsInstance(__lowerCAmelCase ,__lowerCAmelCase ) self.assertIsInstance(__lowerCAmelCase ,__lowerCAmelCase ) self.assertIsInstance(__lowerCAmelCase ,np.ndarray ) _lowerCamelCase : Union[str, Any] = retriever( __lowerCAmelCase ,__lowerCAmelCase ,prefix=retriever.config.generator.prefix ,n_docs=__lowerCAmelCase ,return_tensors="pt" ,) _lowerCamelCase, _lowerCamelCase, _lowerCamelCase, _lowerCamelCase : Dict = ( # noqa: F841 out["context_input_ids"], out["context_attention_mask"], out["retrieved_doc_embeds"], out["doc_ids"], ) self.assertEqual(retrieved_doc_embeds.shape ,(2, n_docs, self.retrieval_vector_size) ) self.assertIsInstance(__lowerCAmelCase ,torch.Tensor ) self.assertIsInstance(__lowerCAmelCase ,torch.Tensor ) self.assertIsInstance(__lowerCAmelCase ,torch.Tensor ) @require_torch @require_tokenizers @require_sentencepiece def _lowercase ( self: Optional[Any] ): '''simple docstring''' _lowerCamelCase : List[str] = self.get_dpr_ctx_encoder_tokenizer() _lowerCamelCase : Tuple = 1 _lowerCamelCase : List[str] = self.get_dummy_custom_hf_index_retriever(from_disk=__lowerCAmelCase ) retriever.set_ctx_encoder_tokenizer(__lowerCAmelCase ) _lowerCamelCase : Any = [[5, 7], [10, 11]] _lowerCamelCase : List[Any] = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] ,dtype=np.floataa ) _lowerCamelCase : List[Any] = retriever(__lowerCAmelCase ,__lowerCAmelCase ,prefix=retriever.config.generator.prefix ,n_docs=__lowerCAmelCase ) self.assertEqual( len(__lowerCAmelCase ) ,6 ) # check whether the retriever output consist of 6 attributes including tokenized docs self.assertEqual( all(k in out for k in ("tokenized_doc_ids", "tokenized_doc_attention_mask") ) ,__lowerCAmelCase ) # check for doc token related keys in dictionary.
340
"""simple docstring""" import time from contextlib import contextmanager from pathlib import Path import pytest import requests from huggingface_hub.hf_api import HfApi, HfFolder _lowerCAmelCase : Optional[int] = '''__DUMMY_TRANSFORMERS_USER__''' _lowerCAmelCase : Dict = '''Dummy User''' _lowerCAmelCase : Optional[int] = '''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''' _lowerCAmelCase : Tuple = '''https://hub-ci.huggingface.co''' _lowerCAmelCase : Any = CI_HUB_ENDPOINT + '''/datasets/{repo_id}/resolve/{revision}/{path}''' _lowerCAmelCase : Tuple = CI_HUB_ENDPOINT + '''/{repo_id}/resolve/{revision}/{filename}''' _lowerCAmelCase : Dict = Path('''~/.huggingface/hub_ci_token''').expanduser() @pytest.fixture def lowerCamelCase_( _lowerCamelCase ) -> Optional[Any]: '''simple docstring''' monkeypatch.setattr( "huggingface_hub.file_download.HUGGINGFACE_CO_URL_TEMPLATE" , _lowerCamelCase ) @pytest.fixture def lowerCamelCase_( _lowerCamelCase ) -> Tuple: '''simple docstring''' monkeypatch.setattr("datasets.config.HF_ENDPOINT" , _lowerCamelCase ) monkeypatch.setattr("datasets.config.HUB_DATASETS_URL" , _lowerCamelCase ) @pytest.fixture def lowerCamelCase_( _lowerCamelCase ) -> Optional[Any]: '''simple docstring''' monkeypatch.setattr("huggingface_hub.hf_api.HfFolder.path_token" , _lowerCamelCase ) @pytest.fixture def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase ) -> Dict: '''simple docstring''' HfFolder.save_token(_lowerCamelCase ) yield HfFolder.delete_token() @pytest.fixture(scope="session" ) def lowerCamelCase_( ) -> str: '''simple docstring''' return HfApi(endpoint=_lowerCamelCase ) @pytest.fixture(scope="session" ) def lowerCamelCase_( _lowerCamelCase ) -> int: '''simple docstring''' _lowerCamelCase : Dict = HfFolder.get_token() HfFolder.save_token(_lowerCamelCase ) yield CI_HUB_USER_TOKEN if previous_token is not None: HfFolder.save_token(_lowerCamelCase ) @pytest.fixture def lowerCamelCase_( _lowerCamelCase ) -> Optional[Any]: '''simple docstring''' def _cleanup_repo(_lowerCamelCase ): hf_api.delete_repo(_lowerCamelCase , token=_lowerCamelCase , repo_type="dataset" ) return _cleanup_repo @pytest.fixture def lowerCamelCase_( _lowerCamelCase ) -> List[str]: '''simple docstring''' @contextmanager def _temporary_repo(_lowerCamelCase ): try: yield repo_id finally: cleanup_repo(_lowerCamelCase ) return _temporary_repo @pytest.fixture(scope="session" ) def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) -> Optional[Any]: '''simple docstring''' _lowerCamelCase : Tuple = F"""repo_txt_data-{int(time.time() * 10e3 )}""" _lowerCamelCase : List[str] = F"""{CI_HUB_USER}/{repo_name}""" hf_api.create_repo(_lowerCamelCase , token=_lowerCamelCase , repo_type="dataset" , private=_lowerCamelCase ) hf_api.upload_file( token=_lowerCamelCase , path_or_fileobj=str(_lowerCamelCase ) , path_in_repo="data/text_data.txt" , repo_id=_lowerCamelCase , repo_type="dataset" , ) yield repo_id try: hf_api.delete_repo(_lowerCamelCase , token=_lowerCamelCase , repo_type="dataset" ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) -> str: '''simple docstring''' return hf_private_dataset_repo_txt_data_ @pytest.fixture(scope="session" ) def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) -> str: '''simple docstring''' _lowerCamelCase : List[Any] = F"""repo_zipped_txt_data-{int(time.time() * 10e3 )}""" _lowerCamelCase : Dict = F"""{CI_HUB_USER}/{repo_name}""" hf_api.create_repo(_lowerCamelCase , token=_lowerCamelCase , repo_type="dataset" , private=_lowerCamelCase ) hf_api.upload_file( token=_lowerCamelCase , path_or_fileobj=str(_lowerCamelCase ) , path_in_repo="data.zip" , repo_id=_lowerCamelCase , repo_type="dataset" , ) yield repo_id try: hf_api.delete_repo(_lowerCamelCase , token=_lowerCamelCase , repo_type="dataset" ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) -> Dict: '''simple docstring''' return hf_private_dataset_repo_zipped_txt_data_ @pytest.fixture(scope="session" ) def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) -> List[Any]: '''simple docstring''' _lowerCamelCase : Any = F"""repo_zipped_img_data-{int(time.time() * 10e3 )}""" _lowerCamelCase : List[Any] = F"""{CI_HUB_USER}/{repo_name}""" hf_api.create_repo(_lowerCamelCase , token=_lowerCamelCase , repo_type="dataset" , private=_lowerCamelCase ) hf_api.upload_file( token=_lowerCamelCase , path_or_fileobj=str(_lowerCamelCase ) , path_in_repo="data.zip" , repo_id=_lowerCamelCase , repo_type="dataset" , ) yield repo_id try: hf_api.delete_repo(_lowerCamelCase , token=_lowerCamelCase , repo_type="dataset" ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) -> Optional[Any]: '''simple docstring''' return hf_private_dataset_repo_zipped_img_data_
340
1
"""simple docstring""" from decimal import Decimal, getcontext from math import ceil, factorial def lowerCamelCase_( _lowerCamelCase ) -> str: '''simple docstring''' if not isinstance(_lowerCamelCase , _lowerCamelCase ): raise TypeError("Undefined for non-integers" ) elif precision < 1: raise ValueError("Undefined for non-natural numbers" ) _lowerCamelCase : int = precision _lowerCamelCase : Dict = ceil(precision / 14 ) _lowerCamelCase : Optional[Any] = 426880 * Decimal(10005 ).sqrt() _lowerCamelCase : int = 1 _lowerCamelCase : Optional[int] = 13591409 _lowerCamelCase : int = Decimal(_lowerCamelCase ) for k in range(1 , _lowerCamelCase ): _lowerCamelCase : Union[str, Any] = factorial(6 * k ) // (factorial(3 * k ) * factorial(_lowerCamelCase ) ** 3) linear_term += 545140134 exponential_term *= -262537412640768000 partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term return str(constant_term / partial_sum )[:-1] if __name__ == "__main__": _lowerCAmelCase : Union[str, Any] = 50 print(f'''The first {n} digits of pi is: {pi(n)}''')
340
"""simple docstring""" import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from ...models.controlnet import ControlNetModel, ControlNetOutput from ...models.modeling_utils import ModelMixin from ...utils import logging _lowerCAmelCase : Dict = logging.get_logger(__name__) class A_ ( _a ): def __init__( self: List[Any] ,__lowerCAmelCase: Union[List[ControlNetModel], Tuple[ControlNetModel]] ): '''simple docstring''' super().__init__() _lowerCamelCase : Tuple = nn.ModuleList(__lowerCAmelCase ) def _lowercase ( self: Union[str, Any] ,__lowerCAmelCase: torch.FloatTensor ,__lowerCAmelCase: Union[torch.Tensor, float, int] ,__lowerCAmelCase: torch.Tensor ,__lowerCAmelCase: List[torch.tensor] ,__lowerCAmelCase: List[float] ,__lowerCAmelCase: Optional[torch.Tensor] = None ,__lowerCAmelCase: Optional[torch.Tensor] = None ,__lowerCAmelCase: Optional[torch.Tensor] = None ,__lowerCAmelCase: Optional[Dict[str, Any]] = None ,__lowerCAmelCase: bool = False ,__lowerCAmelCase: bool = True ,): '''simple docstring''' for i, (image, scale, controlnet) in enumerate(zip(__lowerCAmelCase ,__lowerCAmelCase ,self.nets ) ): _lowerCamelCase, _lowerCamelCase : Union[str, Any] = controlnet( __lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ,) # merge samples if i == 0: _lowerCamelCase, _lowerCamelCase : Optional[Any] = down_samples, mid_sample else: _lowerCamelCase : Optional[int] = [ samples_prev + samples_curr for samples_prev, samples_curr in zip(__lowerCAmelCase ,__lowerCAmelCase ) ] mid_block_res_sample += mid_sample return down_block_res_samples, mid_block_res_sample def _lowercase ( self: Union[str, Any] ,__lowerCAmelCase: Union[str, os.PathLike] ,__lowerCAmelCase: bool = True ,__lowerCAmelCase: Callable = None ,__lowerCAmelCase: bool = False ,__lowerCAmelCase: Optional[str] = None ,): '''simple docstring''' _lowerCamelCase : List[Any] = 0 _lowerCamelCase : str = save_directory for controlnet in self.nets: controlnet.save_pretrained( __lowerCAmelCase ,is_main_process=__lowerCAmelCase ,save_function=__lowerCAmelCase ,safe_serialization=__lowerCAmelCase ,variant=__lowerCAmelCase ,) idx += 1 _lowerCamelCase : int = model_path_to_save + F"""_{idx}""" @classmethod def _lowercase ( cls: Any ,__lowerCAmelCase: Optional[Union[str, os.PathLike]] ,**__lowerCAmelCase: int ): '''simple docstring''' _lowerCamelCase : int = 0 _lowerCamelCase : str = [] # load controlnet and append to list until no controlnet directory exists anymore # first controlnet has to be saved under `./mydirectory/controlnet` to be compliant with `DiffusionPipeline.from_prertained` # second, third, ... controlnets have to be saved under `./mydirectory/controlnet_1`, `./mydirectory/controlnet_2`, ... _lowerCamelCase : Dict = pretrained_model_path while os.path.isdir(__lowerCAmelCase ): _lowerCamelCase : List[Any] = ControlNetModel.from_pretrained(__lowerCAmelCase ,**__lowerCAmelCase ) controlnets.append(__lowerCAmelCase ) idx += 1 _lowerCamelCase : Tuple = pretrained_model_path + F"""_{idx}""" logger.info(F"""{len(__lowerCAmelCase )} controlnets loaded from {pretrained_model_path}.""" ) if len(__lowerCAmelCase ) == 0: raise ValueError( F"""No ControlNets found under {os.path.dirname(__lowerCAmelCase )}. Expected at least {pretrained_model_path + '_0'}.""" ) return cls(__lowerCAmelCase )
340
1
"""simple docstring""" import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def lowerCamelCase_( ) -> str: '''simple docstring''' _lowerCamelCase : Any = ArgumentParser( description=( "PyTorch TPU distributed training launch " "helper utility that will spawn up " "multiple distributed processes" ) ) # Optional arguments for the launch helper parser.add_argument("--num_cores" , type=_lowerCamelCase , default=1 , help="Number of TPU cores to use (1 or 8)." ) # positional parser.add_argument( "training_script" , type=_lowerCamelCase , help=( "The full path to the single TPU training " "program/script to be launched in parallel, " "followed by all the arguments for the " "training script" ) , ) # rest from the training program parser.add_argument("training_script_args" , nargs=_lowerCamelCase ) return parser.parse_args() def lowerCamelCase_( ) -> Optional[int]: '''simple docstring''' _lowerCamelCase : Any = parse_args() # Import training_script as a module. _lowerCamelCase : List[Any] = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) _lowerCamelCase : List[Any] = script_fpath.stem _lowerCamelCase : Union[str, Any] = importlib.import_module(_lowerCamelCase ) # Patch sys.argv _lowerCamelCase : Dict = [args.training_script] + args.training_script_args + ["--tpu_num_cores", str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
340
"""simple docstring""" import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SegformerConfig, SegformerForImageClassification, SegformerForSemanticSegmentation, SegformerImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() _lowerCAmelCase : int = logging.get_logger(__name__) def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase=False ) -> List[str]: '''simple docstring''' _lowerCamelCase : Tuple = OrderedDict() for key, value in state_dict.items(): if encoder_only and not key.startswith("head" ): _lowerCamelCase : Tuple = "segformer.encoder." + key if key.startswith("backbone" ): _lowerCamelCase : Any = key.replace("backbone" , "segformer.encoder" ) if "patch_embed" in key: # replace for example patch_embed1 by patch_embeddings.0 _lowerCamelCase : int = key[key.find("patch_embed" ) + len("patch_embed" )] _lowerCamelCase : int = key.replace(F"""patch_embed{idx}""" , F"""patch_embeddings.{int(_lowerCamelCase )-1}""" ) if "norm" in key: _lowerCamelCase : Optional[Any] = key.replace("norm" , "layer_norm" ) if "segformer.encoder.layer_norm" in key: # replace for example layer_norm1 by layer_norm.0 _lowerCamelCase : Dict = key[key.find("segformer.encoder.layer_norm" ) + len("segformer.encoder.layer_norm" )] _lowerCamelCase : Tuple = key.replace(F"""layer_norm{idx}""" , F"""layer_norm.{int(_lowerCamelCase )-1}""" ) if "layer_norm1" in key: _lowerCamelCase : Union[str, Any] = key.replace("layer_norm1" , "layer_norm_1" ) if "layer_norm2" in key: _lowerCamelCase : int = key.replace("layer_norm2" , "layer_norm_2" ) if "block" in key: # replace for example block1 by block.0 _lowerCamelCase : Union[str, Any] = key[key.find("block" ) + len("block" )] _lowerCamelCase : Optional[Any] = key.replace(F"""block{idx}""" , F"""block.{int(_lowerCamelCase )-1}""" ) if "attn.q" in key: _lowerCamelCase : Optional[int] = key.replace("attn.q" , "attention.self.query" ) if "attn.proj" in key: _lowerCamelCase : List[str] = key.replace("attn.proj" , "attention.output.dense" ) if "attn" in key: _lowerCamelCase : Tuple = key.replace("attn" , "attention.self" ) if "fc1" in key: _lowerCamelCase : Optional[Any] = key.replace("fc1" , "dense1" ) if "fc2" in key: _lowerCamelCase : Dict = key.replace("fc2" , "dense2" ) if "linear_pred" in key: _lowerCamelCase : int = key.replace("linear_pred" , "classifier" ) if "linear_fuse" in key: _lowerCamelCase : str = key.replace("linear_fuse.conv" , "linear_fuse" ) _lowerCamelCase : Optional[Any] = key.replace("linear_fuse.bn" , "batch_norm" ) if "linear_c" in key: # replace for example linear_c4 by linear_c.3 _lowerCamelCase : Union[str, Any] = key[key.find("linear_c" ) + len("linear_c" )] _lowerCamelCase : Optional[int] = key.replace(F"""linear_c{idx}""" , F"""linear_c.{int(_lowerCamelCase )-1}""" ) if key.startswith("head" ): _lowerCamelCase : List[str] = key.replace("head" , "classifier" ) _lowerCamelCase : Union[str, Any] = value return new_state_dict def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase ) -> Optional[Any]: '''simple docstring''' for i in range(config.num_encoder_blocks ): for j in range(config.depths[i] ): # read in weights + bias of keys and values (which is a single matrix in the original implementation) _lowerCamelCase : Optional[Any] = state_dict.pop(F"""segformer.encoder.block.{i}.{j}.attention.self.kv.weight""" ) _lowerCamelCase : Optional[Any] = state_dict.pop(F"""segformer.encoder.block.{i}.{j}.attention.self.kv.bias""" ) # next, add keys and values (in that order) to the state dict _lowerCamelCase : int = kv_weight[ : config.hidden_sizes[i], : ] _lowerCamelCase : int = kv_bias[: config.hidden_sizes[i]] _lowerCamelCase : Optional[int] = kv_weight[ config.hidden_sizes[i] :, : ] _lowerCamelCase : Optional[Any] = kv_bias[ config.hidden_sizes[i] : ] def lowerCamelCase_( ) -> Dict: '''simple docstring''' _lowerCamelCase : int = "http://images.cocodataset.org/val2017/000000039769.jpg" _lowerCamelCase : Union[str, Any] = Image.open(requests.get(_lowerCamelCase , stream=_lowerCamelCase ).raw ) return image @torch.no_grad() def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) -> Dict: '''simple docstring''' _lowerCamelCase : Any = SegformerConfig() _lowerCamelCase : int = False # set attributes based on model_name _lowerCamelCase : Any = "huggingface/label-files" if "segformer" in model_name: _lowerCamelCase : str = model_name[len("segformer." ) : len("segformer." ) + 2] if "ade" in model_name: _lowerCamelCase : str = 150 _lowerCamelCase : Dict = "ade20k-id2label.json" _lowerCamelCase : Dict = (1, 150, 128, 128) elif "city" in model_name: _lowerCamelCase : List[str] = 19 _lowerCamelCase : Tuple = "cityscapes-id2label.json" _lowerCamelCase : Tuple = (1, 19, 128, 128) else: raise ValueError(F"""Model {model_name} not supported""" ) elif "mit" in model_name: _lowerCamelCase : List[str] = True _lowerCamelCase : Tuple = model_name[4:6] _lowerCamelCase : Tuple = 1000 _lowerCamelCase : List[Any] = "imagenet-1k-id2label.json" _lowerCamelCase : List[Any] = (1, 1000) else: raise ValueError(F"""Model {model_name} not supported""" ) # set config attributes _lowerCamelCase : Optional[Any] = json.load(open(hf_hub_download(_lowerCamelCase , _lowerCamelCase , repo_type="dataset" ) , "r" ) ) _lowerCamelCase : List[str] = {int(_lowerCamelCase ): v for k, v in idalabel.items()} _lowerCamelCase : Optional[Any] = idalabel _lowerCamelCase : Union[str, Any] = {v: k for k, v in idalabel.items()} if size == "b0": pass elif size == "b1": _lowerCamelCase : int = [64, 128, 320, 512] _lowerCamelCase : int = 256 elif size == "b2": _lowerCamelCase : Tuple = [64, 128, 320, 512] _lowerCamelCase : List[Any] = 768 _lowerCamelCase : Any = [3, 4, 6, 3] elif size == "b3": _lowerCamelCase : Tuple = [64, 128, 320, 512] _lowerCamelCase : Union[str, Any] = 768 _lowerCamelCase : Optional[Any] = [3, 4, 18, 3] elif size == "b4": _lowerCamelCase : str = [64, 128, 320, 512] _lowerCamelCase : Optional[Any] = 768 _lowerCamelCase : Dict = [3, 8, 27, 3] elif size == "b5": _lowerCamelCase : int = [64, 128, 320, 512] _lowerCamelCase : Tuple = 768 _lowerCamelCase : Tuple = [3, 6, 40, 3] else: raise ValueError(F"""Size {size} not supported""" ) # load image processor (only resize + normalize) _lowerCamelCase : Dict = SegformerImageProcessor( image_scale=(512, 512) , keep_ratio=_lowerCamelCase , align=_lowerCamelCase , do_random_crop=_lowerCamelCase ) # prepare image _lowerCamelCase : List[str] = prepare_img() _lowerCamelCase : Dict = image_processor(images=_lowerCamelCase , return_tensors="pt" ).pixel_values logger.info(F"""Converting model {model_name}...""" ) # load original state dict if encoder_only: _lowerCamelCase : Tuple = torch.load(_lowerCamelCase , map_location=torch.device("cpu" ) ) else: _lowerCamelCase : int = torch.load(_lowerCamelCase , map_location=torch.device("cpu" ) )["state_dict"] # rename keys _lowerCamelCase : str = rename_keys(_lowerCamelCase , encoder_only=_lowerCamelCase ) if not encoder_only: del state_dict["decode_head.conv_seg.weight"] del state_dict["decode_head.conv_seg.bias"] # key and value matrices need special treatment read_in_k_v(_lowerCamelCase , _lowerCamelCase ) # create HuggingFace model and load state dict if encoder_only: _lowerCamelCase : Tuple = False _lowerCamelCase : Optional[int] = SegformerForImageClassification(_lowerCamelCase ) else: _lowerCamelCase : List[str] = SegformerForSemanticSegmentation(_lowerCamelCase ) model.load_state_dict(_lowerCamelCase ) model.eval() # forward pass _lowerCamelCase : Any = model(_lowerCamelCase ) _lowerCamelCase : Dict = outputs.logits # set expected_slice based on model name # ADE20k checkpoints if model_name == "segformer.b0.512x512.ade.160k": _lowerCamelCase : str = torch.tensor( [ [[-4.6_3_1_0, -5.5_2_3_2, -6.2_3_5_6], [-5.1_9_2_1, -6.1_4_4_4, -6.5_9_9_6], [-5.4_4_2_4, -6.2_7_9_0, -6.7_5_7_4]], [[-1_2.1_3_9_1, -1_3.3_1_2_2, -1_3.9_5_5_4], [-1_2.8_7_3_2, -1_3.9_3_5_2, -1_4.3_5_6_3], [-1_2.9_4_3_8, -1_3.8_2_2_6, -1_4.2_5_1_3]], [[-1_2.5_1_3_4, -1_3.4_6_8_6, -1_4.4_9_1_5], [-1_2.8_6_6_9, -1_4.4_3_4_3, -1_4.7_7_5_8], [-1_3.2_5_2_3, -1_4.5_8_1_9, -1_5.0_6_9_4]], ] ) elif model_name == "segformer.b1.512x512.ade.160k": _lowerCamelCase : Any = torch.tensor( [ [[-7.5_8_2_0, -8.7_2_3_1, -8.3_2_1_5], [-8.0_6_0_0, -1_0.3_5_2_9, -1_0.0_3_0_4], [-7.5_2_0_8, -9.4_1_0_3, -9.6_2_3_9]], [[-1_2.6_9_1_8, -1_3.8_9_9_4, -1_3.7_1_3_7], [-1_3.3_1_9_6, -1_5.7_5_2_3, -1_5.4_7_8_9], [-1_2.9_3_4_3, -1_4.8_7_5_7, -1_4.9_6_8_9]], [[-1_1.1_9_1_1, -1_1.9_4_2_1, -1_1.3_2_4_3], [-1_1.3_3_4_2, -1_3.6_8_3_9, -1_3.3_5_8_1], [-1_0.3_9_0_9, -1_2.1_8_3_2, -1_2.4_8_5_8]], ] ) elif model_name == "segformer.b2.512x512.ade.160k": _lowerCamelCase : int = torch.tensor( [ [[-1_1.8_1_7_3, -1_4.3_8_5_0, -1_6.3_1_2_8], [-1_4.5_6_4_8, -1_6.5_8_0_4, -1_8.6_5_6_8], [-1_4.7_2_2_3, -1_5.7_3_8_7, -1_8.4_2_1_8]], [[-1_5.7_2_9_0, -1_7.9_1_7_1, -1_9.4_4_2_3], [-1_8.3_1_0_5, -1_9.9_4_4_8, -2_1.4_6_6_1], [-1_7.9_2_9_6, -1_8.6_4_9_7, -2_0.7_9_1_0]], [[-1_5.0_7_8_3, -1_7.0_3_3_6, -1_8.2_7_8_9], [-1_6.8_7_7_1, -1_8.6_8_7_0, -2_0.1_6_1_2], [-1_6.2_4_5_4, -1_7.1_4_2_6, -1_9.5_0_5_5]], ] ) elif model_name == "segformer.b3.512x512.ade.160k": _lowerCamelCase : Optional[Any] = torch.tensor( [ [[-9.0_8_7_8, -1_0.2_0_8_1, -1_0.1_8_9_1], [-9.3_1_4_4, -1_0.7_9_4_1, -1_0.9_8_4_3], [-9.2_2_9_4, -1_0.3_8_5_5, -1_0.5_7_0_4]], [[-1_2.2_3_1_6, -1_3.9_0_6_8, -1_3.6_1_0_2], [-1_2.9_1_6_1, -1_4.3_7_0_2, -1_4.3_2_3_5], [-1_2.5_2_3_3, -1_3.7_1_7_4, -1_3.7_9_3_2]], [[-1_4.6_2_7_5, -1_5.2_4_9_0, -1_4.9_7_2_7], [-1_4.3_4_0_0, -1_5.9_6_8_7, -1_6.2_8_2_7], [-1_4.1_4_8_4, -1_5.4_0_3_3, -1_5.8_9_3_7]], ] ) elif model_name == "segformer.b4.512x512.ade.160k": _lowerCamelCase : List[str] = torch.tensor( [ [[-1_2.3_1_4_4, -1_3.2_4_4_7, -1_4.0_8_0_2], [-1_3.3_6_1_4, -1_4.5_8_1_6, -1_5.6_1_1_7], [-1_3.3_3_4_0, -1_4.4_4_3_3, -1_6.2_2_1_9]], [[-1_9.2_7_8_1, -2_0.4_1_2_8, -2_0.7_5_0_6], [-2_0.6_1_5_3, -2_1.6_5_6_6, -2_2.0_9_9_8], [-1_9.9_8_0_0, -2_1.0_4_3_0, -2_2.1_4_9_4]], [[-1_8.8_7_3_9, -1_9.7_8_0_4, -2_1.1_8_3_4], [-2_0.1_2_3_3, -2_1.6_7_6_5, -2_3.2_9_4_4], [-2_0.0_3_1_5, -2_1.2_6_4_1, -2_3.6_9_4_4]], ] ) elif model_name == "segformer.b5.640x640.ade.160k": _lowerCamelCase : Any = torch.tensor( [ [[-9.5_5_2_4, -1_2.0_8_3_5, -1_1.7_3_4_8], [-1_0.5_2_2_9, -1_3.6_4_4_6, -1_4.5_6_6_2], [-9.5_8_4_2, -1_2.8_8_5_1, -1_3.9_4_1_4]], [[-1_5.3_4_3_2, -1_7.5_3_2_3, -1_7.0_8_1_8], [-1_6.3_3_3_0, -1_8.9_2_5_5, -1_9.2_1_0_1], [-1_5.1_3_4_0, -1_7.7_8_4_8, -1_8.3_9_7_1]], [[-1_2.6_0_7_2, -1_4.9_4_8_6, -1_4.6_6_3_1], [-1_3.7_6_2_9, -1_7.0_9_0_7, -1_7.7_7_4_5], [-1_2.7_8_9_9, -1_6.1_6_9_5, -1_7.1_6_7_1]], ] ) # Cityscapes checkpoints elif model_name == "segformer.b0.1024x1024.city.160k": _lowerCamelCase : Dict = torch.tensor( [ [[-1_1.9_2_9_5, -1_3.4_0_5_7, -1_4.8_1_0_6], [-1_3.3_4_3_1, -1_4.8_1_7_9, -1_5.3_7_8_1], [-1_4.2_8_3_6, -1_5.5_9_4_2, -1_6.1_5_8_8]], [[-1_1.4_9_0_6, -1_2.8_0_6_7, -1_3.6_5_6_4], [-1_3.1_1_8_9, -1_4.0_5_0_0, -1_4.1_5_4_3], [-1_3.8_7_4_8, -1_4.5_1_3_6, -1_4.8_7_8_9]], [[0.5_3_7_4, 0.1_0_6_7, -0.4_7_4_2], [0.1_1_4_1, -0.2_2_5_5, -0.7_0_9_9], [-0.3_0_0_0, -0.5_9_2_4, -1.3_1_0_5]], ] ) elif model_name == "segformer.b0.512x1024.city.160k": _lowerCamelCase : Optional[int] = torch.tensor( [ [[-7.8_2_1_7, -9.8_7_6_7, -1_0.1_7_1_7], [-9.4_4_3_8, -1_0.9_0_5_8, -1_1.4_0_4_7], [-9.7_9_3_9, -1_2.3_4_9_5, -1_2.1_0_7_9]], [[-7.1_5_1_4, -9.5_3_3_6, -1_0.0_8_6_0], [-9.7_7_7_6, -1_1.6_8_2_2, -1_1.8_4_3_9], [-1_0.1_4_1_1, -1_2.7_6_5_5, -1_2.8_9_7_2]], [[0.3_0_2_1, 0.0_8_0_5, -0.2_3_1_0], [-0.0_3_2_8, -0.1_6_0_5, -0.2_7_1_4], [-0.1_4_0_8, -0.5_4_7_7, -0.6_9_7_6]], ] ) elif model_name == "segformer.b0.640x1280.city.160k": _lowerCamelCase : Tuple = torch.tensor( [ [ [-1.13_72e01, -1.27_87e01, -1.34_77e01], [-1.25_36e01, -1.41_94e01, -1.44_09e01], [-1.32_17e01, -1.48_88e01, -1.53_27e01], ], [ [-1.47_91e01, -1.71_22e01, -1.82_77e01], [-1.71_63e01, -1.91_92e01, -1.95_33e01], [-1.78_97e01, -1.99_91e01, -2.03_15e01], ], [ [7.67_23e-01, 4.19_21e-01, -7.78_78e-02], [4.77_72e-01, 9.55_57e-03, -2.80_82e-01], [3.60_32e-01, -2.48_26e-01, -5.11_68e-01], ], ] ) elif model_name == "segformer.b0.768x768.city.160k": _lowerCamelCase : Union[str, Any] = torch.tensor( [ [[-9.4_9_5_9, -1_1.3_0_8_7, -1_1.7_4_7_9], [-1_1.0_0_2_5, -1_2.6_5_4_0, -1_2.3_3_1_9], [-1_1.4_0_6_4, -1_3.0_4_8_7, -1_2.9_9_0_5]], [[-9.8_9_0_5, -1_1.3_0_8_4, -1_2.0_8_5_4], [-1_1.1_7_2_6, -1_2.7_6_9_8, -1_2.9_5_8_3], [-1_1.5_9_8_5, -1_3.3_2_7_8, -1_4.1_7_7_4]], [[0.2_2_1_3, 0.0_1_9_2, -0.2_4_6_6], [-0.1_7_3_1, -0.4_2_1_3, -0.4_8_7_4], [-0.3_1_2_6, -0.6_5_4_1, -1.1_3_8_9]], ] ) elif model_name == "segformer.b1.1024x1024.city.160k": _lowerCamelCase : List[Any] = torch.tensor( [ [[-1_3.5_7_4_8, -1_3.9_1_1_1, -1_2.6_5_0_0], [-1_4.3_5_0_0, -1_5.3_6_8_3, -1_4.2_3_2_8], [-1_4.7_5_3_2, -1_6.0_4_2_4, -1_5.6_0_8_7]], [[-1_7.1_6_5_1, -1_5.8_7_2_5, -1_2.9_6_5_3], [-1_7.2_5_8_0, -1_7.3_7_1_8, -1_4.8_2_2_3], [-1_6.6_0_5_8, -1_6.8_7_8_3, -1_6.7_4_5_2]], [[-3.6_4_5_6, -3.0_2_0_9, -1.4_2_0_3], [-3.0_7_9_7, -3.1_9_5_9, -2.0_0_0_0], [-1.8_7_5_7, -1.9_2_1_7, -1.6_9_9_7]], ] ) elif model_name == "segformer.b2.1024x1024.city.160k": _lowerCamelCase : Tuple = torch.tensor( [ [[-1_6.0_9_7_6, -1_6.4_8_5_6, -1_7.3_9_6_2], [-1_6.6_2_3_4, -1_9.0_3_4_2, -1_9.7_6_8_5], [-1_6.0_9_0_0, -1_8.0_6_6_1, -1_9.1_1_8_0]], [[-1_8.4_7_5_0, -1_8.8_4_8_8, -1_9.5_0_7_4], [-1_9.4_0_3_0, -2_2.1_5_7_0, -2_2.5_9_7_7], [-1_9.1_1_9_1, -2_0.8_4_8_6, -2_2.3_7_8_3]], [[-4.5_1_7_8, -5.5_0_3_7, -6.5_1_0_9], [-5.0_8_8_4, -7.2_1_7_4, -8.0_3_3_4], [-4.4_1_5_6, -5.8_1_1_7, -7.2_9_7_0]], ] ) elif model_name == "segformer.b3.1024x1024.city.160k": _lowerCamelCase : Any = torch.tensor( [ [[-1_4.2_0_8_1, -1_4.4_7_3_2, -1_4.1_9_7_7], [-1_4.5_8_6_7, -1_6.4_4_2_3, -1_6.6_3_5_6], [-1_3.4_4_4_1, -1_4.9_6_8_5, -1_6.8_6_9_6]], [[-1_4.4_5_7_6, -1_4.7_0_7_3, -1_5.0_4_5_1], [-1_5.0_8_1_6, -1_7.6_2_3_7, -1_7.9_8_7_3], [-1_4.4_2_1_3, -1_6.0_1_9_9, -1_8.5_9_9_2]], [[-4.7_3_4_9, -4.9_5_8_8, -5.0_9_6_6], [-4.3_2_1_0, -6.9_3_2_5, -7.2_5_9_1], [-3.4_3_1_2, -4.7_4_8_4, -7.1_9_1_7]], ] ) elif model_name == "segformer.b4.1024x1024.city.160k": _lowerCamelCase : List[str] = torch.tensor( [ [[-1_1.7_7_3_7, -1_1.9_5_2_6, -1_1.3_2_7_3], [-1_3.6_6_9_2, -1_4.4_5_7_4, -1_3.8_8_7_8], [-1_3.8_9_3_7, -1_4.6_9_2_4, -1_5.9_3_4_5]], [[-1_4.6_7_0_6, -1_4.5_3_3_0, -1_4.1_3_0_6], [-1_6.1_5_0_2, -1_6.8_1_8_0, -1_6.4_2_6_9], [-1_6.8_3_3_8, -1_7.8_9_3_9, -2_0.1_7_4_6]], [[1.0_4_9_1, 0.8_2_8_9, 1.0_3_1_0], [1.1_0_4_4, 0.5_2_1_9, 0.8_0_5_5], [1.0_8_9_9, 0.6_9_2_6, 0.5_5_9_0]], ] ) elif model_name == "segformer.b5.1024x1024.city.160k": _lowerCamelCase : str = torch.tensor( [ [[-1_2.5_6_4_1, -1_3.4_7_7_7, -1_3.0_6_8_4], [-1_3.9_5_8_7, -1_5.8_9_8_3, -1_6.6_5_5_7], [-1_3.3_1_0_9, -1_5.7_3_5_0, -1_6.3_1_4_1]], [[-1_4.7_0_7_4, -1_5.4_3_5_2, -1_4.5_9_4_4], [-1_6.6_3_5_3, -1_8.1_6_6_3, -1_8.6_1_2_0], [-1_5.1_7_0_2, -1_8.0_3_2_9, -1_8.1_5_4_7]], [[-1.7_9_9_0, -2.0_9_5_1, -1.7_7_8_4], [-2.6_3_9_7, -3.8_2_4_5, -3.9_6_8_6], [-1.5_2_6_4, -2.8_1_2_6, -2.9_3_1_6]], ] ) else: _lowerCamelCase : Dict = logits.argmax(-1 ).item() print("Predicted class:" , model.config.idalabel[predicted_class_idx] ) # verify logits if not encoder_only: assert logits.shape == expected_shape assert torch.allclose(logits[0, :3, :3, :3] , _lowerCamelCase , atol=1e-2 ) # finally, save model and image processor logger.info(F"""Saving PyTorch model and image processor to {pytorch_dump_folder_path}...""" ) Path(_lowerCamelCase ).mkdir(exist_ok=_lowerCamelCase ) model.save_pretrained(_lowerCamelCase ) image_processor.save_pretrained(_lowerCamelCase ) if __name__ == "__main__": _lowerCAmelCase : str = argparse.ArgumentParser() parser.add_argument( '''--model_name''', default='''segformer.b0.512x512.ade.160k''', type=str, help='''Name of the model you\'d like to convert.''', ) parser.add_argument( '''--checkpoint_path''', default=None, type=str, help='''Path 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.''' ) _lowerCAmelCase : str = parser.parse_args() convert_segformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
340
1
"""simple docstring""" import random from .binary_exp_mod import bin_exp_mod def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase=1000 ) -> int: '''simple docstring''' if n < 2: return False if n % 2 == 0: return n == 2 # this means n is odd _lowerCamelCase : Any = n - 1 _lowerCamelCase : int = 0 while d % 2 == 0: d /= 2 exp += 1 # n - 1=d*(2**exp) _lowerCamelCase : int = 0 while count < prec: _lowerCamelCase : Union[str, Any] = random.randint(2 , n - 1 ) _lowerCamelCase : Union[str, Any] = bin_exp_mod(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) if b != 1: _lowerCamelCase : Dict = True for _ in range(_lowerCamelCase ): if b == n - 1: _lowerCamelCase : Optional[Any] = False break _lowerCamelCase : Optional[Any] = b * b b %= n if flag: return False count += 1 return True if __name__ == "__main__": _lowerCAmelCase : Optional[int] = abs(int(input('''Enter bound : ''').strip())) print('''Here\'s the list of primes:''') print(''', '''.join(str(i) for i in range(n + 1) if is_prime_big(i)))
340
"""simple docstring""" _lowerCAmelCase : dict[tuple[int, int, int], int] = {} def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) -> int: '''simple docstring''' if late == 3 or absent == 2: return 0 # if we have no days left, and have not failed any other rules, # we have a prize string if days == 0: return 1 # No easy solution, so now we need to do the recursive calculation # First, check if the combination is already in the cache, and # if yes, return the stored value from there since we already # know the number of possible prize strings from this point on _lowerCamelCase : Optional[int] = (days, absent, late) if key in cache: return cache[key] # now we calculate the three possible ways that can unfold from # this point on, depending on our attendance today # 1) if we are late (but not absent), the "absent" counter stays as # it is, but the "late" counter increases by one _lowerCamelCase : int = _calculate(days - 1 , _lowerCamelCase , late + 1 ) # 2) if we are absent, the "absent" counter increases by 1, and the # "late" counter resets to 0 _lowerCamelCase : Tuple = _calculate(days - 1 , absent + 1 , 0 ) # 3) if we are on time, this resets the "late" counter and keeps the # absent counter _lowerCamelCase : str = _calculate(days - 1 , _lowerCamelCase , 0 ) _lowerCamelCase : List[Any] = state_late + state_absent + state_ontime _lowerCamelCase : int = prizestrings return prizestrings def lowerCamelCase_( _lowerCamelCase = 30 ) -> int: '''simple docstring''' return _calculate(_lowerCamelCase , absent=0 , late=0 ) if __name__ == "__main__": print(solution())
340
1
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from ..models.speechta import SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaProcessor from ..utils import is_datasets_available from .base import PipelineTool if is_datasets_available(): from datasets import load_dataset class A_ ( _a ): lowerCAmelCase__ = 'microsoft/speecht5_tts' lowerCAmelCase__ = ( 'This is a tool that reads an English text out loud. It takes an input named `text` which should contain the ' 'text to read (in English) and returns a waveform object containing the sound.' ) lowerCAmelCase__ = 'text_reader' lowerCAmelCase__ = SpeechTaProcessor lowerCAmelCase__ = SpeechTaForTextToSpeech lowerCAmelCase__ = SpeechTaHifiGan lowerCAmelCase__ = ['text'] lowerCAmelCase__ = ['audio'] def _lowercase ( self: int ): '''simple docstring''' if self.post_processor is None: _lowerCamelCase : str = "microsoft/speecht5_hifigan" super().setup() def _lowercase ( self: str ,__lowerCAmelCase: Dict ,__lowerCAmelCase: Optional[Any]=None ): '''simple docstring''' _lowerCamelCase : Union[str, Any] = self.pre_processor(text=__lowerCAmelCase ,return_tensors="pt" ,truncation=__lowerCAmelCase ) if speaker_embeddings is None: if not is_datasets_available(): raise ImportError("Datasets needs to be installed if not passing speaker embeddings." ) _lowerCamelCase : Optional[Any] = load_dataset("Matthijs/cmu-arctic-xvectors" ,split="validation" ) _lowerCamelCase : List[str] = torch.tensor(embeddings_dataset[7_305]["xvector"] ).unsqueeze(0 ) return {"input_ids": inputs["input_ids"], "speaker_embeddings": speaker_embeddings} def _lowercase ( self: List[Any] ,__lowerCAmelCase: int ): '''simple docstring''' with torch.no_grad(): return self.model.generate_speech(**__lowerCAmelCase ) def _lowercase ( self: List[Any] ,__lowerCAmelCase: Dict ): '''simple docstring''' with torch.no_grad(): return self.post_processor(__lowerCAmelCase ).cpu().detach()
340
"""simple docstring""" from __future__ import annotations def lowerCamelCase_( _lowerCamelCase ) -> bool: '''simple docstring''' _lowerCamelCase : int = str(_lowerCamelCase ) return len(_lowerCamelCase ) == 9 and set(_lowerCamelCase ) == set("123456789" ) def lowerCamelCase_( ) -> int | None: '''simple docstring''' for base_num in range(9999 , 4999 , -1 ): _lowerCamelCase : Union[str, Any] = 100002 * base_num if is_9_pandigital(_lowerCamelCase ): return candidate for base_num in range(333 , 99 , -1 ): _lowerCamelCase : Tuple = 1002003 * base_num if is_9_pandigital(_lowerCamelCase ): return candidate return None if __name__ == "__main__": print(f'''{solution() = }''')
340
1
"""simple docstring""" from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast from ...utils import logging _lowerCAmelCase : List[str] = logging.get_logger(__name__) _lowerCAmelCase : str = { '''EleutherAI/gpt-neo-1.3B''': '''https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json''', # See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo } class A_ ( _a ): lowerCAmelCase__ = 'gpt_neo' lowerCAmelCase__ = ['past_key_values'] lowerCAmelCase__ = {'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers'} def __init__( self: Union[str, Any] ,__lowerCAmelCase: List[str]=50_257 ,__lowerCAmelCase: str=2_048 ,__lowerCAmelCase: Optional[int]=2_048 ,__lowerCAmelCase: Any=24 ,__lowerCAmelCase: Union[str, Any]=[[["global", "local"], 12]] ,__lowerCAmelCase: Any=16 ,__lowerCAmelCase: Any=None ,__lowerCAmelCase: Union[str, Any]=256 ,__lowerCAmelCase: Optional[Any]="gelu_new" ,__lowerCAmelCase: Optional[Any]=0.0 ,__lowerCAmelCase: str=0.0 ,__lowerCAmelCase: Dict=0.0 ,__lowerCAmelCase: Dict=0.1 ,__lowerCAmelCase: int=1e-5 ,__lowerCAmelCase: Optional[int]=0.02 ,__lowerCAmelCase: int=True ,__lowerCAmelCase: Dict=50_256 ,__lowerCAmelCase: List[str]=50_256 ,**__lowerCAmelCase: Optional[int] ,): '''simple docstring''' _lowerCamelCase : Tuple = vocab_size _lowerCamelCase : Tuple = max_position_embeddings _lowerCamelCase : Any = hidden_size _lowerCamelCase : List[Any] = num_layers _lowerCamelCase : str = num_heads _lowerCamelCase : Union[str, Any] = intermediate_size _lowerCamelCase : Any = window_size _lowerCamelCase : List[str] = activation_function _lowerCamelCase : Union[str, Any] = resid_dropout _lowerCamelCase : List[Any] = embed_dropout _lowerCamelCase : Dict = attention_dropout _lowerCamelCase : Optional[int] = classifier_dropout _lowerCamelCase : Optional[int] = layer_norm_epsilon _lowerCamelCase : str = initializer_range _lowerCamelCase : List[str] = use_cache _lowerCamelCase : Optional[int] = bos_token_id _lowerCamelCase : Tuple = eos_token_id _lowerCamelCase : List[Any] = attention_types _lowerCamelCase : Optional[int] = self.expand_attention_types_params(__lowerCAmelCase ) if len(self.attention_layers ) != self.num_layers: raise ValueError( "Configuration for convolutional module is incorrect. " "It is required that `len(config.attention_layers)` == `config.num_layers` " F"""but is `len(config.attention_layers) = {len(self.attention_layers )}`, """ F"""`config.num_layers = {self.num_layers}`. """ "`config.attention_layers` is prepared using `config.attention_types`. " "Please verify the value of `config.attention_types` argument." ) super().__init__(bos_token_id=__lowerCAmelCase ,eos_token_id=__lowerCAmelCase ,**__lowerCAmelCase ) @staticmethod def _lowercase ( __lowerCAmelCase: Any ): '''simple docstring''' _lowerCamelCase : int = [] for item in attention_types: for _ in range(item[1] ): attentions.extend(item[0] ) return attentions def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) -> Tuple: '''simple docstring''' import torch _lowerCamelCase : Union[str, Any] = input.size() _lowerCamelCase : List[Any] = len(_lowerCamelCase ) _lowerCamelCase : Dict = shape[dimension] _lowerCamelCase : str = torch.arange(0 , _lowerCamelCase , _lowerCamelCase ) _lowerCamelCase : Optional[int] = torch.div(sizedim - size , _lowerCamelCase , rounding_mode="floor" ) + 1 _lowerCamelCase : Dict = torch.arange(_lowerCamelCase ) + low_indices[:min_length][:, None] _lowerCamelCase : Any = [slice(_lowerCamelCase )] * rank _lowerCamelCase : Dict = indices _lowerCamelCase : Optional[Any] = input[s] _lowerCamelCase : str = list(range(0 , rank + 1 ) ) perm.append(perm.pop(dimension + 1 ) ) return sliced.permute(_lowerCamelCase ) def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase ) -> Any: '''simple docstring''' import torch _lowerCamelCase : int = torch.arange(1 , _lowerCamelCase ) _lowerCamelCase : List[Any] = torch.remainder(_lowerCamelCase , _lowerCamelCase ) _lowerCamelCase : Any = remainders == 0 _lowerCamelCase : Dict = candidates[divisor_indices] _lowerCamelCase : Any = torch.max(_lowerCamelCase ) return largest_divisor, torch.div(_lowerCamelCase , _lowerCamelCase , rounding_mode="floor" ) class A_ ( _a ): @property def _lowercase ( self: Optional[int] ): '''simple docstring''' _lowerCamelCase : int = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}} ) if self.use_past: self.fill_with_past_key_values_(__lowerCAmelCase ,direction="inputs" ) _lowerCamelCase : Tuple = {0: "batch", 1: "past_sequence + sequence"} else: _lowerCamelCase : Optional[Any] = {0: "batch", 1: "sequence"} return common_inputs @property def _lowercase ( self: Union[str, Any] ): '''simple docstring''' return self._config.num_heads def _lowercase ( self: Optional[Any] ,__lowerCAmelCase: PreTrainedTokenizer ,__lowerCAmelCase: int = -1 ,__lowerCAmelCase: int = -1 ,__lowerCAmelCase: bool = False ,__lowerCAmelCase: Optional[TensorType] = None ,): '''simple docstring''' _lowerCamelCase : Tuple = super(__lowerCAmelCase ,self ).generate_dummy_inputs( __lowerCAmelCase ,batch_size=__lowerCAmelCase ,seq_length=__lowerCAmelCase ,is_pair=__lowerCAmelCase ,framework=__lowerCAmelCase ) # We need to order the input in the way they appears in the forward() _lowerCamelCase : int = OrderedDict({"input_ids": common_inputs["input_ids"]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch _lowerCamelCase, _lowerCamelCase : List[Any] = common_inputs["input_ids"].shape # Not using the same length for past_key_values _lowerCamelCase : Any = seqlen + 2 _lowerCamelCase : int = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) _lowerCamelCase : str = [ (torch.zeros(__lowerCAmelCase ), torch.zeros(__lowerCAmelCase )) for _ in range(self.num_layers ) ] _lowerCamelCase : Any = common_inputs["attention_mask"] if self.use_past: _lowerCamelCase : Optional[Any] = ordered_inputs["attention_mask"].dtype _lowerCamelCase : Optional[Any] = torch.cat( [ordered_inputs["attention_mask"], torch.ones(__lowerCAmelCase ,__lowerCAmelCase ,dtype=__lowerCAmelCase )] ,dim=1 ) return ordered_inputs @property def _lowercase ( self: Any ): '''simple docstring''' return 13
340
"""simple docstring""" import warnings from transformers import AutoTokenizer from transformers.utils import is_torch_available from transformers.utils.generic import ExplicitEnum from ...processing_utils import ProcessorMixin if is_torch_available(): import torch class A_ ( _a ): lowerCAmelCase__ = 'char' lowerCAmelCase__ = 'bpe' lowerCAmelCase__ = 'wp' _lowerCAmelCase : List[str] = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class A_ ( _a ): lowerCAmelCase__ = ['image_processor', 'char_tokenizer'] lowerCAmelCase__ = 'ViTImageProcessor' lowerCAmelCase__ = 'MgpstrTokenizer' def __init__( self: List[Any] ,__lowerCAmelCase: int=None ,__lowerCAmelCase: Optional[int]=None ,**__lowerCAmelCase: Optional[Any] ): '''simple docstring''' _lowerCamelCase : Any = None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." ,__lowerCAmelCase ,) _lowerCamelCase : List[Any] = kwargs.pop("feature_extractor" ) _lowerCamelCase : str = 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`." ) _lowerCamelCase : List[str] = tokenizer _lowerCamelCase : str = AutoTokenizer.from_pretrained("gpt2" ) _lowerCamelCase : List[str] = AutoTokenizer.from_pretrained("bert-base-uncased" ) super().__init__(__lowerCAmelCase ,__lowerCAmelCase ) def __call__( self: Optional[int] ,__lowerCAmelCase: List[Any]=None ,__lowerCAmelCase: Union[str, Any]=None ,__lowerCAmelCase: Optional[Any]=None ,**__lowerCAmelCase: Tuple ): '''simple docstring''' 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(__lowerCAmelCase ,return_tensors=__lowerCAmelCase ,**__lowerCAmelCase ) if text is not None: _lowerCamelCase : int = self.char_tokenizer(__lowerCAmelCase ,return_tensors=__lowerCAmelCase ,**__lowerCAmelCase ) if text is None: return inputs elif images is None: return encodings else: _lowerCamelCase : Tuple = encodings["input_ids"] return inputs def _lowercase ( self: int ,__lowerCAmelCase: Dict ): '''simple docstring''' _lowerCamelCase, _lowerCamelCase, _lowerCamelCase : Optional[int] = sequences _lowerCamelCase : Dict = char_preds.size(0 ) _lowerCamelCase, _lowerCamelCase : Optional[Any] = self._decode_helper(__lowerCAmelCase ,"char" ) _lowerCamelCase, _lowerCamelCase : Union[str, Any] = self._decode_helper(__lowerCAmelCase ,"bpe" ) _lowerCamelCase, _lowerCamelCase : Tuple = self._decode_helper(__lowerCAmelCase ,"wp" ) _lowerCamelCase : List[str] = [] _lowerCamelCase : str = [] for i in range(__lowerCAmelCase ): _lowerCamelCase : str = [char_scores[i], bpe_scores[i], wp_scores[i]] _lowerCamelCase : List[Any] = [char_strs[i], bpe_strs[i], wp_strs[i]] _lowerCamelCase : Optional[Any] = scores.index(max(__lowerCAmelCase ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) _lowerCamelCase : Tuple = {} _lowerCamelCase : Tuple = final_strs _lowerCamelCase : int = final_scores _lowerCamelCase : str = char_strs _lowerCamelCase : Dict = bpe_strs _lowerCamelCase : int = wp_strs return out def _lowercase ( self: List[str] ,__lowerCAmelCase: Dict ,__lowerCAmelCase: List[Any] ): '''simple docstring''' if format == DecodeType.CHARACTER: _lowerCamelCase : int = self.char_decode _lowerCamelCase : List[str] = 1 _lowerCamelCase : Optional[int] = "[s]" elif format == DecodeType.BPE: _lowerCamelCase : Dict = self.bpe_decode _lowerCamelCase : str = 2 _lowerCamelCase : Union[str, Any] = "#" elif format == DecodeType.WORDPIECE: _lowerCamelCase : int = self.wp_decode _lowerCamelCase : List[str] = 102 _lowerCamelCase : List[Any] = "[SEP]" else: raise ValueError(F"""Format {format} is not supported.""" ) _lowerCamelCase, _lowerCamelCase : Union[str, Any] = [], [] _lowerCamelCase : Any = pred_logits.size(0 ) _lowerCamelCase : int = pred_logits.size(1 ) _lowerCamelCase, _lowerCamelCase : List[Any] = pred_logits.topk(1 ,dim=-1 ,largest=__lowerCAmelCase ,sorted=__lowerCAmelCase ) _lowerCamelCase : Optional[int] = preds_index.view(-1 ,__lowerCAmelCase )[:, 1:] _lowerCamelCase : List[str] = decoder(__lowerCAmelCase ) _lowerCamelCase, _lowerCamelCase : str = torch.nn.functional.softmax(__lowerCAmelCase ,dim=2 ).max(dim=2 ) _lowerCamelCase : Any = preds_max_prob[:, 1:] for index in range(__lowerCAmelCase ): _lowerCamelCase : List[Any] = preds_str[index].find(__lowerCAmelCase ) _lowerCamelCase : Optional[int] = preds_str[index][:pred_eos] _lowerCamelCase : Optional[Any] = preds_index[index].cpu().tolist() _lowerCamelCase : List[str] = pred_index.index(__lowerCAmelCase ) if eos_token in pred_index else -1 _lowerCamelCase : str = preds_max_prob[index][: pred_eos_index + 1] _lowerCamelCase : Union[str, Any] = pred_max_prob.cumprod(dim=0 )[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(__lowerCAmelCase ) conf_scores.append(__lowerCAmelCase ) return dec_strs, conf_scores def _lowercase ( self: Tuple ,__lowerCAmelCase: Tuple ): '''simple docstring''' _lowerCamelCase : str = [seq.replace(" " ,"" ) for seq in self.char_tokenizer.batch_decode(__lowerCAmelCase )] return decode_strs def _lowercase ( self: List[str] ,__lowerCAmelCase: List[str] ): '''simple docstring''' return self.bpe_tokenizer.batch_decode(__lowerCAmelCase ) def _lowercase ( self: Tuple ,__lowerCAmelCase: Optional[int] ): '''simple docstring''' _lowerCamelCase : Union[str, Any] = [seq.replace(" " ,"" ) for seq in self.wp_tokenizer.batch_decode(__lowerCAmelCase )] return decode_strs
340
1
"""simple docstring""" def lowerCamelCase_( _lowerCamelCase ) -> bool: '''simple docstring''' _lowerCamelCase : List[str] = [int(_lowerCamelCase ) for i in ip_va_address.split("." ) if i.isdigit()] return len(_lowerCamelCase ) == 4 and all(0 <= int(_lowerCamelCase ) <= 254 for octet in octets ) if __name__ == "__main__": _lowerCAmelCase : List[str] = input().strip() _lowerCAmelCase : List[str] = '''valid''' if is_ip_va_address_valid(ip) else '''invalid''' print(f'''{ip} is a {valid_or_invalid} IP v4 address.''')
340
"""simple docstring""" # Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version _lowerCAmelCase : List[Any] = get_logger(__name__) class A_ : lowerCAmelCase__ = 'dummy_data' lowerCAmelCase__ = 'datasets' lowerCAmelCase__ = False def __init__( self: List[str] ,__lowerCAmelCase: str ,__lowerCAmelCase: str ,__lowerCAmelCase: Union[Version, str] ,__lowerCAmelCase: Optional[str] = None ,__lowerCAmelCase: bool = False ,__lowerCAmelCase: bool = True ,__lowerCAmelCase: Optional[List[Callable]] = None ,): '''simple docstring''' _lowerCamelCase : str = 0 _lowerCamelCase : List[str] = dataset_name _lowerCamelCase : Optional[int] = cache_dir _lowerCamelCase : Optional[int] = use_local_dummy_data _lowerCamelCase : int = config # download_callbacks take a single url as input _lowerCamelCase : List[Callable] = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root _lowerCamelCase : int = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general _lowerCamelCase : Tuple = str(__lowerCAmelCase ) # to be downloaded _lowerCamelCase : Optional[Any] = None _lowerCamelCase : Dict = None @property def _lowercase ( self: str ): '''simple docstring''' if self._dummy_file is None: _lowerCamelCase : List[str] = self.download_dummy_data() return self._dummy_file @property def _lowercase ( self: str ): '''simple docstring''' if self.config is not None: # structure is dummy / config_name / version_name return os.path.join("dummy" ,self.config.name ,self.version_name ) # structure is dummy / version_name return os.path.join("dummy" ,self.version_name ) @property def _lowercase ( self: Optional[Any] ): '''simple docstring''' return os.path.join(self.dummy_data_folder ,"dummy_data.zip" ) def _lowercase ( self: Optional[Any] ): '''simple docstring''' _lowerCamelCase : Dict = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) _lowerCamelCase : Optional[int] = cached_path( __lowerCAmelCase ,cache_dir=self.cache_dir ,extract_compressed_file=__lowerCAmelCase ,force_extract=__lowerCAmelCase ) return os.path.join(__lowerCAmelCase ,self.dummy_file_name ) @property def _lowercase ( self: Tuple ): '''simple docstring''' return os.path.join(self.datasets_scripts_dir ,self.dataset_name ,self.dummy_zip_file ) @property def _lowercase ( self: List[str] ): '''simple docstring''' if self._bucket_url is None: _lowerCamelCase : List[str] = hf_github_url(self.dataset_name ,self.dummy_zip_file.replace(os.sep ,"/" ) ) return self._bucket_url @property def _lowercase ( self: Union[str, Any] ): '''simple docstring''' if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep ,"/" ).split("/" )[:-1] ) def _lowercase ( self: Union[str, Any] ,__lowerCAmelCase: str ,*__lowerCAmelCase: List[Any] ): '''simple docstring''' if self.load_existing_dummy_data: # dummy data is downloaded and tested _lowerCamelCase : Tuple = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned _lowerCamelCase : Optional[Any] = self.dummy_file_name # special case when data_url is a dict if isinstance(__lowerCAmelCase ,__lowerCAmelCase ): return self.create_dummy_data_dict(__lowerCAmelCase ,__lowerCAmelCase ) elif isinstance(__lowerCAmelCase ,(list, tuple) ): return self.create_dummy_data_list(__lowerCAmelCase ,__lowerCAmelCase ) else: return self.create_dummy_data_single(__lowerCAmelCase ,__lowerCAmelCase ) def _lowercase ( self: str ,__lowerCAmelCase: Optional[int] ,*__lowerCAmelCase: Optional[int] ): '''simple docstring''' return self.download_and_extract(__lowerCAmelCase ) def _lowercase ( self: List[Any] ,__lowerCAmelCase: Dict ,__lowerCAmelCase: int ): '''simple docstring''' return self.download_and_extract(__lowerCAmelCase ) def _lowercase ( self: Optional[int] ,__lowerCAmelCase: Optional[int] ,*__lowerCAmelCase: List[str] ,**__lowerCAmelCase: Optional[int] ): '''simple docstring''' return path def _lowercase ( self: Optional[int] ): '''simple docstring''' return {} def _lowercase ( self: Optional[Any] ,__lowerCAmelCase: Dict ,__lowerCAmelCase: str ): '''simple docstring''' _lowerCamelCase : str = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(__lowerCAmelCase ,__lowerCAmelCase ): for single_url in single_urls: download_callback(__lowerCAmelCase ) else: _lowerCamelCase : Union[str, Any] = single_urls download_callback(__lowerCAmelCase ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(__lowerCAmelCase ,__lowerCAmelCase ): _lowerCamelCase : Dict = [os.path.join(__lowerCAmelCase ,urllib.parse.quote_plus(Path(__lowerCAmelCase ).name ) ) for x in single_urls] else: _lowerCamelCase : Union[str, Any] = single_urls _lowerCamelCase : List[str] = os.path.join(__lowerCAmelCase ,urllib.parse.quote_plus(Path(__lowerCAmelCase ).name ) ) _lowerCamelCase : List[Any] = value # make sure that values are unique if all(isinstance(__lowerCAmelCase ,__lowerCAmelCase ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique _lowerCamelCase : List[Any] = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def _lowercase ( self: int ,__lowerCAmelCase: List[str] ,__lowerCAmelCase: Tuple ): '''simple docstring''' _lowerCamelCase : Dict = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one _lowerCamelCase : List[str] = all(bool(re.findall("[0-9]{3,}-of-[0-9]{3,}" ,__lowerCAmelCase ) ) for url in data_url ) _lowerCamelCase : Optional[Any] = all( url.startswith("https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed" ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): _lowerCamelCase : Tuple = [data_url[0]] * len(__lowerCAmelCase ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(__lowerCAmelCase ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus _lowerCamelCase : List[Any] = os.path.join(__lowerCAmelCase ,urllib.parse.quote_plus(single_url.split("/" )[-1] ) ) dummy_data_list.append(__lowerCAmelCase ) return dummy_data_list def _lowercase ( self: Union[str, Any] ,__lowerCAmelCase: Optional[Any] ,__lowerCAmelCase: List[Any] ): '''simple docstring''' for download_callback in self.download_callbacks: download_callback(__lowerCAmelCase ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus _lowerCamelCase : Optional[int] = os.path.join(__lowerCAmelCase ,urllib.parse.quote_plus(data_url.split("/" )[-1] ) ) if os.path.exists(__lowerCAmelCase ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def _lowercase ( self: Optional[Any] ): '''simple docstring''' pass def _lowercase ( self: Optional[int] ): '''simple docstring''' pass def _lowercase ( self: List[Any] ,__lowerCAmelCase: Optional[int] ): '''simple docstring''' def _iter_archive_members(__lowerCAmelCase: Any ): # this preserves the order of the members inside the ZIP archive _lowerCamelCase : Tuple = Path(self.dummy_file ).parent _lowerCamelCase : str = path.relative_to(__lowerCAmelCase ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: _lowerCamelCase : Optional[int] = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(__lowerCAmelCase ) _lowerCamelCase : Optional[Any] = Path(__lowerCAmelCase ) _lowerCamelCase : int = _iter_archive_members(__lowerCAmelCase ) if self.use_local_dummy_data else path.rglob("*" ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith((".", "__") ): yield file_path.relative_to(__lowerCAmelCase ).as_posix(), file_path.open("rb" ) def _lowercase ( self: str ,__lowerCAmelCase: Optional[int] ): '''simple docstring''' if not isinstance(__lowerCAmelCase ,__lowerCAmelCase ): _lowerCamelCase : List[Any] = [paths] for path in paths: if os.path.isfile(__lowerCAmelCase ): if os.path.basename(__lowerCAmelCase ).startswith((".", "__") ): return yield path else: for dirpath, dirnames, filenames in os.walk(__lowerCAmelCase ): if os.path.basename(__lowerCAmelCase ).startswith((".", "__") ): continue dirnames.sort() for filename in sorted(__lowerCAmelCase ): if filename.startswith((".", "__") ): continue yield os.path.join(__lowerCAmelCase ,__lowerCAmelCase )
340
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowerCAmelCase : List[Any] = {'''configuration_opt''': ['''OPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''OPTConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase : Optional[int] = [ '''OPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''OPTForCausalLM''', '''OPTModel''', '''OPTPreTrainedModel''', '''OPTForSequenceClassification''', '''OPTForQuestionAnswering''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase : Optional[int] = ['''TFOPTForCausalLM''', '''TFOPTModel''', '''TFOPTPreTrainedModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase : Optional[int] = [ '''FlaxOPTForCausalLM''', '''FlaxOPTModel''', '''FlaxOPTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_opt import OPT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_opt import ( OPT_PRETRAINED_MODEL_ARCHIVE_LIST, OPTForCausalLM, OPTForQuestionAnswering, OPTForSequenceClassification, OPTModel, OPTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_opt import TFOPTForCausalLM, TFOPTModel, TFOPTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_opt import FlaxOPTForCausalLM, FlaxOPTModel, FlaxOPTPreTrainedModel else: import sys _lowerCAmelCase : Optional[int] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
340
"""simple docstring""" from decimal import Decimal, getcontext from math import ceil, factorial def lowerCamelCase_( _lowerCamelCase ) -> str: '''simple docstring''' if not isinstance(_lowerCamelCase , _lowerCamelCase ): raise TypeError("Undefined for non-integers" ) elif precision < 1: raise ValueError("Undefined for non-natural numbers" ) _lowerCamelCase : int = precision _lowerCamelCase : Dict = ceil(precision / 14 ) _lowerCamelCase : Optional[Any] = 426880 * Decimal(10005 ).sqrt() _lowerCamelCase : int = 1 _lowerCamelCase : Optional[int] = 13591409 _lowerCamelCase : int = Decimal(_lowerCamelCase ) for k in range(1 , _lowerCamelCase ): _lowerCamelCase : Union[str, Any] = factorial(6 * k ) // (factorial(3 * k ) * factorial(_lowerCamelCase ) ** 3) linear_term += 545140134 exponential_term *= -262537412640768000 partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term return str(constant_term / partial_sum )[:-1] if __name__ == "__main__": _lowerCAmelCase : Union[str, Any] = 50 print(f'''The first {n} digits of pi is: {pi(n)}''')
340
1