code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
"""simple docstring""" def __magic_name__ ( lowercase = 400_0000 ): SCREAMING_SNAKE_CASE_: Any =[] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Tuple =0, 1 while b <= n: if b % 2 == 0: even_fibs.append(lowercase ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[Any] =b, a + b return sum(lowercase ) if __name__ == "__main__": print(f"""{solution() = }""")
36
"""simple docstring""" from __future__ import annotations import math import random from typing import Any class a : def __init__( self : str ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: list[Any] =[] SCREAMING_SNAKE_CASE_: int =0 SCREAMING_SNAKE_CASE_: int =0 def lowerCamelCase__ ( self : Optional[Any] ) -> bool: '''simple docstring''' return self.head == self.tail def lowerCamelCase__ ( self : Tuple , lowerCAmelCase : Any ) -> None: '''simple docstring''' self.data.append(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =self.tail + 1 def lowerCamelCase__ ( self : int ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: int =self.data[self.head] SCREAMING_SNAKE_CASE_: Optional[int] =self.head + 1 return ret def lowerCamelCase__ ( self : Optional[Any] ) -> int: '''simple docstring''' return self.tail - self.head def lowerCamelCase__ ( self : str ) -> None: '''simple docstring''' print(self.data ) print("""**************""" ) print(self.data[self.head : self.tail] ) class a : def __init__( self : Union[str, Any] , lowerCAmelCase : Any ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =data SCREAMING_SNAKE_CASE_: MyNode | None =None SCREAMING_SNAKE_CASE_: MyNode | None =None SCREAMING_SNAKE_CASE_: int =1 def lowerCamelCase__ ( self : Optional[Any] ) -> Any: '''simple docstring''' return self.data def lowerCamelCase__ ( self : List[Any] ) -> MyNode | None: '''simple docstring''' return self.left def lowerCamelCase__ ( self : Dict ) -> MyNode | None: '''simple docstring''' return self.right def lowerCamelCase__ ( self : Any ) -> int: '''simple docstring''' return self.height def lowerCamelCase__ ( self : Any , lowerCAmelCase : Any ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[Any] =data def lowerCamelCase__ ( self : Dict , lowerCAmelCase : MyNode | None ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =node def lowerCamelCase__ ( self : List[Any] , lowerCAmelCase : MyNode | None ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: str =node def lowerCamelCase__ ( self : int , lowerCAmelCase : int ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =height def __magic_name__ ( lowercase ): if node is None: return 0 return node.get_height() def __magic_name__ ( lowercase , lowercase ): if a > b: return a return b def __magic_name__ ( lowercase ): print("""left rotation node:""" , node.get_data() ) SCREAMING_SNAKE_CASE_: List[Any] =node.get_left() assert ret is not None node.set_left(ret.get_right() ) ret.set_right(lowercase ) SCREAMING_SNAKE_CASE_: Tuple =my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowercase ) SCREAMING_SNAKE_CASE_: int =my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(lowercase ) return ret def __magic_name__ ( lowercase ): print("""right rotation node:""" , node.get_data() ) SCREAMING_SNAKE_CASE_: List[Any] =node.get_right() assert ret is not None node.set_right(ret.get_left() ) ret.set_left(lowercase ) SCREAMING_SNAKE_CASE_: List[Any] =my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowercase ) SCREAMING_SNAKE_CASE_: Optional[int] =my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(lowercase ) return ret def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Any =node.get_left() assert left_child is not None node.set_left(left_rotation(lowercase ) ) return right_rotation(lowercase ) def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Dict =node.get_right() assert right_child is not None node.set_right(right_rotation(lowercase ) ) return left_rotation(lowercase ) def __magic_name__ ( lowercase , lowercase ): if node is None: return MyNode(lowercase ) if data < node.get_data(): node.set_left(insert_node(node.get_left() , lowercase ) ) if ( get_height(node.get_left() ) - get_height(node.get_right() ) == 2 ): # an unbalance detected SCREAMING_SNAKE_CASE_: Union[str, Any] =node.get_left() assert left_child is not None if ( data < left_child.get_data() ): # new node is the left child of the left child SCREAMING_SNAKE_CASE_: Any =right_rotation(lowercase ) else: SCREAMING_SNAKE_CASE_: List[Any] =lr_rotation(lowercase ) else: node.set_right(insert_node(node.get_right() , lowercase ) ) if get_height(node.get_right() ) - get_height(node.get_left() ) == 2: SCREAMING_SNAKE_CASE_: Tuple =node.get_right() assert right_child is not None if data < right_child.get_data(): SCREAMING_SNAKE_CASE_: Optional[Any] =rl_rotation(lowercase ) else: SCREAMING_SNAKE_CASE_: Optional[int] =left_rotation(lowercase ) SCREAMING_SNAKE_CASE_: Tuple =my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowercase ) return node def __magic_name__ ( lowercase ): while True: SCREAMING_SNAKE_CASE_: Dict =root.get_right() if right_child is None: break SCREAMING_SNAKE_CASE_: str =right_child return root.get_data() def __magic_name__ ( lowercase ): while True: SCREAMING_SNAKE_CASE_: str =root.get_left() if left_child is None: break SCREAMING_SNAKE_CASE_: Dict =left_child return root.get_data() def __magic_name__ ( lowercase , lowercase ): SCREAMING_SNAKE_CASE_: str =root.get_left() SCREAMING_SNAKE_CASE_: List[Any] =root.get_right() if root.get_data() == data: if left_child is not None and right_child is not None: SCREAMING_SNAKE_CASE_: Union[str, Any] =get_left_most(lowercase ) root.set_data(lowercase ) root.set_right(del_node(lowercase , lowercase ) ) elif left_child is not None: SCREAMING_SNAKE_CASE_: Optional[int] =left_child elif right_child is not None: SCREAMING_SNAKE_CASE_: Any =right_child else: return None elif root.get_data() > data: if left_child is None: print("""No such data""" ) return root else: root.set_left(del_node(lowercase , lowercase ) ) else: # root.get_data() < data if right_child is None: return root else: root.set_right(del_node(lowercase , lowercase ) ) if get_height(lowercase ) - get_height(lowercase ) == 2: assert right_child is not None if get_height(right_child.get_right() ) > get_height(right_child.get_left() ): SCREAMING_SNAKE_CASE_: Tuple =left_rotation(lowercase ) else: SCREAMING_SNAKE_CASE_: Optional[Any] =rl_rotation(lowercase ) elif get_height(lowercase ) - get_height(lowercase ) == -2: assert left_child is not None if get_height(left_child.get_left() ) > get_height(left_child.get_right() ): SCREAMING_SNAKE_CASE_: Optional[Any] =right_rotation(lowercase ) else: SCREAMING_SNAKE_CASE_: str =lr_rotation(lowercase ) SCREAMING_SNAKE_CASE_: str =my_max(get_height(root.get_right() ) , get_height(root.get_left() ) ) + 1 root.set_height(lowercase ) return root class a : def __init__( self : int ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: MyNode | None =None def lowerCamelCase__ ( self : List[Any] ) -> int: '''simple docstring''' return get_height(self.root ) def lowerCamelCase__ ( self : Optional[int] , lowerCAmelCase : Any ) -> None: '''simple docstring''' print("""insert:""" + str(lowerCAmelCase ) ) SCREAMING_SNAKE_CASE_: Tuple =insert_node(self.root , lowerCAmelCase ) def lowerCamelCase__ ( self : List[Any] , lowerCAmelCase : Any ) -> None: '''simple docstring''' print("""delete:""" + str(lowerCAmelCase ) ) if self.root is None: print("""Tree is empty!""" ) return SCREAMING_SNAKE_CASE_: Union[str, Any] =del_node(self.root , lowerCAmelCase ) def __str__( self : List[str] , ) -> str: # a level traversale, gives a more intuitive look on the tree '''simple docstring''' SCREAMING_SNAKE_CASE_: List[Any] ="""""" SCREAMING_SNAKE_CASE_: str =MyQueue() q.push(self.root ) SCREAMING_SNAKE_CASE_: List[str] =self.get_height() if layer == 0: return output SCREAMING_SNAKE_CASE_: int =0 while not q.is_empty(): SCREAMING_SNAKE_CASE_: int =q.pop() SCREAMING_SNAKE_CASE_: List[Any] =""" """ * int(math.pow(2 , layer - 1 ) ) output += space if node is None: output += "*" q.push(lowerCAmelCase ) q.push(lowerCAmelCase ) else: output += str(node.get_data() ) q.push(node.get_left() ) q.push(node.get_right() ) output += space SCREAMING_SNAKE_CASE_: List[Any] =cnt + 1 for i in range(100 ): if cnt == math.pow(2 , lowerCAmelCase ) - 1: SCREAMING_SNAKE_CASE_: int =layer - 1 if layer == 0: output += "\n*************************************" return output output += "\n" break output += "\n*************************************" return output def __magic_name__ ( ): import doctest doctest.testmod() if __name__ == "__main__": _test() _UpperCAmelCase = AVLtree() _UpperCAmelCase = list(range(1_0)) random.shuffle(lst) for i in lst: t.insert(i) print(str(t)) random.shuffle(lst) for i in lst: t.del_node(i) print(str(t))
36
1
"""simple docstring""" import unittest from transformers import is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class a : @staticmethod def lowerCamelCase__ ( *lowerCAmelCase : List[Any] , **lowerCAmelCase : Tuple ) -> Optional[int]: '''simple docstring''' pass @is_pipeline_test @require_vision class a ( unittest.TestCase ): @require_torch def lowerCamelCase__ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =pipeline( model="""hf-internal-testing/tiny-random-clip-zero-shot-image-classification""" , ) SCREAMING_SNAKE_CASE_: str =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) SCREAMING_SNAKE_CASE_: Any =image_classifier(lowerCAmelCase , candidate_labels=["""a""", """b""", """c"""] ) # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across # python and torch versions. self.assertIn( nested_simplify(lowerCAmelCase ) , [ [{"""score""": 0.3_3_3, """label""": """a"""}, {"""score""": 0.3_3_3, """label""": """b"""}, {"""score""": 0.3_3_3, """label""": """c"""}], [{"""score""": 0.3_3_3, """label""": """a"""}, {"""score""": 0.3_3_3, """label""": """c"""}, {"""score""": 0.3_3_3, """label""": """b"""}], ] , ) SCREAMING_SNAKE_CASE_: str =image_classifier([image] * 5 , candidate_labels=["""A""", """B""", """C"""] , batch_size=2 ) self.assertEqual( nested_simplify(lowerCAmelCase ) , [ [ {"""score""": 0.3_3_3, """label""": ANY(lowerCAmelCase )}, {"""score""": 0.3_3_3, """label""": ANY(lowerCAmelCase )}, {"""score""": 0.3_3_3, """label""": ANY(lowerCAmelCase )}, ], [ {"""score""": 0.3_3_3, """label""": ANY(lowerCAmelCase )}, {"""score""": 0.3_3_3, """label""": ANY(lowerCAmelCase )}, {"""score""": 0.3_3_3, """label""": ANY(lowerCAmelCase )}, ], [ {"""score""": 0.3_3_3, """label""": ANY(lowerCAmelCase )}, {"""score""": 0.3_3_3, """label""": ANY(lowerCAmelCase )}, {"""score""": 0.3_3_3, """label""": ANY(lowerCAmelCase )}, ], [ {"""score""": 0.3_3_3, """label""": ANY(lowerCAmelCase )}, {"""score""": 0.3_3_3, """label""": ANY(lowerCAmelCase )}, {"""score""": 0.3_3_3, """label""": ANY(lowerCAmelCase )}, ], [ {"""score""": 0.3_3_3, """label""": ANY(lowerCAmelCase )}, {"""score""": 0.3_3_3, """label""": ANY(lowerCAmelCase )}, {"""score""": 0.3_3_3, """label""": ANY(lowerCAmelCase )}, ], ] , ) @require_tf def lowerCamelCase__ ( self : List[Any] ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: int =pipeline( model="""hf-internal-testing/tiny-random-clip-zero-shot-image-classification""" , framework="""tf""" ) SCREAMING_SNAKE_CASE_: str =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) SCREAMING_SNAKE_CASE_: Dict =image_classifier(lowerCAmelCase , candidate_labels=["""a""", """b""", """c"""] ) self.assertEqual( nested_simplify(lowerCAmelCase ) , [{"""score""": 0.3_3_3, """label""": """a"""}, {"""score""": 0.3_3_3, """label""": """b"""}, {"""score""": 0.3_3_3, """label""": """c"""}] , ) SCREAMING_SNAKE_CASE_: Dict =image_classifier([image] * 5 , candidate_labels=["""A""", """B""", """C"""] , batch_size=2 ) self.assertEqual( nested_simplify(lowerCAmelCase ) , [ [ {"""score""": 0.3_3_3, """label""": ANY(lowerCAmelCase )}, {"""score""": 0.3_3_3, """label""": ANY(lowerCAmelCase )}, {"""score""": 0.3_3_3, """label""": ANY(lowerCAmelCase )}, ], [ {"""score""": 0.3_3_3, """label""": ANY(lowerCAmelCase )}, {"""score""": 0.3_3_3, """label""": ANY(lowerCAmelCase )}, {"""score""": 0.3_3_3, """label""": ANY(lowerCAmelCase )}, ], [ {"""score""": 0.3_3_3, """label""": ANY(lowerCAmelCase )}, {"""score""": 0.3_3_3, """label""": ANY(lowerCAmelCase )}, {"""score""": 0.3_3_3, """label""": ANY(lowerCAmelCase )}, ], [ {"""score""": 0.3_3_3, """label""": ANY(lowerCAmelCase )}, {"""score""": 0.3_3_3, """label""": ANY(lowerCAmelCase )}, {"""score""": 0.3_3_3, """label""": ANY(lowerCAmelCase )}, ], [ {"""score""": 0.3_3_3, """label""": ANY(lowerCAmelCase )}, {"""score""": 0.3_3_3, """label""": ANY(lowerCAmelCase )}, {"""score""": 0.3_3_3, """label""": ANY(lowerCAmelCase )}, ], ] , ) @slow @require_torch def lowerCamelCase__ ( self : List[Any] ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =pipeline( task="""zero-shot-image-classification""" , model="""openai/clip-vit-base-patch32""" , ) # This is an image of 2 cats with remotes and no planes SCREAMING_SNAKE_CASE_: Optional[Any] =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) SCREAMING_SNAKE_CASE_: List[Any] =image_classifier(lowerCAmelCase , candidate_labels=["""cat""", """plane""", """remote"""] ) self.assertEqual( nested_simplify(lowerCAmelCase ) , [ {"""score""": 0.5_1_1, """label""": """remote"""}, {"""score""": 0.4_8_5, """label""": """cat"""}, {"""score""": 0.0_0_4, """label""": """plane"""}, ] , ) SCREAMING_SNAKE_CASE_: str =image_classifier([image] * 5 , candidate_labels=["""cat""", """plane""", """remote"""] , batch_size=2 ) self.assertEqual( nested_simplify(lowerCAmelCase ) , [ [ {"""score""": 0.5_1_1, """label""": """remote"""}, {"""score""": 0.4_8_5, """label""": """cat"""}, {"""score""": 0.0_0_4, """label""": """plane"""}, ], ] * 5 , ) @slow @require_tf def lowerCamelCase__ ( self : Dict ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[str] =pipeline( task="""zero-shot-image-classification""" , model="""openai/clip-vit-base-patch32""" , framework="""tf""" ) # This is an image of 2 cats with remotes and no planes SCREAMING_SNAKE_CASE_: Tuple =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) SCREAMING_SNAKE_CASE_: Tuple =image_classifier(lowerCAmelCase , candidate_labels=["""cat""", """plane""", """remote"""] ) self.assertEqual( nested_simplify(lowerCAmelCase ) , [ {"""score""": 0.5_1_1, """label""": """remote"""}, {"""score""": 0.4_8_5, """label""": """cat"""}, {"""score""": 0.0_0_4, """label""": """plane"""}, ] , ) SCREAMING_SNAKE_CASE_: Optional[int] =image_classifier([image] * 5 , candidate_labels=["""cat""", """plane""", """remote"""] , batch_size=2 ) self.assertEqual( nested_simplify(lowerCAmelCase ) , [ [ {"""score""": 0.5_1_1, """label""": """remote"""}, {"""score""": 0.4_8_5, """label""": """cat"""}, {"""score""": 0.0_0_4, """label""": """plane"""}, ], ] * 5 , )
36
"""simple docstring""" import string def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: List[Any] ="""""" for i in sequence: SCREAMING_SNAKE_CASE_: List[Any] =ord(lowercase ) if 65 <= extract <= 90: output += chr(155 - extract ) elif 97 <= extract <= 122: output += chr(219 - extract ) else: output += i return output def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Any =string.ascii_letters SCREAMING_SNAKE_CASE_: Tuple =string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1] return "".join( letters_reversed[letters.index(lowercase )] if c in letters else c for c in sequence ) def __magic_name__ ( ): from timeit import timeit print("""Running performance benchmarks...""" ) SCREAMING_SNAKE_CASE_: int ="""from string import printable ; from __main__ import atbash, atbash_slow""" print(f'''> atbash_slow(): {timeit("atbash_slow(printable)" , setup=lowercase )} seconds''' ) print(f'''> atbash(): {timeit("atbash(printable)" , setup=lowercase )} seconds''' ) if __name__ == "__main__": for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"): print(f"""{example} encrypted in atbash: {atbash(example)}""") benchmark()
36
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { """google/vivit-b-16x2-kinetics400""": ( """https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json""" ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class a ( UpperCAmelCase__ ): UpperCamelCase : Dict = 'vivit' def __init__( self : Optional[int] , lowerCAmelCase : str=224 , lowerCAmelCase : List[Any]=32 , lowerCAmelCase : List[Any]=[2, 16, 16] , lowerCAmelCase : Any=3 , lowerCAmelCase : Optional[Any]=768 , lowerCAmelCase : Dict=12 , lowerCAmelCase : int=12 , lowerCAmelCase : Any=3072 , lowerCAmelCase : Tuple="gelu_fast" , lowerCAmelCase : Tuple=0.0 , lowerCAmelCase : Any=0.0 , lowerCAmelCase : Dict=0.0_2 , lowerCAmelCase : Any=1E-06 , lowerCAmelCase : Optional[Any]=True , **lowerCAmelCase : List[str] , ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =hidden_size SCREAMING_SNAKE_CASE_: Dict =num_hidden_layers SCREAMING_SNAKE_CASE_: Optional[Any] =num_attention_heads SCREAMING_SNAKE_CASE_: Tuple =intermediate_size SCREAMING_SNAKE_CASE_: List[Any] =hidden_act SCREAMING_SNAKE_CASE_: Dict =hidden_dropout_prob SCREAMING_SNAKE_CASE_: int =attention_probs_dropout_prob SCREAMING_SNAKE_CASE_: Optional[int] =initializer_range SCREAMING_SNAKE_CASE_: int =layer_norm_eps SCREAMING_SNAKE_CASE_: str =image_size SCREAMING_SNAKE_CASE_: List[str] =num_frames SCREAMING_SNAKE_CASE_: Dict =tubelet_size SCREAMING_SNAKE_CASE_: Optional[int] =num_channels SCREAMING_SNAKE_CASE_: Union[str, Any] =qkv_bias super().__init__(**lowerCAmelCase )
36
"""simple docstring""" import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class a : def __init__( self : Union[str, Any] , lowerCAmelCase : List[str]=2 , lowerCAmelCase : int=3 , lowerCAmelCase : Optional[Any]=64 , lowerCAmelCase : Union[str, Any]=None ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Union[str, Any] =np.random.default_rng(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =length SCREAMING_SNAKE_CASE_: Union[str, Any] =rng.normal(size=(length,) ).astype(np.floataa ) SCREAMING_SNAKE_CASE_: Tuple =a * self.x + b + rng.normal(scale=0.1 , size=(length,) ).astype(np.floataa ) def __len__( self : List[Any] ) -> str: '''simple docstring''' return self.length def __getitem__( self : Union[str, Any] , lowerCAmelCase : Any ) -> List[str]: '''simple docstring''' return {"x": self.x[i], "y": self.y[i]} class a ( torch.nn.Module ): def __init__( self : Optional[int] , lowerCAmelCase : str=0 , lowerCAmelCase : List[Any]=0 , lowerCAmelCase : Optional[int]=False ) -> Tuple: '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE_: int =torch.nn.Parameter(torch.tensor([2, 3] ).float() ) SCREAMING_SNAKE_CASE_: int =torch.nn.Parameter(torch.tensor([2, 3] ).float() ) SCREAMING_SNAKE_CASE_: Dict =True def lowerCamelCase__ ( self : str , lowerCAmelCase : Tuple=None ) -> int: '''simple docstring''' if self.first_batch: print(f'''Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}''' ) SCREAMING_SNAKE_CASE_: Union[str, Any] =False return x * self.a[0] + self.b[0] class a ( torch.nn.Module ): def __init__( self : Union[str, Any] , lowerCAmelCase : Any=0 , lowerCAmelCase : List[Any]=0 , lowerCAmelCase : List[Any]=False ) -> str: '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE_: List[str] =torch.nn.Parameter(torch.tensor(lowerCAmelCase ).float() ) SCREAMING_SNAKE_CASE_: Optional[int] =torch.nn.Parameter(torch.tensor(lowerCAmelCase ).float() ) SCREAMING_SNAKE_CASE_: List[Any] =True def lowerCamelCase__ ( self : List[str] , lowerCAmelCase : int=None ) -> Any: '''simple docstring''' if self.first_batch: print(f'''Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}''' ) SCREAMING_SNAKE_CASE_: Optional[int] =False return x * self.a + self.b def __magic_name__ ( lowercase , lowercase = 16 ): from datasets import load_dataset from transformers import AutoTokenizer SCREAMING_SNAKE_CASE_: Optional[Any] =AutoTokenizer.from_pretrained("""bert-base-cased""" ) SCREAMING_SNAKE_CASE_: Optional[int] ={"""train""": """tests/test_samples/MRPC/train.csv""", """validation""": """tests/test_samples/MRPC/dev.csv"""} SCREAMING_SNAKE_CASE_: Any =load_dataset("""csv""" , data_files=lowercase ) SCREAMING_SNAKE_CASE_: Any =datasets["""train"""].unique("""label""" ) SCREAMING_SNAKE_CASE_: List[Any] ={v: i for i, v in enumerate(lowercase )} def tokenize_function(lowercase ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE_: Dict =tokenizer( examples["""sentence1"""] , examples["""sentence2"""] , truncation=lowercase , max_length=lowercase , padding="""max_length""" ) if "label" in examples: SCREAMING_SNAKE_CASE_: Optional[int] =[label_to_id[l] for l in examples["""label"""]] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset SCREAMING_SNAKE_CASE_: List[Any] =datasets.map( lowercase , batched=lowercase , remove_columns=["""sentence1""", """sentence2""", """label"""] , ) def collate_fn(lowercase ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(lowercase , padding="""max_length""" , max_length=128 , return_tensors="""pt""" ) return tokenizer.pad(lowercase , padding="""longest""" , return_tensors="""pt""" ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE_: Optional[int] =DataLoader(tokenized_datasets["""train"""] , shuffle=lowercase , collate_fn=lowercase , batch_size=2 ) SCREAMING_SNAKE_CASE_: Dict =DataLoader(tokenized_datasets["""validation"""] , shuffle=lowercase , collate_fn=lowercase , batch_size=1 ) return train_dataloader, eval_dataloader
36
1
"""simple docstring""" import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _UpperCAmelCase = get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece @require_tokenizers class a ( UpperCAmelCase__ , unittest.TestCase ): UpperCamelCase : List[str] = XLMRobertaTokenizer UpperCamelCase : Any = XLMRobertaTokenizerFast UpperCamelCase : Any = True UpperCamelCase : Optional[Any] = True def lowerCamelCase__ ( self : str ) -> Optional[int]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE_: Optional[int] =XLMRobertaTokenizer(lowerCAmelCase , keep_accents=lowerCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCamelCase__ ( self : str ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: str ="""<pad>""" SCREAMING_SNAKE_CASE_: Any =1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCAmelCase ) , lowerCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCAmelCase ) , lowerCAmelCase ) def lowerCamelCase__ ( self : Any ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE_: str =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<s>""" ) self.assertEqual(vocab_keys[1] , """<pad>""" ) self.assertEqual(vocab_keys[-1] , """<mask>""" ) self.assertEqual(len(lowerCAmelCase ) , 1002 ) def lowerCamelCase__ ( self : Dict ) -> Tuple: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1002 ) def lowerCamelCase__ ( self : Tuple ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[Any] =XLMRobertaTokenizer(lowerCAmelCase , keep_accents=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Dict =tokenizer.tokenize("""This is a test""" ) self.assertListEqual(lowerCAmelCase , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowerCAmelCase ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) SCREAMING_SNAKE_CASE_: List[Any] =tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( lowerCAmelCase , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) SCREAMING_SNAKE_CASE_: Tuple =tokenizer.convert_tokens_to_ids(lowerCAmelCase ) self.assertListEqual( lowerCAmelCase , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) SCREAMING_SNAKE_CASE_: List[Any] =tokenizer.convert_ids_to_tokens(lowerCAmelCase ) self.assertListEqual( lowerCAmelCase , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) def lowerCamelCase__ ( self : Union[str, Any] ) -> Dict: '''simple docstring''' if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return SCREAMING_SNAKE_CASE_: Optional[int] =(self.rust_tokenizer_class, """hf-internal-testing/tiny-xlm-roberta""", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE_: Tuple =self.rust_tokenizer_class.from_pretrained(lowerCAmelCase , **lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Dict =self.tokenizer_class.from_pretrained(lowerCAmelCase , **lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =tempfile.mkdtemp() SCREAMING_SNAKE_CASE_: Tuple =tokenizer_r.save_pretrained(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Union[str, Any] =tokenizer_p.save_pretrained(lowerCAmelCase ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) SCREAMING_SNAKE_CASE_: List[Any] =tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(lowerCAmelCase , lowerCAmelCase ) # Checks everything loads correctly in the same way SCREAMING_SNAKE_CASE_: List[str] =tokenizer_r.from_pretrained(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Any =tokenizer_p.from_pretrained(lowerCAmelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowerCAmelCase , lowerCAmelCase ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(lowerCAmelCase ) # Save tokenizer rust, legacy_format=True SCREAMING_SNAKE_CASE_: Any =tempfile.mkdtemp() SCREAMING_SNAKE_CASE_: List[str] =tokenizer_r.save_pretrained(lowerCAmelCase , legacy_format=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: int =tokenizer_p.save_pretrained(lowerCAmelCase ) # Checks it save with the same files self.assertSequenceEqual(lowerCAmelCase , lowerCAmelCase ) # Checks everything loads correctly in the same way SCREAMING_SNAKE_CASE_: Dict =tokenizer_r.from_pretrained(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple =tokenizer_p.from_pretrained(lowerCAmelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowerCAmelCase , lowerCAmelCase ) ) shutil.rmtree(lowerCAmelCase ) # Save tokenizer rust, legacy_format=False SCREAMING_SNAKE_CASE_: Optional[int] =tempfile.mkdtemp() SCREAMING_SNAKE_CASE_: Optional[int] =tokenizer_r.save_pretrained(lowerCAmelCase , legacy_format=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =tokenizer_p.save_pretrained(lowerCAmelCase ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way SCREAMING_SNAKE_CASE_: Optional[int] =tokenizer_r.from_pretrained(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[Any] =tokenizer_p.from_pretrained(lowerCAmelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowerCAmelCase , lowerCAmelCase ) ) shutil.rmtree(lowerCAmelCase ) @cached_property def lowerCamelCase__ ( self : str ) -> Optional[Any]: '''simple docstring''' return XLMRobertaTokenizer.from_pretrained("""xlm-roberta-base""" ) def lowerCamelCase__ ( self : List[Any] ) -> Any: '''simple docstring''' with tempfile.NamedTemporaryFile() as f: shutil.copyfile(lowerCAmelCase , f.name ) SCREAMING_SNAKE_CASE_: Optional[Any] =XLMRobertaTokenizer(f.name , keep_accents=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: str =pickle.dumps(lowerCAmelCase ) pickle.loads(lowerCAmelCase ) def lowerCamelCase__ ( self : List[str] ) -> List[str]: '''simple docstring''' if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE_: Tuple =self.get_tokenizer() SCREAMING_SNAKE_CASE_: Optional[int] =self.get_rust_tokenizer() SCREAMING_SNAKE_CASE_: List[str] ="""I was born in 92000, and this is falsé.""" SCREAMING_SNAKE_CASE_: Any =tokenizer.tokenize(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[Any] =rust_tokenizer.tokenize(lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: str =tokenizer.encode(lowerCAmelCase , add_special_tokens=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[Any] =rust_tokenizer.encode(lowerCAmelCase , add_special_tokens=lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =self.get_rust_tokenizer() SCREAMING_SNAKE_CASE_: List[Any] =tokenizer.encode(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Dict =rust_tokenizer.encode(lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , lowerCAmelCase ) @slow def lowerCamelCase__ ( self : Dict ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple ="""Hello World!""" SCREAMING_SNAKE_CASE_: Tuple =[0, 3_5378, 6661, 38, 2] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(lowerCAmelCase , self.big_tokenizer.encode(lowerCAmelCase ) ) @slow def lowerCamelCase__ ( self : Optional[int] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[int] =( """This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will""" """ add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth""" ) SCREAMING_SNAKE_CASE_: Union[str, Any] =[ 0, 3293, 83, 10, 4552, 4989, 7986, 678, 10, 5915, 111, 17_9459, 12_4850, 4, 6044, 237, 12, 6, 5, 6, 4, 6780, 705, 15, 1388, 44, 378, 1_0114, 711, 152, 20, 6, 5, 2_2376, 642, 1221, 1_5190, 3_4153, 450, 5608, 959, 1119, 5_7702, 136, 186, 47, 1098, 2_9367, 47, # 4426, # What fairseq tokenizes from "<unk>": "_<" # 3678, # What fairseq tokenizes from "<unk>": "unk" # 2740, # What fairseq tokenizes from "<unk>": ">" 3, # What we tokenize from "<unk>": "<unk>" 6, # Residue from the tokenization: an extra sentencepiece underline 4, 6044, 237, 6284, 5_0901, 528, 31, 90, 34, 927, 2, ] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(lowerCAmelCase , self.big_tokenizer.encode(lowerCAmelCase ) ) @slow def lowerCamelCase__ ( self : Dict ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple ={"""input_ids""": [[0, 1_1062, 8_2772, 7, 15, 8_2772, 538, 5_1529, 237, 1_7198, 1290, 206, 9, 21_5175, 1314, 136, 1_7198, 1290, 206, 9, 5_6359, 42, 12_2009, 9, 1_6466, 16, 8_7344, 4537, 9, 4717, 7_8381, 6, 15_9958, 7, 15, 2_4480, 618, 4, 527, 2_2693, 5428, 4, 2777, 2_4480, 9874, 4, 4_3523, 594, 4, 803, 1_8392, 3_3189, 18, 4, 4_3523, 2_4447, 1_2399, 100, 2_4955, 8_3658, 9626, 14_4057, 15, 839, 2_2335, 16, 136, 2_4955, 8_3658, 8_3479, 15, 3_9102, 724, 16, 678, 645, 2789, 1328, 4589, 42, 12_2009, 11_5774, 23, 805, 1328, 4_6876, 7, 136, 5_3894, 1940, 4_2227, 4_1159, 1_7721, 823, 425, 4, 2_7512, 9_8722, 206, 136, 5531, 4970, 919, 1_7336, 5, 2], [0, 2_0080, 618, 83, 8_2775, 47, 479, 9, 1517, 73, 5_3894, 333, 8_0581, 11_0117, 1_8811, 5256, 1295, 51, 15_2526, 297, 7986, 390, 12_4416, 538, 3_5431, 214, 98, 1_5044, 2_5737, 136, 7108, 4_3701, 23, 756, 13_5355, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 581, 6_3773, 11_9455, 6, 14_7797, 8_8203, 7, 645, 70, 21, 3285, 1_0269, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowerCAmelCase , model_name="""xlm-roberta-base""" , revision="""d9d8a8ea5eb94b1c6654ae9249df7793cd2933d3""" , )
36
"""simple docstring""" def __magic_name__ ( lowercase ): if upper_limit < 0: raise ValueError("""Limit for the Catalan sequence must be ≥ 0""" ) SCREAMING_SNAKE_CASE_: Tuple =[0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 SCREAMING_SNAKE_CASE_: Any =1 if upper_limit > 0: SCREAMING_SNAKE_CASE_: List[str] =1 # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i for i in range(2 , upper_limit + 1 ): for j in range(lowercase ): catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1] return catalan_list if __name__ == "__main__": print("""\n********* Catalan Numbers Using Dynamic Programming ************\n""") print("""\n*** Enter -1 at any time to quit ***""") print("""\nEnter the upper limit (≥ 0) for the Catalan number sequence: """, end="""""") try: while True: _UpperCAmelCase = int(input().strip()) if N < 0: print("""\n********* Goodbye!! ************""") break else: print(f"""The Catalan numbers from 0 through {N} are:""") print(catalan_numbers(N)) print("""Try another upper limit for the sequence: """, end="""""") except (NameError, ValueError): print("""\n********* Invalid input, goodbye! ************\n""") import doctest doctest.testmod()
36
1
"""simple docstring""" from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...file_utils import TensorType, is_torch_available from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { """facebook/blenderbot_small-90M""": """https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/config.json""", # See all BlenderbotSmall models at https://huggingface.co/models?filter=blenderbot_small } class a ( UpperCAmelCase__ ): UpperCamelCase : Tuple = 'blenderbot-small' UpperCamelCase : Union[str, Any] = ['past_key_values'] UpperCamelCase : List[Any] = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self : List[Any] , lowerCAmelCase : Dict=5_0265 , lowerCAmelCase : Dict=512 , lowerCAmelCase : Any=8 , lowerCAmelCase : str=2048 , lowerCAmelCase : Union[str, Any]=16 , lowerCAmelCase : List[str]=8 , lowerCAmelCase : str=2048 , lowerCAmelCase : Optional[int]=16 , lowerCAmelCase : List[Any]=0.0 , lowerCAmelCase : int=0.0 , lowerCAmelCase : Optional[int]=True , lowerCAmelCase : Optional[Any]=True , lowerCAmelCase : int="gelu" , lowerCAmelCase : Union[str, Any]=512 , lowerCAmelCase : Any=0.1 , lowerCAmelCase : List[Any]=0.0 , lowerCAmelCase : Union[str, Any]=0.0 , lowerCAmelCase : List[Any]=0.0_2 , lowerCAmelCase : Tuple=1 , lowerCAmelCase : str=False , lowerCAmelCase : str=0 , lowerCAmelCase : int=1 , lowerCAmelCase : Any=2 , lowerCAmelCase : int=2 , **lowerCAmelCase : Tuple , ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE_: Union[str, Any] =vocab_size SCREAMING_SNAKE_CASE_: Any =max_position_embeddings SCREAMING_SNAKE_CASE_: Any =d_model SCREAMING_SNAKE_CASE_: int =encoder_ffn_dim SCREAMING_SNAKE_CASE_: Optional[int] =encoder_layers SCREAMING_SNAKE_CASE_: Any =encoder_attention_heads SCREAMING_SNAKE_CASE_: Optional[Any] =decoder_ffn_dim SCREAMING_SNAKE_CASE_: Optional[int] =decoder_layers SCREAMING_SNAKE_CASE_: List[str] =decoder_attention_heads SCREAMING_SNAKE_CASE_: List[Any] =dropout SCREAMING_SNAKE_CASE_: Dict =attention_dropout SCREAMING_SNAKE_CASE_: Optional[Any] =activation_dropout SCREAMING_SNAKE_CASE_: Union[str, Any] =activation_function SCREAMING_SNAKE_CASE_: Any =init_std SCREAMING_SNAKE_CASE_: List[str] =encoder_layerdrop SCREAMING_SNAKE_CASE_: Optional[Any] =decoder_layerdrop SCREAMING_SNAKE_CASE_: Optional[Any] =use_cache SCREAMING_SNAKE_CASE_: int =encoder_layers SCREAMING_SNAKE_CASE_: str =scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( pad_token_id=lowerCAmelCase , bos_token_id=lowerCAmelCase , eos_token_id=lowerCAmelCase , is_encoder_decoder=lowerCAmelCase , decoder_start_token_id=lowerCAmelCase , forced_eos_token_id=lowerCAmelCase , **lowerCAmelCase , ) class a ( UpperCAmelCase__ ): @property def lowerCamelCase__ ( self : List[Any] ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: SCREAMING_SNAKE_CASE_: Tuple =OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}), ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}), ] ) if self.use_past: SCREAMING_SNAKE_CASE_: List[Any] ={0: """batch"""} SCREAMING_SNAKE_CASE_: Dict ={0: """batch""", 1: """past_decoder_sequence + sequence"""} else: SCREAMING_SNAKE_CASE_: Optional[int] ={0: """batch""", 1: """decoder_sequence"""} SCREAMING_SNAKE_CASE_: Optional[int] ={0: """batch""", 1: """decoder_sequence"""} if self.use_past: self.fill_with_past_key_values_(lowerCAmelCase , direction="""inputs""" ) elif self.task == "causal-lm": # TODO: figure this case out. SCREAMING_SNAKE_CASE_: Union[str, Any] =OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}), ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}), ] ) if self.use_past: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Dict =self.num_layers for i in range(lowerCAmelCase ): SCREAMING_SNAKE_CASE_: Dict ={0: """batch""", 2: """past_sequence + sequence"""} SCREAMING_SNAKE_CASE_: Union[str, Any] ={0: """batch""", 2: """past_sequence + sequence"""} else: SCREAMING_SNAKE_CASE_: int =OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}), ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}), ("""decoder_input_ids""", {0: """batch""", 1: """decoder_sequence"""}), ("""decoder_attention_mask""", {0: """batch""", 1: """decoder_sequence"""}), ] ) return common_inputs @property def lowerCamelCase__ ( self : Dict ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: SCREAMING_SNAKE_CASE_: Tuple =super().outputs else: SCREAMING_SNAKE_CASE_: Optional[Any] =super(lowerCAmelCase , self ).outputs if self.use_past: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: int =self.num_layers for i in range(lowerCAmelCase ): SCREAMING_SNAKE_CASE_: List[Any] ={0: """batch""", 2: """past_sequence + sequence"""} SCREAMING_SNAKE_CASE_: List[Any] ={0: """batch""", 2: """past_sequence + sequence"""} return common_outputs def lowerCamelCase__ ( self : List[str] , lowerCAmelCase : PreTrainedTokenizer , lowerCAmelCase : int = -1 , lowerCAmelCase : int = -1 , lowerCAmelCase : bool = False , lowerCAmelCase : Optional[TensorType] = None , ) -> Mapping[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[int] =self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) # Generate decoder inputs SCREAMING_SNAKE_CASE_: List[str] =seq_length if not self.use_past else 1 SCREAMING_SNAKE_CASE_: Union[str, Any] =self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Union[str, Any] ={f'''decoder_{name}''': tensor for name, tensor in decoder_inputs.items()} SCREAMING_SNAKE_CASE_: Union[str, Any] =dict(**lowerCAmelCase , **lowerCAmelCase ) if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Tuple =common_inputs["""input_ids"""].shape SCREAMING_SNAKE_CASE_: Optional[Any] =common_inputs["""decoder_input_ids"""].shape[1] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Any =self.num_attention_heads SCREAMING_SNAKE_CASE_: Optional[int] =( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) SCREAMING_SNAKE_CASE_: int =decoder_seq_length + 3 SCREAMING_SNAKE_CASE_: str =( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) SCREAMING_SNAKE_CASE_: List[str] =torch.cat( [common_inputs["""decoder_attention_mask"""], torch.ones(lowerCAmelCase , lowerCAmelCase )] , dim=1 ) SCREAMING_SNAKE_CASE_: Any =[] # If the number of encoder and decoder layers are present in the model configuration, both are considered SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: int =self.num_layers SCREAMING_SNAKE_CASE_: Dict =min(lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple =max(lowerCAmelCase , lowerCAmelCase ) - min_num_layers SCREAMING_SNAKE_CASE_: Optional[int] ="""encoder""" if num_encoder_layers > num_decoder_layers else """decoder""" for _ in range(lowerCAmelCase ): common_inputs["past_key_values"].append( ( torch.zeros(lowerCAmelCase ), torch.zeros(lowerCAmelCase ), torch.zeros(lowerCAmelCase ), torch.zeros(lowerCAmelCase ), ) ) # TODO: test this. SCREAMING_SNAKE_CASE_: List[Any] =encoder_shape if remaining_side_name == """encoder""" else decoder_shape for _ in range(lowerCAmelCase , lowerCAmelCase ): common_inputs["past_key_values"].append((torch.zeros(lowerCAmelCase ), torch.zeros(lowerCAmelCase )) ) return common_inputs def lowerCamelCase__ ( self : Any , lowerCAmelCase : PreTrainedTokenizer , lowerCAmelCase : int = -1 , lowerCAmelCase : int = -1 , lowerCAmelCase : bool = False , lowerCAmelCase : Optional[TensorType] = None , ) -> Mapping[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[int] =self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[int] =common_inputs["""input_ids"""].shape # Not using the same length for past_key_values SCREAMING_SNAKE_CASE_: List[Any] =seqlen + 2 SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Union[str, Any] =self.num_layers SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[Any] =self.num_attention_heads SCREAMING_SNAKE_CASE_: List[str] =( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) SCREAMING_SNAKE_CASE_: Optional[int] =common_inputs["""attention_mask"""].dtype SCREAMING_SNAKE_CASE_: List[Any] =torch.cat( [common_inputs["""attention_mask"""], torch.ones(lowerCAmelCase , lowerCAmelCase , dtype=lowerCAmelCase )] , dim=1 ) SCREAMING_SNAKE_CASE_: List[str] =[ (torch.zeros(lowerCAmelCase ), torch.zeros(lowerCAmelCase )) for _ in range(lowerCAmelCase ) ] return common_inputs def lowerCamelCase__ ( self : Any , lowerCAmelCase : PreTrainedTokenizer , lowerCAmelCase : int = -1 , lowerCAmelCase : int = -1 , lowerCAmelCase : bool = False , lowerCAmelCase : Optional[TensorType] = None , ) -> Mapping[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =compute_effective_axis_dimension( lowerCAmelCase , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX SCREAMING_SNAKE_CASE_: str =tokenizer.num_special_tokens_to_add(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: str =compute_effective_axis_dimension( lowerCAmelCase , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=lowerCAmelCase ) # Generate dummy inputs according to compute batch and sequence SCREAMING_SNAKE_CASE_: Dict =[""" """.join([tokenizer.unk_token] ) * seq_length] * batch_size SCREAMING_SNAKE_CASE_: Tuple =dict(tokenizer(lowerCAmelCase , return_tensors=lowerCAmelCase ) ) return common_inputs def lowerCamelCase__ ( self : Tuple , lowerCAmelCase : PreTrainedTokenizer , lowerCAmelCase : int = -1 , lowerCAmelCase : int = -1 , lowerCAmelCase : bool = False , lowerCAmelCase : Optional[TensorType] = None , ) -> Mapping[str, Any]: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: SCREAMING_SNAKE_CASE_: Dict =self._generate_dummy_inputs_for_default_and_seqaseq_lm( lowerCAmelCase , batch_size=lowerCAmelCase , seq_length=lowerCAmelCase , is_pair=lowerCAmelCase , framework=lowerCAmelCase ) elif self.task == "causal-lm": SCREAMING_SNAKE_CASE_: int =self._generate_dummy_inputs_for_causal_lm( lowerCAmelCase , batch_size=lowerCAmelCase , seq_length=lowerCAmelCase , is_pair=lowerCAmelCase , framework=lowerCAmelCase ) else: SCREAMING_SNAKE_CASE_: Tuple =self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowerCAmelCase , batch_size=lowerCAmelCase , seq_length=lowerCAmelCase , is_pair=lowerCAmelCase , framework=lowerCAmelCase ) return common_inputs def lowerCamelCase__ ( self : Union[str, Any] , lowerCAmelCase : Dict , lowerCAmelCase : Any , lowerCAmelCase : Dict , lowerCAmelCase : List[Any] ) -> int: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: SCREAMING_SNAKE_CASE_: Tuple =super()._flatten_past_key_values_(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) else: SCREAMING_SNAKE_CASE_: List[str] =super(lowerCAmelCase , self )._flatten_past_key_values_( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase )
36
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig _UpperCAmelCase = { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/config.json""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/config.json""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/config.json""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/config.json""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/config.json""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/config.json""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json""", } class a ( UpperCAmelCase__ ): UpperCamelCase : Any = 'albert' def __init__( self : Dict , lowerCAmelCase : List[str]=3_0000 , lowerCAmelCase : List[Any]=128 , lowerCAmelCase : List[str]=4096 , lowerCAmelCase : str=12 , lowerCAmelCase : str=1 , lowerCAmelCase : Tuple=64 , lowerCAmelCase : Dict=1_6384 , lowerCAmelCase : int=1 , lowerCAmelCase : str="gelu_new" , lowerCAmelCase : Dict=0 , lowerCAmelCase : Optional[Any]=0 , lowerCAmelCase : str=512 , lowerCAmelCase : Optional[int]=2 , lowerCAmelCase : List[Any]=0.0_2 , lowerCAmelCase : Union[str, Any]=1E-12 , lowerCAmelCase : Tuple=0.1 , lowerCAmelCase : List[Any]="absolute" , lowerCAmelCase : List[Any]=0 , lowerCAmelCase : int=2 , lowerCAmelCase : Optional[int]=3 , **lowerCAmelCase : int , ) -> Tuple: '''simple docstring''' super().__init__(pad_token_id=lowerCAmelCase , bos_token_id=lowerCAmelCase , eos_token_id=lowerCAmelCase , **lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =vocab_size SCREAMING_SNAKE_CASE_: Optional[int] =embedding_size SCREAMING_SNAKE_CASE_: Optional[int] =hidden_size SCREAMING_SNAKE_CASE_: Tuple =num_hidden_layers SCREAMING_SNAKE_CASE_: Any =num_hidden_groups SCREAMING_SNAKE_CASE_: List[Any] =num_attention_heads SCREAMING_SNAKE_CASE_: List[Any] =inner_group_num SCREAMING_SNAKE_CASE_: Optional[int] =hidden_act SCREAMING_SNAKE_CASE_: int =intermediate_size SCREAMING_SNAKE_CASE_: Any =hidden_dropout_prob SCREAMING_SNAKE_CASE_: Union[str, Any] =attention_probs_dropout_prob SCREAMING_SNAKE_CASE_: int =max_position_embeddings SCREAMING_SNAKE_CASE_: Any =type_vocab_size SCREAMING_SNAKE_CASE_: int =initializer_range SCREAMING_SNAKE_CASE_: List[Any] =layer_norm_eps SCREAMING_SNAKE_CASE_: Dict =classifier_dropout_prob SCREAMING_SNAKE_CASE_: int =position_embedding_type class a ( UpperCAmelCase__ ): @property def lowerCamelCase__ ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": SCREAMING_SNAKE_CASE_: str ={0: """batch""", 1: """choice""", 2: """sequence"""} else: SCREAMING_SNAKE_CASE_: Dict ={0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
36
1
"""simple docstring""" import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from xgboost import XGBClassifier def __magic_name__ ( lowercase ): return (data["data"], data["target"]) def __magic_name__ ( lowercase , lowercase ): SCREAMING_SNAKE_CASE_: Dict =XGBClassifier() classifier.fit(lowercase , lowercase ) return classifier def __magic_name__ ( ): SCREAMING_SNAKE_CASE_: Optional[Any] =load_iris() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Tuple =data_handling(lowercase ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[Any] =train_test_split( lowercase , lowercase , test_size=0.25 ) SCREAMING_SNAKE_CASE_: Tuple =iris["""target_names"""] # Create an XGBoost Classifier from the training data SCREAMING_SNAKE_CASE_: Optional[int] =xgboost(lowercase , lowercase ) # Display the confusion matrix of the classifier with both training and test sets ConfusionMatrixDisplay.from_estimator( lowercase , lowercase , lowercase , display_labels=lowercase , cmap="""Blues""" , normalize="""true""" , ) plt.title("""Normalized Confusion Matrix - IRIS Dataset""" ) plt.show() if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
36
"""simple docstring""" from collections import Counter from pathlib import Path from typing import Optional, Tuple import yaml class a ( yaml.SafeLoader ): def lowerCamelCase__ ( self : int , lowerCAmelCase : List[str] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =[self.constructed_objects[key_node] for key_node, _ in node.value] SCREAMING_SNAKE_CASE_: Any =[tuple(lowerCAmelCase ) if isinstance(lowerCAmelCase , lowerCAmelCase ) else key for key in keys] SCREAMING_SNAKE_CASE_: Dict =Counter(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =[key for key in counter if counter[key] > 1] if duplicate_keys: raise TypeError(f'''Got duplicate yaml keys: {duplicate_keys}''' ) def lowerCamelCase__ ( self : Tuple , lowerCAmelCase : str , lowerCAmelCase : Optional[int]=False ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =super().construct_mapping(lowerCAmelCase , deep=lowerCAmelCase ) self._check_no_duplicates_on_constructed_node(lowerCAmelCase ) return mapping def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Dict =list(readme_content.splitlines() ) if full_content and full_content[0] == "---" and "---" in full_content[1:]: SCREAMING_SNAKE_CASE_: Union[str, Any] =full_content[1:].index("""---""" ) + 1 SCREAMING_SNAKE_CASE_: List[str] ="""\n""".join(full_content[1:sep_idx] ) return yamlblock, "\n".join(full_content[sep_idx + 1 :] ) return None, "\n".join(lowercase ) class a ( UpperCAmelCase__ ): # class attributes UpperCamelCase : Tuple = {'train_eval_index'} # train-eval-index in the YAML metadata @classmethod def lowerCamelCase__ ( cls : List[Any] , lowerCAmelCase : Path ) -> "DatasetMetadata": '''simple docstring''' with open(lowerCAmelCase , encoding="""utf-8""" ) as readme_file: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Union[str, Any] =_split_yaml_from_readme(readme_file.read() ) if yaml_string is not None: return cls.from_yaml_string(lowerCAmelCase ) else: return cls() def lowerCamelCase__ ( self : Any , lowerCAmelCase : Path ) -> List[str]: '''simple docstring''' if path.exists(): with open(lowerCAmelCase , encoding="""utf-8""" ) as readme_file: SCREAMING_SNAKE_CASE_: str =readme_file.read() else: SCREAMING_SNAKE_CASE_: str =None SCREAMING_SNAKE_CASE_: Tuple =self._to_readme(lowerCAmelCase ) with open(lowerCAmelCase , """w""" , encoding="""utf-8""" ) as readme_file: readme_file.write(lowerCAmelCase ) def lowerCamelCase__ ( self : Optional[Any] , lowerCAmelCase : Optional[str] = None ) -> str: '''simple docstring''' if readme_content is not None: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[str] =_split_yaml_from_readme(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] ="""---\n""" + self.to_yaml_string() + """---\n""" + content else: SCREAMING_SNAKE_CASE_: List[Any] ="""---\n""" + self.to_yaml_string() + """---\n""" return full_content @classmethod def lowerCamelCase__ ( cls : Optional[int] , lowerCAmelCase : str ) -> "DatasetMetadata": '''simple docstring''' SCREAMING_SNAKE_CASE_: int =yaml.load(lowerCAmelCase , Loader=_NoDuplicateSafeLoader ) or {} # Convert the YAML keys to DatasetMetadata fields SCREAMING_SNAKE_CASE_: List[Any] ={ (key.replace("""-""" , """_""" ) if key.replace("""-""" , """_""" ) in cls._FIELDS_WITH_DASHES else key): value for key, value in metadata_dict.items() } return cls(**lowerCAmelCase ) def lowerCamelCase__ ( self : Dict ) -> str: '''simple docstring''' return yaml.safe_dump( { (key.replace("""_""" , """-""" ) if key in self._FIELDS_WITH_DASHES else key): value for key, value in self.items() } , sort_keys=lowerCAmelCase , allow_unicode=lowerCAmelCase , encoding="""utf-8""" , ).decode("""utf-8""" ) _UpperCAmelCase = { """image-classification""": [], """translation""": [], """image-segmentation""": [], """fill-mask""": [], """automatic-speech-recognition""": [], """token-classification""": [], """sentence-similarity""": [], """audio-classification""": [], """question-answering""": [], """summarization""": [], """zero-shot-classification""": [], """table-to-text""": [], """feature-extraction""": [], """other""": [], """multiple-choice""": [], """text-classification""": [], """text-to-image""": [], """text2text-generation""": [], """zero-shot-image-classification""": [], """tabular-classification""": [], """tabular-regression""": [], """image-to-image""": [], """tabular-to-text""": [], """unconditional-image-generation""": [], """text-retrieval""": [], """text-to-speech""": [], """object-detection""": [], """audio-to-audio""": [], """text-generation""": [], """conversational""": [], """table-question-answering""": [], """visual-question-answering""": [], """image-to-text""": [], """reinforcement-learning""": [], """voice-activity-detection""": [], """time-series-forecasting""": [], """document-question-answering""": [], } if __name__ == "__main__": from argparse import ArgumentParser _UpperCAmelCase = ArgumentParser(usage="""Validate the yaml metadata block of a README.md file.""") ap.add_argument("""readme_filepath""") _UpperCAmelCase = ap.parse_args() _UpperCAmelCase = Path(args.readme_filepath) _UpperCAmelCase = DatasetMetadata.from_readme(readme_filepath) print(dataset_metadata) dataset_metadata.to_readme(readme_filepath)
36
1
"""simple docstring""" import json import logging import os import sys from pathlib import Path import finetune_rag from transformers.file_utils import is_apex_available from transformers.testing_utils import ( TestCasePlus, execute_subprocess_async, require_ray, require_torch_gpu, require_torch_multi_gpu, ) logging.basicConfig(level=logging.DEBUG) _UpperCAmelCase = logging.getLogger() _UpperCAmelCase = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class a ( UpperCAmelCase__ ): def lowerCamelCase__ ( self : str , lowerCAmelCase : List[str] ) -> Dict: '''simple docstring''' os.makedirs(lowerCAmelCase , exist_ok=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Union[str, Any] ={"""source""": """What is love ?""", """target""": """life"""} SCREAMING_SNAKE_CASE_: List[Any] ={"""train""": 12, """val""": 2, """test""": 2} for split in ["train", "test", "val"]: for field in ["source", "target"]: SCREAMING_SNAKE_CASE_: Optional[Any] ="""\n""".join([contents[field]] * n_lines[split] ) with open(os.path.join(lowerCAmelCase , f'''{split}.{field}''' ) , """w""" ) as f: f.write(lowerCAmelCase ) def lowerCamelCase__ ( self : Optional[Any] , lowerCAmelCase : int , lowerCAmelCase : str = "pytorch" ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE_: Optional[int] =os.path.join(lowerCAmelCase , """output""" ) SCREAMING_SNAKE_CASE_: Optional[Any] =os.path.join(lowerCAmelCase , """data""" ) self._create_dummy_data(data_dir=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Union[str, Any] =f''' --data_dir {data_dir} \ --output_dir {output_dir} \ --model_name_or_path facebook/rag-sequence-base \ --model_type rag_sequence \ --do_train \ --do_predict \ --n_val -1 \ --val_check_interval 1.0 \ --train_batch_size 2 \ --eval_batch_size 1 \ --max_source_length 25 \ --max_target_length 25 \ --val_max_target_length 25 \ --test_max_target_length 25 \ --label_smoothing 0.1 \ --dropout 0.1 \ --attention_dropout 0.1 \ --weight_decay 0.001 \ --adam_epsilon 1e-08 \ --max_grad_norm 0.1 \ --lr_scheduler polynomial \ --learning_rate 3e-04 \ --num_train_epochs 1 \ --warmup_steps 4 \ --gradient_accumulation_steps 1 \ --distributed-port 8787 \ --use_dummy_dataset 1 \ --distributed_retriever {distributed_retriever} \ '''.split() if gpus > 0: testargs.append(f'''--gpus={gpus}''' ) if is_apex_available(): testargs.append("""--fp16""" ) else: testargs.append("""--gpus=0""" ) testargs.append("""--distributed_backend=ddp_cpu""" ) testargs.append("""--num_processes=2""" ) SCREAMING_SNAKE_CASE_: Optional[int] =[sys.executable, str(Path(finetune_rag.__file__ ).resolve() )] + testargs execute_subprocess_async(lowerCAmelCase , env=self.get_env() ) SCREAMING_SNAKE_CASE_: List[Any] =os.path.join(lowerCAmelCase , """metrics.json""" ) with open(lowerCAmelCase ) as f: SCREAMING_SNAKE_CASE_: Any =json.load(lowerCAmelCase ) return result @require_torch_gpu def lowerCamelCase__ ( self : Dict ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[Any] =self._run_finetune(gpus=1 ) self.assertGreaterEqual(result["""test"""][0]["""test_avg_em"""] , 0.2 ) @require_torch_multi_gpu def lowerCamelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =self._run_finetune(gpus=2 ) self.assertGreaterEqual(result["""test"""][0]["""test_avg_em"""] , 0.2 ) @require_torch_gpu @require_ray def lowerCamelCase__ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[Any] =self._run_finetune(gpus=1 , distributed_retriever="""ray""" ) self.assertGreaterEqual(result["""test"""][0]["""test_avg_em"""] , 0.2 ) @require_torch_multi_gpu @require_ray def lowerCamelCase__ ( self : List[str] ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[Any] =self._run_finetune(gpus=1 , distributed_retriever="""ray""" ) self.assertGreaterEqual(result["""test"""][0]["""test_avg_em"""] , 0.2 )
36
"""simple docstring""" import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from xgboost import XGBClassifier def __magic_name__ ( lowercase ): return (data["data"], data["target"]) def __magic_name__ ( lowercase , lowercase ): SCREAMING_SNAKE_CASE_: Dict =XGBClassifier() classifier.fit(lowercase , lowercase ) return classifier def __magic_name__ ( ): SCREAMING_SNAKE_CASE_: Optional[Any] =load_iris() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Tuple =data_handling(lowercase ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[Any] =train_test_split( lowercase , lowercase , test_size=0.25 ) SCREAMING_SNAKE_CASE_: Tuple =iris["""target_names"""] # Create an XGBoost Classifier from the training data SCREAMING_SNAKE_CASE_: Optional[int] =xgboost(lowercase , lowercase ) # Display the confusion matrix of the classifier with both training and test sets ConfusionMatrixDisplay.from_estimator( lowercase , lowercase , lowercase , display_labels=lowercase , cmap="""Blues""" , normalize="""true""" , ) plt.title("""Normalized Confusion Matrix - IRIS Dataset""" ) plt.show() if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
36
1
"""simple docstring""" from typing import Optional from .. import Features, NamedSplit from ..packaged_modules.text.text import Text from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class a ( UpperCAmelCase__ ): def __init__( self : Tuple , lowerCAmelCase : NestedDataStructureLike[PathLike] , lowerCAmelCase : Optional[NamedSplit] = None , lowerCAmelCase : Optional[Features] = None , lowerCAmelCase : str = None , lowerCAmelCase : bool = False , lowerCAmelCase : bool = False , lowerCAmelCase : Optional[int] = None , **lowerCAmelCase : Dict , ) -> str: '''simple docstring''' super().__init__( lowerCAmelCase , split=lowerCAmelCase , features=lowerCAmelCase , cache_dir=lowerCAmelCase , keep_in_memory=lowerCAmelCase , streaming=lowerCAmelCase , num_proc=lowerCAmelCase , **lowerCAmelCase , ) SCREAMING_SNAKE_CASE_: Tuple =path_or_paths if isinstance(lowerCAmelCase , lowerCAmelCase ) else {self.split: path_or_paths} SCREAMING_SNAKE_CASE_: Optional[Any] =Text( cache_dir=lowerCAmelCase , data_files=lowerCAmelCase , features=lowerCAmelCase , **lowerCAmelCase , ) def lowerCamelCase__ ( self : Optional[Any] ) -> int: '''simple docstring''' if self.streaming: SCREAMING_SNAKE_CASE_: Any =self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: SCREAMING_SNAKE_CASE_: Tuple =None SCREAMING_SNAKE_CASE_: Optional[Any] =None SCREAMING_SNAKE_CASE_: Optional[int] =None SCREAMING_SNAKE_CASE_: Any =None self.builder.download_and_prepare( download_config=lowerCAmelCase , download_mode=lowerCAmelCase , verification_mode=lowerCAmelCase , base_path=lowerCAmelCase , num_proc=self.num_proc , ) SCREAMING_SNAKE_CASE_: Any =self.builder.as_dataset( split=self.split , verification_mode=lowerCAmelCase , in_memory=self.keep_in_memory ) return dataset
36
"""simple docstring""" from typing import Dict import numpy as np import torch from . import residue_constants as rc from .tensor_utils import tensor_tree_map, tree_map def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Optional[Any] =[] SCREAMING_SNAKE_CASE_: List[str] =[] SCREAMING_SNAKE_CASE_: Any =[] for rt in rc.restypes: SCREAMING_SNAKE_CASE_: Optional[int] =rc.restype_name_to_atomaa_names[rc.restype_atoa[rt]] restype_atomaa_to_atomaa_list.append([(rc.atom_order[name] if name else 0) for name in atom_names] ) SCREAMING_SNAKE_CASE_: Any ={name: i for i, name in enumerate(lowercase )} restype_atomaa_to_atomaa_list.append( [(atom_name_to_idxaa[name] if name in atom_name_to_idxaa else 0) for name in rc.atom_types] ) restype_atomaa_mask_list.append([(1.0 if name else 0.0) for name in atom_names] ) # Add dummy mapping for restype 'UNK' restype_atomaa_to_atomaa_list.append([0] * 14 ) restype_atomaa_to_atomaa_list.append([0] * 37 ) restype_atomaa_mask_list.append([0.0] * 14 ) SCREAMING_SNAKE_CASE_: Union[str, Any] =torch.tensor( lowercase , dtype=torch.intaa , device=protein["""aatype"""].device , ) SCREAMING_SNAKE_CASE_: Optional[Any] =torch.tensor( lowercase , dtype=torch.intaa , device=protein["""aatype"""].device , ) SCREAMING_SNAKE_CASE_: List[str] =torch.tensor( lowercase , dtype=torch.floataa , device=protein["""aatype"""].device , ) SCREAMING_SNAKE_CASE_: Optional[Any] =protein["""aatype"""].to(torch.long ) # create the mapping for (residx, atom14) --> atom37, i.e. an array # with shape (num_res, 14) containing the atom37 indices for this protein SCREAMING_SNAKE_CASE_: List[str] =restype_atomaa_to_atomaa[protein_aatype] SCREAMING_SNAKE_CASE_: Any =restype_atomaa_mask[protein_aatype] SCREAMING_SNAKE_CASE_: Tuple =residx_atomaa_mask SCREAMING_SNAKE_CASE_: Dict =residx_atomaa_to_atomaa.long() # create the gather indices for mapping back SCREAMING_SNAKE_CASE_: Dict =restype_atomaa_to_atomaa[protein_aatype] SCREAMING_SNAKE_CASE_: Optional[int] =residx_atomaa_to_atomaa.long() # create the corresponding mask SCREAMING_SNAKE_CASE_: Optional[int] =torch.zeros([21, 37] , dtype=torch.floataa , device=protein["""aatype"""].device ) for restype, restype_letter in enumerate(rc.restypes ): SCREAMING_SNAKE_CASE_: int =rc.restype_atoa[restype_letter] SCREAMING_SNAKE_CASE_: Any =rc.residue_atoms[restype_name] for atom_name in atom_names: SCREAMING_SNAKE_CASE_: Optional[int] =rc.atom_order[atom_name] SCREAMING_SNAKE_CASE_: Dict =1 SCREAMING_SNAKE_CASE_: List[str] =restype_atomaa_mask[protein_aatype] SCREAMING_SNAKE_CASE_: List[Any] =residx_atomaa_mask return protein def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Any =tree_map(lambda lowercase : torch.tensor(lowercase , device=batch["""aatype"""].device ) , lowercase , np.ndarray ) SCREAMING_SNAKE_CASE_: int =tensor_tree_map(lambda lowercase : np.array(lowercase ) , make_atomaa_masks(lowercase ) ) return out
36
1
"""simple docstring""" from __future__ import annotations _UpperCAmelCase = [True] * 1_0_0_0_0_0_1 _UpperCAmelCase = 2 while i * i <= 1_0_0_0_0_0_0: if seive[i]: for j in range(i * i, 1_0_0_0_0_0_1, i): _UpperCAmelCase = False i += 1 def __magic_name__ ( lowercase ): return seive[n] def __magic_name__ ( lowercase ): return any(digit in """02468""" for digit in str(lowercase ) ) def __magic_name__ ( lowercase = 100_0000 ): SCREAMING_SNAKE_CASE_: str =[2] # result already includes the number 2. for num in range(3 , limit + 1 , 2 ): if is_prime(lowercase ) and not contains_an_even_digit(lowercase ): SCREAMING_SNAKE_CASE_: Any =str(lowercase ) SCREAMING_SNAKE_CASE_: str =[int(str_num[j:] + str_num[:j] ) for j in range(len(lowercase ) )] if all(is_prime(lowercase ) for i in list_nums ): result.append(lowercase ) return result def __magic_name__ ( ): return len(find_circular_primes() ) if __name__ == "__main__": print(f"""{len(find_circular_primes()) = }""")
36
"""simple docstring""" from pathlib import Path from typing import List from transformers import is_torch_available, is_vision_available from transformers.testing_utils import get_tests_dir, is_tool_test from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText if is_torch_available(): import torch if is_vision_available(): from PIL import Image _UpperCAmelCase = ["""text""", """image""", """audio"""] def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: str =[] for input_type in input_types: if input_type == "text": inputs.append("""Text input""" ) elif input_type == "image": inputs.append( Image.open(Path(get_tests_dir("""fixtures/tests_samples/COCO""" ) ) / """000000039769.png""" ).resize((512, 512) ) ) elif input_type == "audio": inputs.append(torch.ones(3000 ) ) elif isinstance(lowercase , lowercase ): inputs.append(create_inputs(lowercase ) ) else: raise ValueError(f'''Invalid type requested: {input_type}''' ) return inputs def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: int =[] for output in outputs: if isinstance(lowercase , (str, AgentText) ): output_types.append("""text""" ) elif isinstance(lowercase , (Image.Image, AgentImage) ): output_types.append("""image""" ) elif isinstance(lowercase , (torch.Tensor, AgentAudio) ): output_types.append("""audio""" ) else: raise ValueError(f'''Invalid output: {output}''' ) return output_types @is_tool_test class a : def lowerCamelCase__ ( self : Tuple ) -> List[Any]: '''simple docstring''' self.assertTrue(hasattr(self.tool , """inputs""" ) ) self.assertTrue(hasattr(self.tool , """outputs""" ) ) SCREAMING_SNAKE_CASE_: Optional[int] =self.tool.inputs for _input in inputs: if isinstance(_input , lowerCAmelCase ): for __input in _input: self.assertTrue(__input in authorized_types ) else: self.assertTrue(_input in authorized_types ) SCREAMING_SNAKE_CASE_: Any =self.tool.outputs for _output in outputs: self.assertTrue(_output in authorized_types ) def lowerCamelCase__ ( self : str ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =create_inputs(self.tool.inputs ) SCREAMING_SNAKE_CASE_: List[Any] =self.tool(*lowerCAmelCase ) # There is a single output if len(self.tool.outputs ) == 1: SCREAMING_SNAKE_CASE_: str =[outputs] self.assertListEqual(output_types(lowerCAmelCase ) , self.tool.outputs ) def lowerCamelCase__ ( self : str ) -> Optional[Any]: '''simple docstring''' self.assertTrue(hasattr(self.tool , """description""" ) ) self.assertTrue(hasattr(self.tool , """default_checkpoint""" ) ) self.assertTrue(self.tool.description.startswith("""This is a tool that""" ) ) def lowerCamelCase__ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: str =create_inputs(self.tool.inputs ) SCREAMING_SNAKE_CASE_: Tuple =self.tool(*lowerCAmelCase ) if not isinstance(lowerCAmelCase , lowerCAmelCase ): SCREAMING_SNAKE_CASE_: int =[outputs] self.assertEqual(len(lowerCAmelCase ) , len(self.tool.outputs ) ) for output, output_type in zip(lowerCAmelCase , self.tool.outputs ): SCREAMING_SNAKE_CASE_: int =AGENT_TYPE_MAPPING[output_type] self.assertTrue(isinstance(lowerCAmelCase , lowerCAmelCase ) ) def lowerCamelCase__ ( self : List[Any] ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =create_inputs(self.tool.inputs ) SCREAMING_SNAKE_CASE_: Union[str, Any] =[] for _input, input_type in zip(lowerCAmelCase , self.tool.inputs ): if isinstance(lowerCAmelCase , lowerCAmelCase ): _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input ) for _input_type in input_type] ) else: _inputs.append(AGENT_TYPE_MAPPING[input_type](_input ) ) # Should not raise an error SCREAMING_SNAKE_CASE_: Dict =self.tool(*lowerCAmelCase ) if not isinstance(lowerCAmelCase , lowerCAmelCase ): SCREAMING_SNAKE_CASE_: List[str] =[outputs] self.assertEqual(len(lowerCAmelCase ) , len(self.tool.outputs ) )
36
1
"""simple docstring""" import time from dataclasses import dataclass from multiprocessing import Pool from unittest import TestCase from unittest.mock import patch import multiprocess import numpy as np import pytest from datasets.utils.py_utils import ( NestedDataStructure, asdict, iflatmap_unordered, map_nested, temp_seed, temporary_assignment, zip_dict, ) from .utils import require_tf, require_torch def __magic_name__ ( lowercase ): # picklable for multiprocessing return x.sum() def __magic_name__ ( lowercase ): # picklable for multiprocessing return i + 1 @dataclass class a : UpperCamelCase : int UpperCamelCase : str class a ( UpperCAmelCase__ ): def lowerCamelCase__ ( self : int ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[int] ={} SCREAMING_SNAKE_CASE_: Optional[Any] =[] SCREAMING_SNAKE_CASE_: List[str] =1 SCREAMING_SNAKE_CASE_: List[Any] =[1, 2] SCREAMING_SNAKE_CASE_: Optional[int] ={"""a""": 1, """b""": 2} SCREAMING_SNAKE_CASE_: Tuple ={"""a""": [1, 2], """b""": [3, 4]} SCREAMING_SNAKE_CASE_: Optional[Any] ={"""a""": {"""1""": 1}, """b""": 2} SCREAMING_SNAKE_CASE_: List[str] ={"""a""": 1, """b""": 2, """c""": 3, """d""": 4} SCREAMING_SNAKE_CASE_: List[str] ={} SCREAMING_SNAKE_CASE_: Dict =[] SCREAMING_SNAKE_CASE_: Dict =2 SCREAMING_SNAKE_CASE_: Any =[2, 3] SCREAMING_SNAKE_CASE_: Dict ={"""a""": 2, """b""": 3} SCREAMING_SNAKE_CASE_: Any ={"""a""": [2, 3], """b""": [4, 5]} SCREAMING_SNAKE_CASE_: str ={"""a""": {"""1""": 2}, """b""": 3} SCREAMING_SNAKE_CASE_: str ={"""a""": 2, """b""": 3, """c""": 4, """d""": 5} self.assertEqual(map_nested(lowerCAmelCase , lowerCAmelCase ) , lowerCAmelCase ) self.assertEqual(map_nested(lowerCAmelCase , lowerCAmelCase ) , lowerCAmelCase ) self.assertEqual(map_nested(lowerCAmelCase , lowerCAmelCase ) , lowerCAmelCase ) self.assertEqual(map_nested(lowerCAmelCase , lowerCAmelCase ) , lowerCAmelCase ) self.assertEqual(map_nested(lowerCAmelCase , lowerCAmelCase ) , lowerCAmelCase ) self.assertEqual(map_nested(lowerCAmelCase , lowerCAmelCase ) , lowerCAmelCase ) self.assertEqual(map_nested(lowerCAmelCase , lowerCAmelCase ) , lowerCAmelCase ) self.assertEqual(map_nested(lowerCAmelCase , lowerCAmelCase ) , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple =2 self.assertEqual(map_nested(lowerCAmelCase , lowerCAmelCase , num_proc=lowerCAmelCase ) , lowerCAmelCase ) self.assertEqual(map_nested(lowerCAmelCase , lowerCAmelCase , num_proc=lowerCAmelCase ) , lowerCAmelCase ) self.assertEqual(map_nested(lowerCAmelCase , lowerCAmelCase , num_proc=lowerCAmelCase ) , lowerCAmelCase ) self.assertEqual(map_nested(lowerCAmelCase , lowerCAmelCase , num_proc=lowerCAmelCase ) , lowerCAmelCase ) self.assertEqual(map_nested(lowerCAmelCase , lowerCAmelCase , num_proc=lowerCAmelCase ) , lowerCAmelCase ) self.assertEqual(map_nested(lowerCAmelCase , lowerCAmelCase , num_proc=lowerCAmelCase ) , lowerCAmelCase ) self.assertEqual(map_nested(lowerCAmelCase , lowerCAmelCase , num_proc=lowerCAmelCase ) , lowerCAmelCase ) self.assertEqual(map_nested(lowerCAmelCase , lowerCAmelCase , num_proc=lowerCAmelCase ) , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple ={"""a""": np.eye(2 ), """b""": np.zeros(3 ), """c""": np.ones(2 )} SCREAMING_SNAKE_CASE_: Tuple ={"""a""": 2, """b""": 0, """c""": 2} SCREAMING_SNAKE_CASE_: str ={ """a""": np.eye(2 ).astype(lowerCAmelCase ), """b""": np.zeros(3 ).astype(lowerCAmelCase ), """c""": np.ones(2 ).astype(lowerCAmelCase ), } self.assertEqual(map_nested(lowerCAmelCase , lowerCAmelCase , map_numpy=lowerCAmelCase ) , lowerCAmelCase ) self.assertEqual( {k: v.tolist() for k, v in map_nested(lowerCAmelCase , lowerCAmelCase , map_numpy=lowerCAmelCase ).items()} , {k: v.tolist() for k, v in expected_map_nested_sna_int.items()} , ) self.assertEqual(map_nested(lowerCAmelCase , lowerCAmelCase , map_numpy=lowerCAmelCase , num_proc=lowerCAmelCase ) , lowerCAmelCase ) self.assertEqual( {k: v.tolist() for k, v in map_nested(lowerCAmelCase , lowerCAmelCase , map_numpy=lowerCAmelCase , num_proc=lowerCAmelCase ).items()} , {k: v.tolist() for k, v in expected_map_nested_sna_int.items()} , ) with self.assertRaises(lowerCAmelCase ): # can't pickle a local lambda map_nested(lambda lowerCAmelCase : x + 1 , lowerCAmelCase , num_proc=lowerCAmelCase ) def lowerCamelCase__ ( self : List[Any] ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Union[str, Any] ={"""a""": 1, """b""": 2} SCREAMING_SNAKE_CASE_: int ={"""a""": 3, """b""": 4} SCREAMING_SNAKE_CASE_: Any ={"""a""": 5, """b""": 6} SCREAMING_SNAKE_CASE_: Optional[Any] =sorted([("""a""", (1, 3, 5)), ("""b""", (2, 4, 6))] ) self.assertEqual(sorted(zip_dict(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) ) , lowerCAmelCase ) def lowerCamelCase__ ( self : List[Any] ) -> Tuple: '''simple docstring''' class a : UpperCamelCase : int = 'bar' SCREAMING_SNAKE_CASE_: Union[str, Any] =Foo() self.assertEqual(foo.my_attr , """bar""" ) with temporary_assignment(lowerCAmelCase , """my_attr""" , """BAR""" ): self.assertEqual(foo.my_attr , """BAR""" ) self.assertEqual(foo.my_attr , """bar""" ) @pytest.mark.parametrize( """iterable_length, num_proc, expected_num_proc""" , [ (1, None, 1), (1, 1, 1), (2, None, 1), (2, 1, 1), (2, 2, 1), (2, 3, 1), (3, 2, 1), (16, 16, 16), (16, 17, 16), (17, 16, 16), ] , ) def __magic_name__ ( lowercase , lowercase , lowercase ): with patch("""datasets.utils.py_utils._single_map_nested""" ) as mock_single_map_nested, patch( """datasets.parallel.parallel.Pool""" ) as mock_multiprocessing_pool: SCREAMING_SNAKE_CASE_: Dict ={f'''{i}''': i for i in range(lowercase )} SCREAMING_SNAKE_CASE_: List[str] =map_nested(lambda lowercase : x + 10 , lowercase , num_proc=lowercase , parallel_min_length=16 ) if expected_num_proc == 1: assert mock_single_map_nested.called assert not mock_multiprocessing_pool.called else: assert not mock_single_map_nested.called assert mock_multiprocessing_pool.called assert mock_multiprocessing_pool.call_args[0][0] == expected_num_proc class a ( UpperCAmelCase__ ): @require_tf def lowerCamelCase__ ( self : Tuple ) -> int: '''simple docstring''' import tensorflow as tf from tensorflow.keras import layers SCREAMING_SNAKE_CASE_: Dict =layers.Dense(2 ) def gen_random_output(): SCREAMING_SNAKE_CASE_: int =tf.random.uniform((1, 3) ) return model(lowerCAmelCase ).numpy() with temp_seed(42 , set_tensorflow=lowerCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[Any] =gen_random_output() with temp_seed(42 , set_tensorflow=lowerCAmelCase ): SCREAMING_SNAKE_CASE_: Any =gen_random_output() SCREAMING_SNAKE_CASE_: str =gen_random_output() np.testing.assert_equal(lowerCAmelCase , lowerCAmelCase ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) @require_torch def lowerCamelCase__ ( self : Optional[Any] ) -> int: '''simple docstring''' import torch def gen_random_output(): SCREAMING_SNAKE_CASE_: int =torch.nn.Linear(3 , 2 ) SCREAMING_SNAKE_CASE_: Optional[Any] =torch.rand(1 , 3 ) return model(lowerCAmelCase ).detach().numpy() with temp_seed(42 , set_pytorch=lowerCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[Any] =gen_random_output() with temp_seed(42 , set_pytorch=lowerCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[int] =gen_random_output() SCREAMING_SNAKE_CASE_: str =gen_random_output() np.testing.assert_equal(lowerCAmelCase , lowerCAmelCase ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) def lowerCamelCase__ ( self : Tuple ) -> str: '''simple docstring''' def gen_random_output(): return np.random.rand(1 , 3 ) with temp_seed(42 ): SCREAMING_SNAKE_CASE_: Union[str, Any] =gen_random_output() with temp_seed(42 ): SCREAMING_SNAKE_CASE_: Dict =gen_random_output() SCREAMING_SNAKE_CASE_: Optional[Any] =gen_random_output() np.testing.assert_equal(lowerCAmelCase , lowerCAmelCase ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) @pytest.mark.parametrize("""input_data""" , [{}] ) def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: List[Any] =NestedDataStructure(lowercase ).data assert output_data == input_data @pytest.mark.parametrize( """data, expected_output""" , [ ({}, []), ([], []), ("""foo""", ["""foo"""]), (["""foo""", """bar"""], ["""foo""", """bar"""]), ([["""foo""", """bar"""]], ["""foo""", """bar"""]), ([[["""foo"""], ["""bar"""]]], ["""foo""", """bar"""]), ([[["""foo"""], """bar"""]], ["""foo""", """bar"""]), ({"""a""": 1, """b""": 2}, [1, 2]), ({"""a""": [1, 2], """b""": [3, 4]}, [1, 2, 3, 4]), ({"""a""": [[1, 2]], """b""": [[3, 4]]}, [1, 2, 3, 4]), ({"""a""": [[1, 2]], """b""": [3, 4]}, [1, 2, 3, 4]), ({"""a""": [[[1], [2]]], """b""": [[[3], [4]]]}, [1, 2, 3, 4]), ({"""a""": [[[1], [2]]], """b""": [[3, 4]]}, [1, 2, 3, 4]), ({"""a""": [[[1], [2]]], """b""": [3, 4]}, [1, 2, 3, 4]), ({"""a""": [[[1], [2]]], """b""": [3, [4]]}, [1, 2, 3, 4]), ({"""a""": {"""1""": 1}, """b""": 2}, [1, 2]), ({"""a""": {"""1""": [1]}, """b""": 2}, [1, 2]), ({"""a""": {"""1""": [1]}, """b""": [2]}, [1, 2]), ] , ) def __magic_name__ ( lowercase , lowercase ): SCREAMING_SNAKE_CASE_: Tuple =NestedDataStructure(lowercase ).flatten() assert output == expected_output def __magic_name__ ( ): SCREAMING_SNAKE_CASE_: int =A(x=1 , y="""foobar""" ) SCREAMING_SNAKE_CASE_: List[str] ={"""x""": 1, """y""": """foobar"""} assert asdict(lowercase ) == expected_output SCREAMING_SNAKE_CASE_: Optional[Any] ={"""a""": {"""b""": A(x=10 , y="""foo""" )}, """c""": [A(x=20 , y="""bar""" )]} SCREAMING_SNAKE_CASE_: List[str] ={"""a""": {"""b""": {"""x""": 10, """y""": """foo"""}}, """c""": [{"""x""": 20, """y""": """bar"""}]} assert asdict(lowercase ) == expected_output with pytest.raises(lowercase ): asdict([1, A(x=10 , y="""foo""" )] ) def __magic_name__ ( lowercase ): return text.split() def __magic_name__ ( lowercase ): yield (time.time(), content) time.sleep(2 ) yield (time.time(), content) def __magic_name__ ( ): with Pool(2 ) as pool: SCREAMING_SNAKE_CASE_: Any =list(iflatmap_unordered(lowercase , _split_text , kwargs_iterable=[{"""text""": """hello there"""}] * 10 ) ) assert out.count("""hello""" ) == 10 assert out.count("""there""" ) == 10 assert len(lowercase ) == 20 # check multiprocess from pathos (uses dill for pickling) with multiprocess.Pool(2 ) as pool: SCREAMING_SNAKE_CASE_: Union[str, Any] =list(iflatmap_unordered(lowercase , _split_text , kwargs_iterable=[{"""text""": """hello there"""}] * 10 ) ) assert out.count("""hello""" ) == 10 assert out.count("""there""" ) == 10 assert len(lowercase ) == 20 # check that we get items as fast as possible with Pool(2 ) as pool: SCREAMING_SNAKE_CASE_: Optional[int] =[] for yield_time, content in iflatmap_unordered( lowercase , _aseconds_generator_of_aitems_with_timing , kwargs_iterable=[{"""content""": """a"""}, {"""content""": """b"""}] ): assert yield_time < time.time() + 0.1, "we should each item directly after it was yielded" out.append(lowercase ) assert out.count("""a""" ) == 2 assert out.count("""b""" ) == 2 assert len(lowercase ) == 4
36
"""simple docstring""" from __future__ import annotations def __magic_name__ ( lowercase , lowercase ): SCREAMING_SNAKE_CASE_: List[Any] =sorted(numsa + numsa ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Tuple =divmod(len(lowercase ) , 2 ) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() _UpperCAmelCase = [float(x) for x in input("""Enter the elements of first array: """).split()] _UpperCAmelCase = [float(x) for x in input("""Enter the elements of second array: """).split()] print(f"""The median of two arrays is: {median_of_two_arrays(array_a, array_a)}""")
36
1
"""simple docstring""" import time import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers.generation import ( MaxLengthCriteria, MaxNewTokensCriteria, MaxTimeCriteria, StoppingCriteriaList, validate_stopping_criteria, ) @require_torch class a ( unittest.TestCase ): def lowerCamelCase__ ( self : List[Any] , lowerCAmelCase : Dict ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[Any] =3 SCREAMING_SNAKE_CASE_: List[str] =250 SCREAMING_SNAKE_CASE_: Any =ids_tensor((batch_size, length) , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple =torch.ones((batch_size, length) , device=lowerCAmelCase , dtype=torch.float ) / length return input_ids, scores def lowerCamelCase__ ( self : List[str] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: int =self._get_tensors(5 ) SCREAMING_SNAKE_CASE_: int =StoppingCriteriaList( [ MaxLengthCriteria(max_length=10 ), MaxTimeCriteria(max_time=0.1 ), ] ) self.assertFalse(criteria(lowerCAmelCase , lowerCAmelCase ) ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Dict =self._get_tensors(9 ) self.assertFalse(criteria(lowerCAmelCase , lowerCAmelCase ) ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: int =self._get_tensors(10 ) self.assertTrue(criteria(lowerCAmelCase , lowerCAmelCase ) ) def lowerCamelCase__ ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: int =MaxLengthCriteria(max_length=10 ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Dict =self._get_tensors(5 ) self.assertFalse(criteria(lowerCAmelCase , lowerCAmelCase ) ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Tuple =self._get_tensors(9 ) self.assertFalse(criteria(lowerCAmelCase , lowerCAmelCase ) ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: int =self._get_tensors(10 ) self.assertTrue(criteria(lowerCAmelCase , lowerCAmelCase ) ) def lowerCamelCase__ ( self : int ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[int] =MaxNewTokensCriteria(start_length=5 , max_new_tokens=5 ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Union[str, Any] =self._get_tensors(5 ) self.assertFalse(criteria(lowerCAmelCase , lowerCAmelCase ) ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Any =self._get_tensors(9 ) self.assertFalse(criteria(lowerCAmelCase , lowerCAmelCase ) ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: str =self._get_tensors(10 ) self.assertTrue(criteria(lowerCAmelCase , lowerCAmelCase ) ) SCREAMING_SNAKE_CASE_: List[str] =StoppingCriteriaList([criteria] ) self.assertEqual(criteria_list.max_length , 10 ) def lowerCamelCase__ ( self : str ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[Any] =self._get_tensors(5 ) SCREAMING_SNAKE_CASE_: Union[str, Any] =MaxTimeCriteria(max_time=0.1 ) self.assertFalse(criteria(lowerCAmelCase , lowerCAmelCase ) ) SCREAMING_SNAKE_CASE_: Optional[int] =MaxTimeCriteria(max_time=0.1 , initial_timestamp=time.time() - 0.2 ) self.assertTrue(criteria(lowerCAmelCase , lowerCAmelCase ) ) def lowerCamelCase__ ( self : str ) -> Dict: '''simple docstring''' validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10 )] ) , 10 ) with self.assertWarns(lowerCAmelCase ): validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10 )] ) , 11 ) SCREAMING_SNAKE_CASE_: Optional[int] =validate_stopping_criteria(StoppingCriteriaList() , 11 ) self.assertEqual(len(lowerCAmelCase ) , 1 )
36
"""simple docstring""" import copy import inspect import unittest from transformers import PretrainedConfig, SwiftFormerConfig from transformers.testing_utils import ( require_torch, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwiftFormerForImageClassification, SwiftFormerModel from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class a : def __init__( self : Any , lowerCAmelCase : Any , lowerCAmelCase : List[str]=13 , lowerCAmelCase : Dict=3 , lowerCAmelCase : Optional[Any]=True , lowerCAmelCase : Dict=True , lowerCAmelCase : Dict=0.1 , lowerCAmelCase : str=0.1 , lowerCAmelCase : List[str]=224 , lowerCAmelCase : List[str]=1000 , lowerCAmelCase : Optional[Any]=[3, 3, 6, 4] , lowerCAmelCase : int=[48, 56, 112, 220] , ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[int] =parent SCREAMING_SNAKE_CASE_: Any =batch_size SCREAMING_SNAKE_CASE_: Tuple =num_channels SCREAMING_SNAKE_CASE_: Union[str, Any] =is_training SCREAMING_SNAKE_CASE_: Tuple =use_labels SCREAMING_SNAKE_CASE_: Optional[int] =hidden_dropout_prob SCREAMING_SNAKE_CASE_: Tuple =attention_probs_dropout_prob SCREAMING_SNAKE_CASE_: List[Any] =num_labels SCREAMING_SNAKE_CASE_: int =image_size SCREAMING_SNAKE_CASE_: Optional[Any] =layer_depths SCREAMING_SNAKE_CASE_: List[Any] =embed_dims def lowerCamelCase__ ( self : List[Any] ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[str] =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_: List[Any] =None if self.use_labels: SCREAMING_SNAKE_CASE_: List[str] =ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE_: Tuple =self.get_config() return config, pixel_values, labels def lowerCamelCase__ ( self : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' return SwiftFormerConfig( depths=self.layer_depths , embed_dims=self.embed_dims , mlp_ratio=4 , downsamples=[True, True, True, True] , hidden_act="""gelu""" , num_labels=self.num_labels , down_patch_size=3 , down_stride=2 , down_pad=1 , drop_rate=0.0 , drop_path_rate=0.0 , use_layer_scale=lowerCAmelCase , layer_scale_init_value=1E-5 , ) def lowerCamelCase__ ( self : Any , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Optional[Any] , lowerCAmelCase : Optional[int] ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[str] =SwiftFormerModel(config=lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() SCREAMING_SNAKE_CASE_: Any =model(lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dims[-1], 7, 7) ) def lowerCamelCase__ ( self : Union[str, Any] , lowerCAmelCase : List[Any] , lowerCAmelCase : Optional[int] , lowerCAmelCase : Union[str, Any] ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[Any] =self.num_labels SCREAMING_SNAKE_CASE_: Dict =SwiftFormerForImageClassification(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() SCREAMING_SNAKE_CASE_: Dict =model(lowerCAmelCase , labels=lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) SCREAMING_SNAKE_CASE_: int =SwiftFormerForImageClassification(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() SCREAMING_SNAKE_CASE_: Tuple =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_: Dict =model(lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase__ ( self : int ) -> Optional[Any]: '''simple docstring''' ((SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_)): str =self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_: Tuple ={"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class a ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): UpperCamelCase : Optional[int] = (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else () UpperCamelCase : Tuple = ( {'feature-extraction': SwiftFormerModel, 'image-classification': SwiftFormerForImageClassification} if is_torch_available() else {} ) UpperCamelCase : Any = False UpperCamelCase : Optional[int] = False UpperCamelCase : Optional[Any] = False UpperCamelCase : Dict = False UpperCamelCase : List[str] = False def lowerCamelCase__ ( self : Dict ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =SwiftFormerModelTester(self ) SCREAMING_SNAKE_CASE_: Union[str, Any] =ConfigTester( self , config_class=lowerCAmelCase , has_text_modality=lowerCAmelCase , hidden_size=37 , num_attention_heads=12 , num_hidden_layers=12 , ) def lowerCamelCase__ ( self : Tuple ) -> int: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="""SwiftFormer does not use inputs_embeds""" ) def lowerCamelCase__ ( self : Tuple ) -> List[str]: '''simple docstring''' pass def lowerCamelCase__ ( self : Optional[int] ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[str] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_: Any =model_class(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[Any] =model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCAmelCase , nn.Linear ) ) def lowerCamelCase__ ( self : str ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[Any] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_: int =model_class(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[Any] =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE_: Any =[*signature.parameters.keys()] SCREAMING_SNAKE_CASE_: Tuple =["""pixel_values"""] self.assertListEqual(arg_names[:1] , lowerCAmelCase ) def lowerCamelCase__ ( self : int ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase ) def lowerCamelCase__ ( self : Any ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: int =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase ) @slow def lowerCamelCase__ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_: Optional[Any] =SwiftFormerModel.from_pretrained(lowerCAmelCase ) self.assertIsNotNone(lowerCAmelCase ) @unittest.skip(reason="""SwiftFormer does not output attentions""" ) def lowerCamelCase__ ( self : Optional[int] ) -> str: '''simple docstring''' pass def lowerCamelCase__ ( self : List[Any] ) -> List[str]: '''simple docstring''' def check_hidden_states_output(lowerCAmelCase : Optional[int] , lowerCAmelCase : str , lowerCAmelCase : Optional[int] ): SCREAMING_SNAKE_CASE_: Optional[Any] =model_class(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_: List[str] =model(**self._prepare_for_class(lowerCAmelCase , lowerCAmelCase ) ) SCREAMING_SNAKE_CASE_: Dict =outputs.hidden_states SCREAMING_SNAKE_CASE_: List[Any] =8 self.assertEqual(len(lowerCAmelCase ) , lowerCAmelCase ) # TODO # SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width) # with the width and height being successively divided by 2, after every 2 blocks for i in range(len(lowerCAmelCase ) ): self.assertEqual( hidden_states[i].shape , torch.Size( [ self.model_tester.batch_size, self.model_tester.embed_dims[i // 2], (self.model_tester.image_size // 4) // 2 ** (i // 2), (self.model_tester.image_size // 4) // 2 ** (i // 2), ] ) , ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: int =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_: Dict =True check_hidden_states_output(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE_: Any =True check_hidden_states_output(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) def lowerCamelCase__ ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' def _config_zero_init(lowerCAmelCase : str ): SCREAMING_SNAKE_CASE_: Dict =copy.deepcopy(lowerCAmelCase ) for key in configs_no_init.__dict__.keys(): if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key: setattr(lowerCAmelCase , lowerCAmelCase , 1E-10 ) if isinstance(getattr(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) , lowerCAmelCase ): SCREAMING_SNAKE_CASE_: Tuple =_config_zero_init(getattr(lowerCAmelCase , lowerCAmelCase ) ) setattr(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) return configs_no_init SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[Any] =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_: List[Any] =_config_zero_init(lowerCAmelCase ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_: Any =model_class(config=lowerCAmelCase ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1E9) / 1E9).round().item() , [0.0, 1.0] , msg=f'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def lowerCamelCase__ ( self : List[str] ) -> List[str]: '''simple docstring''' pass def __magic_name__ ( ): SCREAMING_SNAKE_CASE_: List[Any] =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class a ( unittest.TestCase ): @cached_property def lowerCamelCase__ ( self : str ) -> str: '''simple docstring''' return ViTImageProcessor.from_pretrained("""MBZUAI/swiftformer-xs""" ) if is_vision_available() else None @slow def lowerCamelCase__ ( self : Union[str, Any] ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: str =SwiftFormerForImageClassification.from_pretrained("""MBZUAI/swiftformer-xs""" ).to(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: str =self.default_image_processor SCREAMING_SNAKE_CASE_: int =prepare_img() SCREAMING_SNAKE_CASE_: Union[str, Any] =image_processor(images=lowerCAmelCase , return_tensors="""pt""" ).to(lowerCAmelCase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_: Dict =model(**lowerCAmelCase ) # verify the logits SCREAMING_SNAKE_CASE_: Optional[Any] =torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =torch.tensor([[-2.1_703E00, 2.1_107E00, -2.0_811E00]] ).to(lowerCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCAmelCase , atol=1E-4 ) )
36
1
"""simple docstring""" def __magic_name__ ( lowercase ): if upper_limit < 0: raise ValueError("""Limit for the Catalan sequence must be ≥ 0""" ) SCREAMING_SNAKE_CASE_: Tuple =[0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 SCREAMING_SNAKE_CASE_: Any =1 if upper_limit > 0: SCREAMING_SNAKE_CASE_: List[str] =1 # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i for i in range(2 , upper_limit + 1 ): for j in range(lowercase ): catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1] return catalan_list if __name__ == "__main__": print("""\n********* Catalan Numbers Using Dynamic Programming ************\n""") print("""\n*** Enter -1 at any time to quit ***""") print("""\nEnter the upper limit (≥ 0) for the Catalan number sequence: """, end="""""") try: while True: _UpperCAmelCase = int(input().strip()) if N < 0: print("""\n********* Goodbye!! ************""") break else: print(f"""The Catalan numbers from 0 through {N} are:""") print(catalan_numbers(N)) print("""Try another upper limit for the sequence: """, end="""""") except (NameError, ValueError): print("""\n********* Invalid input, goodbye! ************\n""") import doctest doctest.testmod()
36
"""simple docstring""" from math import pi def __magic_name__ ( lowercase , lowercase ): return 2 * pi * radius * (angle / 360) if __name__ == "__main__": print(arc_length(9_0, 1_0))
36
1
"""simple docstring""" from typing import Any, Dict, Optional import torch import torch.nn.functional as F from torch import nn from ..utils import maybe_allow_in_graph from .activations import get_activation from .attention_processor import Attention from .embeddings import CombinedTimestepLabelEmbeddings @maybe_allow_in_graph class a ( nn.Module ): def __init__( self : int , lowerCAmelCase : int , lowerCAmelCase : int , lowerCAmelCase : int , lowerCAmelCase : List[str]=0.0 , lowerCAmelCase : Optional[int] = None , lowerCAmelCase : str = "geglu" , lowerCAmelCase : Optional[int] = None , lowerCAmelCase : bool = False , lowerCAmelCase : bool = False , lowerCAmelCase : bool = False , lowerCAmelCase : bool = False , lowerCAmelCase : bool = True , lowerCAmelCase : str = "layer_norm" , lowerCAmelCase : bool = False , ) -> Any: '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE_: Union[str, Any] =only_cross_attention SCREAMING_SNAKE_CASE_: str =(num_embeds_ada_norm is not None) and norm_type == """ada_norm_zero""" SCREAMING_SNAKE_CASE_: List[Any] =(num_embeds_ada_norm is not None) and norm_type == """ada_norm""" if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None: raise ValueError( f'''`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to''' f''' define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}.''' ) # Define 3 blocks. Each block has its own normalization layer. # 1. Self-Attn if self.use_ada_layer_norm: SCREAMING_SNAKE_CASE_: Optional[int] =AdaLayerNorm(lowerCAmelCase , lowerCAmelCase ) elif self.use_ada_layer_norm_zero: SCREAMING_SNAKE_CASE_: Tuple =AdaLayerNormZero(lowerCAmelCase , lowerCAmelCase ) else: SCREAMING_SNAKE_CASE_: str =nn.LayerNorm(lowerCAmelCase , elementwise_affine=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: str =Attention( query_dim=lowerCAmelCase , heads=lowerCAmelCase , dim_head=lowerCAmelCase , dropout=lowerCAmelCase , bias=lowerCAmelCase , cross_attention_dim=cross_attention_dim if only_cross_attention else None , upcast_attention=lowerCAmelCase , ) # 2. Cross-Attn if cross_attention_dim is not None or double_self_attention: # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during # the second cross attention block. SCREAMING_SNAKE_CASE_: int =( AdaLayerNorm(lowerCAmelCase , lowerCAmelCase ) if self.use_ada_layer_norm else nn.LayerNorm(lowerCAmelCase , elementwise_affine=lowerCAmelCase ) ) SCREAMING_SNAKE_CASE_: str =Attention( query_dim=lowerCAmelCase , cross_attention_dim=cross_attention_dim if not double_self_attention else None , heads=lowerCAmelCase , dim_head=lowerCAmelCase , dropout=lowerCAmelCase , bias=lowerCAmelCase , upcast_attention=lowerCAmelCase , ) # is self-attn if encoder_hidden_states is none else: SCREAMING_SNAKE_CASE_: Optional[int] =None SCREAMING_SNAKE_CASE_: Optional[Any] =None # 3. Feed-forward SCREAMING_SNAKE_CASE_: List[str] =nn.LayerNorm(lowerCAmelCase , elementwise_affine=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =FeedForward(lowerCAmelCase , dropout=lowerCAmelCase , activation_fn=lowerCAmelCase , final_dropout=lowerCAmelCase ) # let chunk size default to None SCREAMING_SNAKE_CASE_: str =None SCREAMING_SNAKE_CASE_: List[Any] =0 def lowerCamelCase__ ( self : Tuple , lowerCAmelCase : Optional[int] , lowerCAmelCase : int ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =chunk_size SCREAMING_SNAKE_CASE_: Optional[Any] =dim def lowerCamelCase__ ( self : Tuple , lowerCAmelCase : torch.FloatTensor , lowerCAmelCase : Optional[torch.FloatTensor] = None , lowerCAmelCase : Optional[torch.FloatTensor] = None , lowerCAmelCase : Optional[torch.FloatTensor] = None , lowerCAmelCase : Optional[torch.LongTensor] = None , lowerCAmelCase : Dict[str, Any] = None , lowerCAmelCase : Optional[torch.LongTensor] = None , ) -> List[Any]: '''simple docstring''' if self.use_ada_layer_norm: SCREAMING_SNAKE_CASE_: Optional[int] =self.norma(lowerCAmelCase , lowerCAmelCase ) elif self.use_ada_layer_norm_zero: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: str =self.norma( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , hidden_dtype=hidden_states.dtype ) else: SCREAMING_SNAKE_CASE_: Tuple =self.norma(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Any =cross_attention_kwargs if cross_attention_kwargs is not None else {} SCREAMING_SNAKE_CASE_: List[str] =self.attna( lowerCAmelCase , encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None , attention_mask=lowerCAmelCase , **lowerCAmelCase , ) if self.use_ada_layer_norm_zero: SCREAMING_SNAKE_CASE_: str =gate_msa.unsqueeze(1 ) * attn_output SCREAMING_SNAKE_CASE_: str =attn_output + hidden_states # 2. Cross-Attention if self.attna is not None: SCREAMING_SNAKE_CASE_: Any =( self.norma(lowerCAmelCase , lowerCAmelCase ) if self.use_ada_layer_norm else self.norma(lowerCAmelCase ) ) SCREAMING_SNAKE_CASE_: List[str] =self.attna( lowerCAmelCase , encoder_hidden_states=lowerCAmelCase , attention_mask=lowerCAmelCase , **lowerCAmelCase , ) SCREAMING_SNAKE_CASE_: Any =attn_output + hidden_states # 3. Feed-forward SCREAMING_SNAKE_CASE_: str =self.norma(lowerCAmelCase ) if self.use_ada_layer_norm_zero: SCREAMING_SNAKE_CASE_: Optional[int] =norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None] if self._chunk_size is not None: # "feed_forward_chunk_size" can be used to save memory if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0: raise ValueError( f'''`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`.''' ) SCREAMING_SNAKE_CASE_: str =norm_hidden_states.shape[self._chunk_dim] // self._chunk_size SCREAMING_SNAKE_CASE_: int =torch.cat( [self.ff(lowerCAmelCase ) for hid_slice in norm_hidden_states.chunk(lowerCAmelCase , dim=self._chunk_dim )] , dim=self._chunk_dim , ) else: SCREAMING_SNAKE_CASE_: int =self.ff(lowerCAmelCase ) if self.use_ada_layer_norm_zero: SCREAMING_SNAKE_CASE_: List[Any] =gate_mlp.unsqueeze(1 ) * ff_output SCREAMING_SNAKE_CASE_: Optional[Any] =ff_output + hidden_states return hidden_states class a ( nn.Module ): def __init__( self : Dict , lowerCAmelCase : int , lowerCAmelCase : Optional[int] = None , lowerCAmelCase : int = 4 , lowerCAmelCase : float = 0.0 , lowerCAmelCase : str = "geglu" , lowerCAmelCase : bool = False , ) -> Optional[int]: '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE_: Optional[Any] =int(dim * mult ) SCREAMING_SNAKE_CASE_: Optional[int] =dim_out if dim_out is not None else dim if activation_fn == "gelu": SCREAMING_SNAKE_CASE_: Union[str, Any] =GELU(lowerCAmelCase , lowerCAmelCase ) if activation_fn == "gelu-approximate": SCREAMING_SNAKE_CASE_: int =GELU(lowerCAmelCase , lowerCAmelCase , approximate="""tanh""" ) elif activation_fn == "geglu": SCREAMING_SNAKE_CASE_: Optional[Any] =GEGLU(lowerCAmelCase , lowerCAmelCase ) elif activation_fn == "geglu-approximate": SCREAMING_SNAKE_CASE_: Optional[Any] =ApproximateGELU(lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =nn.ModuleList([] ) # project in self.net.append(lowerCAmelCase ) # project dropout self.net.append(nn.Dropout(lowerCAmelCase ) ) # project out self.net.append(nn.Linear(lowerCAmelCase , lowerCAmelCase ) ) # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout if final_dropout: self.net.append(nn.Dropout(lowerCAmelCase ) ) def lowerCamelCase__ ( self : int , lowerCAmelCase : str ) -> Dict: '''simple docstring''' for module in self.net: SCREAMING_SNAKE_CASE_: List[Any] =module(lowerCAmelCase ) return hidden_states class a ( nn.Module ): def __init__( self : Optional[int] , lowerCAmelCase : int , lowerCAmelCase : int , lowerCAmelCase : str = "none" ) -> Optional[int]: '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE_: str =nn.Linear(lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =approximate def lowerCamelCase__ ( self : str , lowerCAmelCase : Optional[Any] ) -> Optional[int]: '''simple docstring''' if gate.device.type != "mps": return F.gelu(lowerCAmelCase , approximate=self.approximate ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) , approximate=self.approximate ).to(dtype=gate.dtype ) def lowerCamelCase__ ( self : Optional[Any] , lowerCAmelCase : Dict ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =self.proj(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[Any] =self.gelu(lowerCAmelCase ) return hidden_states class a ( nn.Module ): def __init__( self : List[str] , lowerCAmelCase : int , lowerCAmelCase : int ) -> Union[str, Any]: '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE_: Any =nn.Linear(lowerCAmelCase , dim_out * 2 ) def lowerCamelCase__ ( self : str , lowerCAmelCase : List[str] ) -> Union[str, Any]: '''simple docstring''' if gate.device.type != "mps": return F.gelu(lowerCAmelCase ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) ).to(dtype=gate.dtype ) def lowerCamelCase__ ( self : List[str] , lowerCAmelCase : Tuple ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Tuple =self.proj(lowerCAmelCase ).chunk(2 , dim=-1 ) return hidden_states * self.gelu(lowerCAmelCase ) class a ( nn.Module ): def __init__( self : Tuple , lowerCAmelCase : int , lowerCAmelCase : int ) -> List[str]: '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE_: List[str] =nn.Linear(lowerCAmelCase , lowerCAmelCase ) def lowerCamelCase__ ( self : Optional[int] , lowerCAmelCase : List[Any] ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: Union[str, Any] =self.proj(lowerCAmelCase ) return x * torch.sigmoid(1.7_0_2 * x ) class a ( nn.Module ): def __init__( self : int , lowerCAmelCase : List[str] , lowerCAmelCase : List[str] ) -> Optional[Any]: '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE_: Any =nn.Embedding(lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[Any] =nn.SiLU() SCREAMING_SNAKE_CASE_: int =nn.Linear(lowerCAmelCase , embedding_dim * 2 ) SCREAMING_SNAKE_CASE_: Optional[int] =nn.LayerNorm(lowerCAmelCase , elementwise_affine=lowerCAmelCase ) def lowerCamelCase__ ( self : Tuple , lowerCAmelCase : str , lowerCAmelCase : Any ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[Any] =self.linear(self.silu(self.emb(lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Dict =torch.chunk(lowerCAmelCase , 2 ) SCREAMING_SNAKE_CASE_: Any =self.norm(lowerCAmelCase ) * (1 + scale) + shift return x class a ( nn.Module ): def __init__( self : List[str] , lowerCAmelCase : List[str] , lowerCAmelCase : Any ) -> Union[str, Any]: '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE_: str =CombinedTimestepLabelEmbeddings(lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[Any] =nn.SiLU() SCREAMING_SNAKE_CASE_: Optional[Any] =nn.Linear(lowerCAmelCase , 6 * embedding_dim , bias=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple =nn.LayerNorm(lowerCAmelCase , elementwise_affine=lowerCAmelCase , eps=1E-6 ) def lowerCamelCase__ ( self : Tuple , lowerCAmelCase : Optional[Any] , lowerCAmelCase : str , lowerCAmelCase : Tuple , lowerCAmelCase : List[str]=None ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[str] =self.linear(self.silu(self.emb(lowerCAmelCase , lowerCAmelCase , hidden_dtype=lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[int] =emb.chunk(6 , dim=1 ) SCREAMING_SNAKE_CASE_: int =self.norm(lowerCAmelCase ) * (1 + scale_msa[:, None]) + shift_msa[:, None] return x, gate_msa, shift_mlp, scale_mlp, gate_mlp class a ( nn.Module ): def __init__( self : int , lowerCAmelCase : int , lowerCAmelCase : int , lowerCAmelCase : int , lowerCAmelCase : Optional[str] = None , lowerCAmelCase : float = 1E-5 ) -> str: '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE_: List[Any] =num_groups SCREAMING_SNAKE_CASE_: Any =eps if act_fn is None: SCREAMING_SNAKE_CASE_: List[Any] =None else: SCREAMING_SNAKE_CASE_: Optional[Any] =get_activation(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =nn.Linear(lowerCAmelCase , out_dim * 2 ) def lowerCamelCase__ ( self : Optional[int] , lowerCAmelCase : int , lowerCAmelCase : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' if self.act: SCREAMING_SNAKE_CASE_: Dict =self.act(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: int =self.linear(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple =emb[:, :, None, None] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: int =emb.chunk(2 , dim=1 ) SCREAMING_SNAKE_CASE_: Optional[Any] =F.group_norm(lowerCAmelCase , self.num_groups , eps=self.eps ) SCREAMING_SNAKE_CASE_: List[Any] =x * (1 + scale) + shift return x
36
"""simple docstring""" 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 a ( unittest.TestCase ): def lowerCamelCase__ ( self : Dict ) -> str: '''simple docstring''' super().tearDown() gc.collect() def lowerCamelCase__ ( self : Optional[Any] ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Dict =FlaxStableDiffusionPipeline.from_pretrained( """stabilityai/stable-diffusion-2""" , revision="""bf16""" , dtype=jnp.bfloataa , ) SCREAMING_SNAKE_CASE_: Union[str, Any] ="""A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE_: Any =jax.device_count() SCREAMING_SNAKE_CASE_: Dict =num_samples * [prompt] SCREAMING_SNAKE_CASE_: List[Any] =sd_pipe.prepare_inputs(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Union[str, Any] =replicate(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =shard(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Dict =jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE_: Union[str, Any] =jax.random.split(lowerCAmelCase , jax.device_count() ) SCREAMING_SNAKE_CASE_: Tuple =sd_pipe(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , num_inference_steps=25 , jit=lowerCAmelCase )[0] assert images.shape == (jax.device_count(), 1, 768, 768, 3) SCREAMING_SNAKE_CASE_: Dict =images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) SCREAMING_SNAKE_CASE_: Dict =images[0, 253:256, 253:256, -1] SCREAMING_SNAKE_CASE_: Optional[int] =jnp.asarray(jax.device_get(image_slice.flatten() ) ) SCREAMING_SNAKE_CASE_: Optional[int] =jnp.array([0.4_2_3_8, 0.4_4_1_4, 0.4_3_9_5, 0.4_4_5_3, 0.4_6_2_9, 0.4_5_9_0, 0.4_5_3_1, 0.4_5_5_0_8, 0.4_5_1_2] ) print(f'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2 def lowerCamelCase__ ( self : List[str] ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE_: int ="""stabilityai/stable-diffusion-2""" SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[int] =FlaxDPMSolverMultistepScheduler.from_pretrained(lowerCAmelCase , subfolder="""scheduler""" ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[int] =FlaxStableDiffusionPipeline.from_pretrained( lowerCAmelCase , scheduler=lowerCAmelCase , revision="""bf16""" , dtype=jnp.bfloataa , ) SCREAMING_SNAKE_CASE_: Optional[int] =scheduler_params SCREAMING_SNAKE_CASE_: Tuple ="""A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE_: Union[str, Any] =jax.device_count() SCREAMING_SNAKE_CASE_: Optional[Any] =num_samples * [prompt] SCREAMING_SNAKE_CASE_: List[Any] =sd_pipe.prepare_inputs(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple =replicate(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =shard(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Any =jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE_: Any =jax.random.split(lowerCAmelCase , jax.device_count() ) SCREAMING_SNAKE_CASE_: Tuple =sd_pipe(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , num_inference_steps=25 , jit=lowerCAmelCase )[0] assert images.shape == (jax.device_count(), 1, 768, 768, 3) SCREAMING_SNAKE_CASE_: str =images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) SCREAMING_SNAKE_CASE_: Any =images[0, 253:256, 253:256, -1] SCREAMING_SNAKE_CASE_: Optional[Any] =jnp.asarray(jax.device_get(image_slice.flatten() ) ) SCREAMING_SNAKE_CASE_: Optional[int] =jnp.array([0.4_3_3_6, 0.4_2_9_6_9, 0.4_4_5_3, 0.4_1_9_9, 0.4_2_9_7, 0.4_5_3_1, 0.4_4_3_4, 0.4_4_3_4, 0.4_2_9_7] ) print(f'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2
36
1
"""simple docstring""" import baseaa def __magic_name__ ( lowercase ): return baseaa.baaencode(string.encode("""utf-8""" ) ) def __magic_name__ ( lowercase ): return baseaa.baadecode(lowercase ).decode("""utf-8""" ) if __name__ == "__main__": _UpperCAmelCase = """Hello World!""" _UpperCAmelCase = baseaa_encode(test) print(encoded) _UpperCAmelCase = baseaa_decode(encoded) print(decoded)
36
"""simple docstring""" def __magic_name__ ( lowercase = 200_0000 ): SCREAMING_SNAKE_CASE_: List[Any] =[0 for i in range(n + 1 )] SCREAMING_SNAKE_CASE_: Union[str, Any] =1 SCREAMING_SNAKE_CASE_: Optional[Any] =1 for i in range(2 , int(n**0.5 ) + 1 ): if primality_list[i] == 0: for j in range(i * i , n + 1 , lowercase ): SCREAMING_SNAKE_CASE_: Optional[int] =1 SCREAMING_SNAKE_CASE_: Dict =0 for i in range(lowercase ): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(f"""{solution() = }""")
36
1
"""simple docstring""" from typing import Dict import numpy as np import torch from . import residue_constants as rc from .tensor_utils import tensor_tree_map, tree_map def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Optional[Any] =[] SCREAMING_SNAKE_CASE_: List[str] =[] SCREAMING_SNAKE_CASE_: Any =[] for rt in rc.restypes: SCREAMING_SNAKE_CASE_: Optional[int] =rc.restype_name_to_atomaa_names[rc.restype_atoa[rt]] restype_atomaa_to_atomaa_list.append([(rc.atom_order[name] if name else 0) for name in atom_names] ) SCREAMING_SNAKE_CASE_: Any ={name: i for i, name in enumerate(lowercase )} restype_atomaa_to_atomaa_list.append( [(atom_name_to_idxaa[name] if name in atom_name_to_idxaa else 0) for name in rc.atom_types] ) restype_atomaa_mask_list.append([(1.0 if name else 0.0) for name in atom_names] ) # Add dummy mapping for restype 'UNK' restype_atomaa_to_atomaa_list.append([0] * 14 ) restype_atomaa_to_atomaa_list.append([0] * 37 ) restype_atomaa_mask_list.append([0.0] * 14 ) SCREAMING_SNAKE_CASE_: Union[str, Any] =torch.tensor( lowercase , dtype=torch.intaa , device=protein["""aatype"""].device , ) SCREAMING_SNAKE_CASE_: Optional[Any] =torch.tensor( lowercase , dtype=torch.intaa , device=protein["""aatype"""].device , ) SCREAMING_SNAKE_CASE_: List[str] =torch.tensor( lowercase , dtype=torch.floataa , device=protein["""aatype"""].device , ) SCREAMING_SNAKE_CASE_: Optional[Any] =protein["""aatype"""].to(torch.long ) # create the mapping for (residx, atom14) --> atom37, i.e. an array # with shape (num_res, 14) containing the atom37 indices for this protein SCREAMING_SNAKE_CASE_: List[str] =restype_atomaa_to_atomaa[protein_aatype] SCREAMING_SNAKE_CASE_: Any =restype_atomaa_mask[protein_aatype] SCREAMING_SNAKE_CASE_: Tuple =residx_atomaa_mask SCREAMING_SNAKE_CASE_: Dict =residx_atomaa_to_atomaa.long() # create the gather indices for mapping back SCREAMING_SNAKE_CASE_: Dict =restype_atomaa_to_atomaa[protein_aatype] SCREAMING_SNAKE_CASE_: Optional[int] =residx_atomaa_to_atomaa.long() # create the corresponding mask SCREAMING_SNAKE_CASE_: Optional[int] =torch.zeros([21, 37] , dtype=torch.floataa , device=protein["""aatype"""].device ) for restype, restype_letter in enumerate(rc.restypes ): SCREAMING_SNAKE_CASE_: int =rc.restype_atoa[restype_letter] SCREAMING_SNAKE_CASE_: Any =rc.residue_atoms[restype_name] for atom_name in atom_names: SCREAMING_SNAKE_CASE_: Optional[int] =rc.atom_order[atom_name] SCREAMING_SNAKE_CASE_: Dict =1 SCREAMING_SNAKE_CASE_: List[str] =restype_atomaa_mask[protein_aatype] SCREAMING_SNAKE_CASE_: List[Any] =residx_atomaa_mask return protein def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Any =tree_map(lambda lowercase : torch.tensor(lowercase , device=batch["""aatype"""].device ) , lowercase , np.ndarray ) SCREAMING_SNAKE_CASE_: int =tensor_tree_map(lambda lowercase : np.array(lowercase ) , make_atomaa_masks(lowercase ) ) return out
36
"""simple docstring""" import argparse import torch from transformers import BertForMaskedLM if __name__ == "__main__": _UpperCAmelCase = argparse.ArgumentParser( description=( """Extraction some layers of the full BertForMaskedLM or RObertaForMaskedLM for Transfer Learned""" """ Distillation""" ) ) parser.add_argument("""--model_type""", default="""bert""", choices=["""bert"""]) parser.add_argument("""--model_name""", default="""bert-base-uncased""", type=str) parser.add_argument("""--dump_checkpoint""", default="""serialization_dir/tf_bert-base-uncased_0247911.pth""", type=str) parser.add_argument("""--vocab_transform""", action="""store_true""") _UpperCAmelCase = parser.parse_args() if args.model_type == "bert": _UpperCAmelCase = BertForMaskedLM.from_pretrained(args.model_name) _UpperCAmelCase = """bert""" else: raise ValueError("""args.model_type should be \"bert\".""") _UpperCAmelCase = model.state_dict() _UpperCAmelCase = {} for w in ["word_embeddings", "position_embeddings"]: _UpperCAmelCase = state_dict[f"""{prefix}.embeddings.{w}.weight"""] for w in ["weight", "bias"]: _UpperCAmelCase = state_dict[f"""{prefix}.embeddings.LayerNorm.{w}"""] _UpperCAmelCase = 0 for teacher_idx in [0, 2, 4, 7, 9, 1_1]: for w in ["weight", "bias"]: _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.query.{w}""" ] _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.key.{w}""" ] _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.value.{w}""" ] _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.output.dense.{w}""" ] _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.output.LayerNorm.{w}""" ] _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.intermediate.dense.{w}""" ] _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.output.dense.{w}""" ] _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.output.LayerNorm.{w}""" ] std_idx += 1 _UpperCAmelCase = state_dict["""cls.predictions.decoder.weight"""] _UpperCAmelCase = state_dict["""cls.predictions.bias"""] if args.vocab_transform: for w in ["weight", "bias"]: _UpperCAmelCase = state_dict[f"""cls.predictions.transform.dense.{w}"""] _UpperCAmelCase = state_dict[f"""cls.predictions.transform.LayerNorm.{w}"""] print(f"""N layers selected for distillation: {std_idx}""") print(f"""Number of params transferred for distillation: {len(compressed_sd.keys())}""") print(f"""Save transferred checkpoint to {args.dump_checkpoint}.""") torch.save(compressed_sd, args.dump_checkpoint)
36
1
"""simple docstring""" def __magic_name__ ( lowercase = 1 , lowercase = 1000 ): SCREAMING_SNAKE_CASE_: List[str] =1 SCREAMING_SNAKE_CASE_: List[str] =0 for divide_by_number in range(lowercase , digit + 1 ): SCREAMING_SNAKE_CASE_: list[int] =[] SCREAMING_SNAKE_CASE_: Dict =numerator for _ in range(1 , digit + 1 ): if now_divide in has_been_divided: if longest_list_length < len(lowercase ): SCREAMING_SNAKE_CASE_: Tuple =len(lowercase ) SCREAMING_SNAKE_CASE_: List[str] =divide_by_number else: has_been_divided.append(lowercase ) SCREAMING_SNAKE_CASE_: List[Any] =now_divide * 10 % divide_by_number return the_digit # Tests if __name__ == "__main__": import doctest doctest.testmod()
36
"""simple docstring""" def __magic_name__ ( lowercase , lowercase ): return int((input_a, input_a).count(0 ) == 0 ) def __magic_name__ ( ): assert and_gate(0 , 0 ) == 0 assert and_gate(0 , 1 ) == 0 assert and_gate(1 , 0 ) == 0 assert and_gate(1 , 1 ) == 1 if __name__ == "__main__": test_and_gate() print(and_gate(1, 0)) print(and_gate(0, 0)) print(and_gate(0, 1)) print(and_gate(1, 1))
36
1
"""simple docstring""" from __future__ import annotations import math class a : def __init__( self : List[str] , lowerCAmelCase : int ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: Union[str, Any] =size # approximate the overall size of segment tree with given value SCREAMING_SNAKE_CASE_: Any =[0 for i in range(0 , 4 * size )] # create array to store lazy update SCREAMING_SNAKE_CASE_: Tuple =[0 for i in range(0 , 4 * size )] SCREAMING_SNAKE_CASE_: Optional[Any] =[0 for i in range(0 , 4 * size )] # flag for lazy update def lowerCamelCase__ ( self : Optional[Any] , lowerCAmelCase : int ) -> int: '''simple docstring''' return idx * 2 def lowerCamelCase__ ( self : Optional[Any] , lowerCAmelCase : int ) -> int: '''simple docstring''' return idx * 2 + 1 def lowerCamelCase__ ( self : Dict , lowerCAmelCase : int , lowerCAmelCase : int , lowerCAmelCase : int , lowerCAmelCase : list[int] ) -> None: '''simple docstring''' if left_element == right_element: SCREAMING_SNAKE_CASE_: Union[str, Any] =a[left_element - 1] else: SCREAMING_SNAKE_CASE_: List[Any] =(left_element + right_element) // 2 self.build(self.left(lowerCAmelCase ) , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) self.build(self.right(lowerCAmelCase ) , mid + 1 , lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[Any] =max( self.segment_tree[self.left(lowerCAmelCase )] , self.segment_tree[self.right(lowerCAmelCase )] ) def lowerCamelCase__ ( self : Optional[Any] , lowerCAmelCase : int , lowerCAmelCase : int , lowerCAmelCase : int , lowerCAmelCase : int , lowerCAmelCase : int , lowerCAmelCase : int ) -> bool: '''simple docstring''' if self.flag[idx] is True: SCREAMING_SNAKE_CASE_: Optional[Any] =self.lazy[idx] SCREAMING_SNAKE_CASE_: Optional[int] =False if left_element != right_element: SCREAMING_SNAKE_CASE_: List[str] =self.lazy[idx] SCREAMING_SNAKE_CASE_: Tuple =self.lazy[idx] SCREAMING_SNAKE_CASE_: List[str] =True SCREAMING_SNAKE_CASE_: str =True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: SCREAMING_SNAKE_CASE_: List[str] =val if left_element != right_element: SCREAMING_SNAKE_CASE_: Tuple =val SCREAMING_SNAKE_CASE_: str =val SCREAMING_SNAKE_CASE_: List[Any] =True SCREAMING_SNAKE_CASE_: Tuple =True return True SCREAMING_SNAKE_CASE_: Tuple =(left_element + right_element) // 2 self.update(self.left(lowerCAmelCase ) , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) self.update(self.right(lowerCAmelCase ) , mid + 1 , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Any =max( self.segment_tree[self.left(lowerCAmelCase )] , self.segment_tree[self.right(lowerCAmelCase )] ) return True def lowerCamelCase__ ( self : List[Any] , lowerCAmelCase : int , lowerCAmelCase : int , lowerCAmelCase : int , lowerCAmelCase : int , lowerCAmelCase : int ) -> int | float: '''simple docstring''' if self.flag[idx] is True: SCREAMING_SNAKE_CASE_: List[str] =self.lazy[idx] SCREAMING_SNAKE_CASE_: Dict =False if left_element != right_element: SCREAMING_SNAKE_CASE_: Optional[Any] =self.lazy[idx] SCREAMING_SNAKE_CASE_: Any =self.lazy[idx] SCREAMING_SNAKE_CASE_: List[str] =True SCREAMING_SNAKE_CASE_: str =True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] SCREAMING_SNAKE_CASE_: Dict =(left_element + right_element) // 2 SCREAMING_SNAKE_CASE_: List[str] =self.query(self.left(lowerCAmelCase ) , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Dict =self.query(self.right(lowerCAmelCase ) , mid + 1 , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) return max(lowerCAmelCase , lowerCAmelCase ) def __str__( self : List[str] ) -> str: '''simple docstring''' return str([self.query(1 , 1 , self.size , lowerCAmelCase , lowerCAmelCase ) for i in range(1 , self.size + 1 )] ) if __name__ == "__main__": _UpperCAmelCase = [1, 2, -4, 7, 3, -5, 6, 1_1, -2_0, 9, 1_4, 1_5, 5, 2, -8] _UpperCAmelCase = 1_5 _UpperCAmelCase = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 1_1)) print(segt.query(1, 1, size, 7, 1_2)) segt.update(1, 1, size, 1, 3, 1_1_1) print(segt.query(1, 1, size, 1, 1_5)) segt.update(1, 1, size, 7, 8, 2_3_5) print(segt)
36
"""simple docstring""" import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() _UpperCAmelCase = logging.get_logger("""transformers.models.speecht5""") def __magic_name__ ( lowercase , lowercase , lowercase ): hf_model.apply_weight_norm() SCREAMING_SNAKE_CASE_: Tuple =checkpoint["""input_conv.weight_g"""] SCREAMING_SNAKE_CASE_: Optional[int] =checkpoint["""input_conv.weight_v"""] SCREAMING_SNAKE_CASE_: Optional[int] =checkpoint["""input_conv.bias"""] for i in range(len(config.upsample_rates ) ): SCREAMING_SNAKE_CASE_: Any =checkpoint[f'''upsamples.{i}.1.weight_g'''] SCREAMING_SNAKE_CASE_: Any =checkpoint[f'''upsamples.{i}.1.weight_v'''] SCREAMING_SNAKE_CASE_: List[str] =checkpoint[f'''upsamples.{i}.1.bias'''] for i in range(len(config.upsample_rates ) * len(config.resblock_kernel_sizes ) ): for j in range(len(config.resblock_dilation_sizes ) ): SCREAMING_SNAKE_CASE_: Dict =checkpoint[f'''blocks.{i}.convs1.{j}.1.weight_g'''] SCREAMING_SNAKE_CASE_: Any =checkpoint[f'''blocks.{i}.convs1.{j}.1.weight_v'''] SCREAMING_SNAKE_CASE_: Union[str, Any] =checkpoint[f'''blocks.{i}.convs1.{j}.1.bias'''] SCREAMING_SNAKE_CASE_: Dict =checkpoint[f'''blocks.{i}.convs2.{j}.1.weight_g'''] SCREAMING_SNAKE_CASE_: Any =checkpoint[f'''blocks.{i}.convs2.{j}.1.weight_v'''] SCREAMING_SNAKE_CASE_: List[Any] =checkpoint[f'''blocks.{i}.convs2.{j}.1.bias'''] SCREAMING_SNAKE_CASE_: Tuple =checkpoint["""output_conv.1.weight_g"""] SCREAMING_SNAKE_CASE_: List[str] =checkpoint["""output_conv.1.weight_v"""] SCREAMING_SNAKE_CASE_: Optional[int] =checkpoint["""output_conv.1.bias"""] hf_model.remove_weight_norm() @torch.no_grad() def __magic_name__ ( lowercase , lowercase , lowercase , lowercase=None , lowercase=None , ): if config_path is not None: SCREAMING_SNAKE_CASE_: List[Any] =SpeechTaHifiGanConfig.from_pretrained(lowercase ) else: SCREAMING_SNAKE_CASE_: Optional[Any] =SpeechTaHifiGanConfig() SCREAMING_SNAKE_CASE_: Union[str, Any] =SpeechTaHifiGan(lowercase ) SCREAMING_SNAKE_CASE_: Any =torch.load(lowercase ) load_weights(orig_checkpoint["""model"""]["""generator"""] , lowercase , lowercase ) SCREAMING_SNAKE_CASE_: List[Any] =np.load(lowercase ) SCREAMING_SNAKE_CASE_: Any =stats[0].reshape(-1 ) SCREAMING_SNAKE_CASE_: str =stats[1].reshape(-1 ) SCREAMING_SNAKE_CASE_: Dict =torch.from_numpy(lowercase ).float() SCREAMING_SNAKE_CASE_: Dict =torch.from_numpy(lowercase ).float() model.save_pretrained(lowercase ) if repo_id: print("""Pushing to the hub...""" ) model.push_to_hub(lowercase ) if __name__ == "__main__": _UpperCAmelCase = argparse.ArgumentParser() parser.add_argument("""--checkpoint_path""", required=True, default=None, type=str, help="""Path to original checkpoint""") parser.add_argument("""--stats_path""", required=True, default=None, type=str, help="""Path to stats.npy file""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--pytorch_dump_folder_path""", required=True, default=None, type=str, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--push_to_hub""", default=None, type=str, help="""Where to upload the converted model on the 🤗 hub.""" ) _UpperCAmelCase = parser.parse_args() convert_hifigan_checkpoint( args.checkpoint_path, args.stats_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
36
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _UpperCAmelCase = { """configuration_tapas""": ["""TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TapasConfig"""], """tokenization_tapas""": ["""TapasTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ """TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST""", """TapasForMaskedLM""", """TapasForQuestionAnswering""", """TapasForSequenceClassification""", """TapasModel""", """TapasPreTrainedModel""", """load_tf_weights_in_tapas""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ """TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFTapasForMaskedLM""", """TFTapasForQuestionAnswering""", """TFTapasForSequenceClassification""", """TFTapasModel""", """TFTapasPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_tapas import TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP, TapasConfig from .tokenization_tapas import TapasTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tapas import ( TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasPreTrainedModel, load_tf_weights_in_tapas, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_tapas import ( TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TFTapasForMaskedLM, TFTapasForQuestionAnswering, TFTapasForSequenceClassification, TFTapasModel, TFTapasPreTrainedModel, ) else: import sys _UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
36
"""simple docstring""" import argparse import requests import torch from PIL import Image from transformers import ViTMAEConfig, ViTMAEForPreTraining, ViTMAEImageProcessor def __magic_name__ ( lowercase ): if "cls_token" in name: SCREAMING_SNAKE_CASE_: Optional[int] =name.replace("""cls_token""" , """vit.embeddings.cls_token""" ) if "mask_token" in name: SCREAMING_SNAKE_CASE_: Optional[int] =name.replace("""mask_token""" , """decoder.mask_token""" ) if "decoder_pos_embed" in name: SCREAMING_SNAKE_CASE_: int =name.replace("""decoder_pos_embed""" , """decoder.decoder_pos_embed""" ) if "pos_embed" in name and "decoder" not in name: SCREAMING_SNAKE_CASE_: str =name.replace("""pos_embed""" , """vit.embeddings.position_embeddings""" ) if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE_: str =name.replace("""patch_embed.proj""" , """vit.embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: SCREAMING_SNAKE_CASE_: int =name.replace("""patch_embed.norm""" , """vit.embeddings.norm""" ) if "decoder_blocks" in name: SCREAMING_SNAKE_CASE_: List[Any] =name.replace("""decoder_blocks""" , """decoder.decoder_layers""" ) if "blocks" in name: SCREAMING_SNAKE_CASE_: str =name.replace("""blocks""" , """vit.encoder.layer""" ) if "attn.proj" in name: SCREAMING_SNAKE_CASE_: Optional[Any] =name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: SCREAMING_SNAKE_CASE_: Union[str, Any] =name.replace("""attn""" , """attention.self""" ) if "norm1" in name: SCREAMING_SNAKE_CASE_: Optional[Any] =name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: SCREAMING_SNAKE_CASE_: int =name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE_: int =name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE_: Dict =name.replace("""mlp.fc2""" , """output.dense""" ) if "decoder_embed" in name: SCREAMING_SNAKE_CASE_: List[str] =name.replace("""decoder_embed""" , """decoder.decoder_embed""" ) if "decoder_norm" in name: SCREAMING_SNAKE_CASE_: Tuple =name.replace("""decoder_norm""" , """decoder.decoder_norm""" ) if "decoder_pred" in name: SCREAMING_SNAKE_CASE_: Any =name.replace("""decoder_pred""" , """decoder.decoder_pred""" ) if "norm.weight" in name and "decoder" not in name: SCREAMING_SNAKE_CASE_: List[str] =name.replace("""norm.weight""" , """vit.layernorm.weight""" ) if "norm.bias" in name and "decoder" not in name: SCREAMING_SNAKE_CASE_: List[str] =name.replace("""norm.bias""" , """vit.layernorm.bias""" ) return name def __magic_name__ ( lowercase , lowercase ): for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE_: Optional[int] =orig_state_dict.pop(lowercase ) if "qkv" in key: SCREAMING_SNAKE_CASE_: Dict =key.split(""".""" ) SCREAMING_SNAKE_CASE_: Optional[Any] =int(key_split[1] ) if "decoder_blocks" in key: SCREAMING_SNAKE_CASE_: int =config.decoder_hidden_size SCREAMING_SNAKE_CASE_: Optional[int] ="""decoder.decoder_layers.""" if "weight" in key: SCREAMING_SNAKE_CASE_: Dict =val[:dim, :] SCREAMING_SNAKE_CASE_: Tuple =val[dim : dim * 2, :] SCREAMING_SNAKE_CASE_: str =val[-dim:, :] elif "bias" in key: SCREAMING_SNAKE_CASE_: List[Any] =val[:dim] SCREAMING_SNAKE_CASE_: Tuple =val[dim : dim * 2] SCREAMING_SNAKE_CASE_: List[Any] =val[-dim:] else: SCREAMING_SNAKE_CASE_: Any =config.hidden_size SCREAMING_SNAKE_CASE_: Union[str, Any] ="""vit.encoder.layer.""" if "weight" in key: SCREAMING_SNAKE_CASE_: Optional[Any] =val[:dim, :] SCREAMING_SNAKE_CASE_: Optional[Any] =val[dim : dim * 2, :] SCREAMING_SNAKE_CASE_: Dict =val[-dim:, :] elif "bias" in key: SCREAMING_SNAKE_CASE_: Optional[Any] =val[:dim] SCREAMING_SNAKE_CASE_: Any =val[dim : dim * 2] SCREAMING_SNAKE_CASE_: Optional[Any] =val[-dim:] else: SCREAMING_SNAKE_CASE_: Tuple =val return orig_state_dict def __magic_name__ ( lowercase , lowercase ): SCREAMING_SNAKE_CASE_: Dict =ViTMAEConfig() if "large" in checkpoint_url: SCREAMING_SNAKE_CASE_: List[Any] =1024 SCREAMING_SNAKE_CASE_: Dict =4096 SCREAMING_SNAKE_CASE_: Tuple =24 SCREAMING_SNAKE_CASE_: int =16 elif "huge" in checkpoint_url: SCREAMING_SNAKE_CASE_: Union[str, Any] =14 SCREAMING_SNAKE_CASE_: Any =1280 SCREAMING_SNAKE_CASE_: Dict =5120 SCREAMING_SNAKE_CASE_: Optional[int] =32 SCREAMING_SNAKE_CASE_: Optional[Any] =16 SCREAMING_SNAKE_CASE_: Tuple =ViTMAEForPreTraining(lowercase ) SCREAMING_SNAKE_CASE_: Optional[int] =torch.hub.load_state_dict_from_url(lowercase , map_location="""cpu""" )["""model"""] SCREAMING_SNAKE_CASE_: Optional[Any] =ViTMAEImageProcessor(size=config.image_size ) SCREAMING_SNAKE_CASE_: str =convert_state_dict(lowercase , lowercase ) model.load_state_dict(lowercase ) model.eval() SCREAMING_SNAKE_CASE_: Tuple ="""https://user-images.githubusercontent.com/11435359/147738734-196fd92f-9260-48d5-ba7e-bf103d29364d.jpg""" SCREAMING_SNAKE_CASE_: List[Any] =Image.open(requests.get(lowercase , stream=lowercase ).raw ) SCREAMING_SNAKE_CASE_: int =ViTMAEImageProcessor(size=config.image_size ) SCREAMING_SNAKE_CASE_: int =image_processor(images=lowercase , return_tensors="""pt""" ) # forward pass torch.manual_seed(2 ) SCREAMING_SNAKE_CASE_: Optional[Any] =model(**lowercase ) SCREAMING_SNAKE_CASE_: Optional[int] =outputs.logits if "large" in checkpoint_url: SCREAMING_SNAKE_CASE_: Dict =torch.tensor( [[-0.7_309, -0.7_128, -1.0_169], [-1.0_161, -0.9_058, -1.1_878], [-1.0_478, -0.9_411, -1.1_911]] ) elif "huge" in checkpoint_url: SCREAMING_SNAKE_CASE_: Tuple =torch.tensor( [[-1.1_599, -0.9_199, -1.2_221], [-1.1_952, -0.9_269, -1.2_307], [-1.2_143, -0.9_337, -1.2_262]] ) else: SCREAMING_SNAKE_CASE_: Any =torch.tensor( [[-0.9_192, -0.8_481, -1.1_259], [-1.1_349, -1.0_034, -1.2_599], [-1.1_757, -1.0_429, -1.2_726]] ) # verify logits assert torch.allclose(logits[0, :3, :3] , lowercase , atol=1e-4 ) print(f'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowercase ) if __name__ == "__main__": _UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--checkpoint_url""", default="""https://dl.fbaipublicfiles.com/mae/visualize/mae_visualize_vit_base.pth""", type=str, help="""URL of the checkpoint you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) _UpperCAmelCase = parser.parse_args() convert_vit_mae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
36
1
"""simple docstring""" def __magic_name__ ( lowercase ): if not isinstance(lowercase , lowercase ): raise ValueError("""Input series is not valid, valid series - [2, 4, 6]""" ) if len(lowercase ) == 0: raise ValueError("""Input list must be a non empty list""" ) if len(lowercase ) == 1: return True SCREAMING_SNAKE_CASE_: Union[str, Any] =series[1] - series[0] for index in range(len(lowercase ) - 1 ): if series[index + 1] - series[index] != common_diff: return False return True def __magic_name__ ( lowercase ): if not isinstance(lowercase , lowercase ): raise ValueError("""Input series is not valid, valid series - [2, 4, 6]""" ) if len(lowercase ) == 0: raise ValueError("""Input list must be a non empty list""" ) SCREAMING_SNAKE_CASE_: Tuple =0 for val in series: answer += val return answer / len(lowercase ) if __name__ == "__main__": import doctest doctest.testmod()
36
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _UpperCAmelCase = { """configuration_xlm""": ["""XLM_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XLMConfig""", """XLMOnnxConfig"""], """tokenization_xlm""": ["""XLMTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ """XLM_PRETRAINED_MODEL_ARCHIVE_LIST""", """XLMForMultipleChoice""", """XLMForQuestionAnswering""", """XLMForQuestionAnsweringSimple""", """XLMForSequenceClassification""", """XLMForTokenClassification""", """XLMModel""", """XLMPreTrainedModel""", """XLMWithLMHeadModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ """TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFXLMForMultipleChoice""", """TFXLMForQuestionAnsweringSimple""", """TFXLMForSequenceClassification""", """TFXLMForTokenClassification""", """TFXLMMainLayer""", """TFXLMModel""", """TFXLMPreTrainedModel""", """TFXLMWithLMHeadModel""", ] if TYPE_CHECKING: from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig from .tokenization_xlm import XLMTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm import ( XLM_PRETRAINED_MODEL_ARCHIVE_LIST, XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMPreTrainedModel, XLMWithLMHeadModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm import ( TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMForMultipleChoice, TFXLMForQuestionAnsweringSimple, TFXLMForSequenceClassification, TFXLMForTokenClassification, TFXLMMainLayer, TFXLMModel, TFXLMPreTrainedModel, TFXLMWithLMHeadModel, ) else: import sys _UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
36
1
"""simple docstring""" def __magic_name__ ( lowercase = 400_0000 ): SCREAMING_SNAKE_CASE_: Optional[Any] =[0, 1] SCREAMING_SNAKE_CASE_: Optional[int] =0 while fib[i] <= n: fib.append(fib[i] + fib[i + 1] ) if fib[i + 2] > n: break i += 1 SCREAMING_SNAKE_CASE_: Union[str, Any] =0 for j in range(len(lowercase ) - 1 ): if fib[j] % 2 == 0: total += fib[j] return total if __name__ == "__main__": print(f"""{solution() = }""")
36
"""simple docstring""" def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: int =False while is_sorted is False: # Until all the indices are traversed keep looping SCREAMING_SNAKE_CASE_: Tuple =True for i in range(0 , len(lowercase ) - 1 , 2 ): # iterating over all even indices if input_list[i] > input_list[i + 1]: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[int] =input_list[i + 1], input_list[i] # swapping if elements not in order SCREAMING_SNAKE_CASE_: Tuple =False for i in range(1 , len(lowercase ) - 1 , 2 ): # iterating over all odd indices if input_list[i] > input_list[i + 1]: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: str =input_list[i + 1], input_list[i] # swapping if elements not in order SCREAMING_SNAKE_CASE_: str =False return input_list if __name__ == "__main__": print("""Enter list to be sorted""") _UpperCAmelCase = [int(x) for x in input().split()] # inputing elements of the list in one line _UpperCAmelCase = odd_even_sort(input_list) print("""The sorted list is""") print(sorted_list)
36
1
"""simple docstring""" import time import warnings from abc import ABC from copy import deepcopy from typing import Optional import torch from ..utils import add_start_docstrings, logging _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = r""" Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`): Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax or scores for each vocabulary token after SoftMax. kwargs (`Dict[str, Any]`, *optional*): Additional stopping criteria specific kwargs. Return: `bool`. `False` indicates we should continue, `True` indicates we should stop. """ class a ( UpperCAmelCase__ ): @add_start_docstrings(lowerCAmelCase ) def __call__( self : int , lowerCAmelCase : torch.LongTensor , lowerCAmelCase : torch.FloatTensor , **lowerCAmelCase : Dict ) -> bool: '''simple docstring''' raise NotImplementedError("""StoppingCriteria needs to be subclassed""" ) class a ( UpperCAmelCase__ ): def __init__( self : Optional[Any] , lowerCAmelCase : int , lowerCAmelCase : Optional[int] = None ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[Any] =max_length SCREAMING_SNAKE_CASE_: Dict =max_position_embeddings @add_start_docstrings(lowerCAmelCase ) def __call__( self : str , lowerCAmelCase : torch.LongTensor , lowerCAmelCase : torch.FloatTensor , **lowerCAmelCase : Any ) -> bool: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[Any] =input_ids.shape[-1] SCREAMING_SNAKE_CASE_: int =cur_len >= self.max_length if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings: logger.warning_once( """This is a friendly reminder - the current text generation call will exceed the model's predefined """ f'''maximum length ({self.max_position_embeddings}). Depending on the model, you may observe ''' """exceptions, performance degradation, or nothing at all.""" ) return is_done class a ( UpperCAmelCase__ ): def __init__( self : Optional[Any] , lowerCAmelCase : int , lowerCAmelCase : int ) -> Optional[int]: '''simple docstring''' warnings.warn( """The class `MaxNewTokensCriteria` is deprecated. """ f'''Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` ''' """with `max_length = start_length + max_new_tokens` instead.""" , lowerCAmelCase , ) SCREAMING_SNAKE_CASE_: Optional[int] =start_length SCREAMING_SNAKE_CASE_: Optional[int] =max_new_tokens SCREAMING_SNAKE_CASE_: Optional[Any] =start_length + max_new_tokens @add_start_docstrings(lowerCAmelCase ) def __call__( self : Optional[int] , lowerCAmelCase : torch.LongTensor , lowerCAmelCase : torch.FloatTensor , **lowerCAmelCase : str ) -> bool: '''simple docstring''' return input_ids.shape[-1] >= self.max_length class a ( UpperCAmelCase__ ): def __init__( self : Optional[int] , lowerCAmelCase : float , lowerCAmelCase : Optional[float] = None ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =max_time SCREAMING_SNAKE_CASE_: Optional[int] =time.time() if initial_timestamp is None else initial_timestamp @add_start_docstrings(lowerCAmelCase ) def __call__( self : str , lowerCAmelCase : torch.LongTensor , lowerCAmelCase : torch.FloatTensor , **lowerCAmelCase : Dict ) -> bool: '''simple docstring''' return time.time() - self.initial_timestamp > self.max_time class a ( UpperCAmelCase__ ): @add_start_docstrings(lowerCAmelCase ) def __call__( self : List[str] , lowerCAmelCase : torch.LongTensor , lowerCAmelCase : torch.FloatTensor , **lowerCAmelCase : int ) -> bool: '''simple docstring''' return any(criteria(lowerCAmelCase , lowerCAmelCase ) for criteria in self ) @property def lowerCamelCase__ ( self : Dict ) -> Optional[int]: '''simple docstring''' for stopping_criterium in self: if isinstance(lowerCAmelCase , lowerCAmelCase ): return stopping_criterium.max_length elif isinstance(lowerCAmelCase , lowerCAmelCase ): return stopping_criterium.max_length return None def __magic_name__ ( lowercase , lowercase ): SCREAMING_SNAKE_CASE_: List[Any] =stopping_criteria.max_length SCREAMING_SNAKE_CASE_: Tuple =deepcopy(lowercase ) if stopping_max_length is not None and stopping_max_length != max_length: warnings.warn("""You set different `max_length` for stopping criteria and `max_length` parameter""" , lowercase ) elif stopping_max_length is None: new_stopping_criteria.append(MaxLengthCriteria(max_length=lowercase ) ) return new_stopping_criteria
36
"""simple docstring""" def __magic_name__ ( lowercase ): return str(lowercase ) == str(lowercase )[::-1] def __magic_name__ ( lowercase ): return int(lowercase ) + int(str(lowercase )[::-1] ) def __magic_name__ ( lowercase = 1_0000 ): SCREAMING_SNAKE_CASE_: List[str] =[] for num in range(1 , lowercase ): SCREAMING_SNAKE_CASE_: List[Any] =0 SCREAMING_SNAKE_CASE_: int =num while iterations < 50: SCREAMING_SNAKE_CASE_: Optional[Any] =sum_reverse(lowercase ) iterations += 1 if is_palindrome(lowercase ): break else: lychrel_nums.append(lowercase ) return len(lowercase ) if __name__ == "__main__": print(f"""{solution() = }""")
36
1
"""simple docstring""" import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": _UpperCAmelCase = argparse.ArgumentParser() parser.add_argument( """--checkpoint_path""", default=None, type=str, required=True, help="""Path to the checkpoint to convert.""" ) parser.add_argument( """--original_config_file""", type=str, required=True, help="""The YAML config file corresponding to the original architecture.""", ) parser.add_argument( """--num_in_channels""", default=None, type=int, help="""The number of input channels. If `None` number of input channels will be automatically inferred.""", ) parser.add_argument( """--image_size""", default=5_1_2, type=int, help=( """The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2""" """ Base. Use 768 for Stable Diffusion v2.""" ), ) parser.add_argument( """--extract_ema""", action="""store_true""", help=( """Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights""" """ or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield""" """ higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.""" ), ) parser.add_argument( """--upcast_attention""", action="""store_true""", help=( """Whether the attention computation should always be upcasted. This is necessary when running stable""" """ diffusion 2.1.""" ), ) parser.add_argument( """--from_safetensors""", action="""store_true""", help="""If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.""", ) parser.add_argument( """--to_safetensors""", action="""store_true""", help="""Whether to store pipeline in safetensors format or not.""", ) parser.add_argument("""--dump_path""", default=None, type=str, required=True, help="""Path to the output model.""") parser.add_argument("""--device""", type=str, help="""Device to use (e.g. cpu, cuda:0, cuda:1, etc.)""") def __magic_name__ ( lowercase ): if string == "True": return True elif string == "False": return False else: raise ValueError(f'''could not parse string as bool {string}''' ) parser.add_argument( """--use_linear_projection""", help="""Override for use linear projection""", required=False, type=parse_bool ) parser.add_argument("""--cross_attention_dim""", help="""Override for cross attention_dim""", required=False, type=int) _UpperCAmelCase = parser.parse_args() _UpperCAmelCase = download_controlnet_from_original_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, extract_ema=args.extract_ema, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, use_linear_projection=args.use_linear_projection, cross_attention_dim=args.cross_attention_dim, ) controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
36
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available from ...utils import OptionalDependencyNotAvailable _UpperCAmelCase = {"""configuration_dpt""": ["""DPT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """DPTConfig"""]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = ["""DPTFeatureExtractor"""] _UpperCAmelCase = ["""DPTImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ """DPT_PRETRAINED_MODEL_ARCHIVE_LIST""", """DPTForDepthEstimation""", """DPTForSemanticSegmentation""", """DPTModel""", """DPTPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_dpt import DPTFeatureExtractor from .image_processing_dpt import DPTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dpt import ( DPT_PRETRAINED_MODEL_ARCHIVE_LIST, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel, DPTPreTrainedModel, ) else: import sys _UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
36
1
"""simple docstring""" from __future__ import annotations import unittest from transformers import DebertaVaConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, TFDebertaVaModel, ) class a : def __init__( self : List[str] , lowerCAmelCase : Any , lowerCAmelCase : Optional[Any]=13 , lowerCAmelCase : Union[str, Any]=7 , lowerCAmelCase : Optional[Any]=True , lowerCAmelCase : Tuple=True , lowerCAmelCase : Dict=True , lowerCAmelCase : Dict=True , lowerCAmelCase : Any=99 , lowerCAmelCase : List[str]=32 , lowerCAmelCase : Dict=2 , lowerCAmelCase : Optional[int]=4 , lowerCAmelCase : Any=37 , lowerCAmelCase : List[str]="gelu" , lowerCAmelCase : List[Any]=0.1 , lowerCAmelCase : Tuple=0.1 , lowerCAmelCase : List[str]=512 , lowerCAmelCase : List[str]=16 , lowerCAmelCase : Dict=2 , lowerCAmelCase : int=0.0_2 , lowerCAmelCase : List[Any]=False , lowerCAmelCase : str=True , lowerCAmelCase : Tuple="None" , lowerCAmelCase : Union[str, Any]=3 , lowerCAmelCase : List[str]=4 , lowerCAmelCase : int=None , ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[Any] =parent SCREAMING_SNAKE_CASE_: int =batch_size SCREAMING_SNAKE_CASE_: int =seq_length SCREAMING_SNAKE_CASE_: str =is_training SCREAMING_SNAKE_CASE_: Optional[int] =use_input_mask SCREAMING_SNAKE_CASE_: List[Any] =use_token_type_ids SCREAMING_SNAKE_CASE_: str =use_labels SCREAMING_SNAKE_CASE_: List[Any] =vocab_size SCREAMING_SNAKE_CASE_: Union[str, Any] =hidden_size SCREAMING_SNAKE_CASE_: List[str] =num_hidden_layers SCREAMING_SNAKE_CASE_: Dict =num_attention_heads SCREAMING_SNAKE_CASE_: int =intermediate_size SCREAMING_SNAKE_CASE_: List[Any] =hidden_act SCREAMING_SNAKE_CASE_: Any =hidden_dropout_prob SCREAMING_SNAKE_CASE_: List[Any] =attention_probs_dropout_prob SCREAMING_SNAKE_CASE_: Optional[int] =max_position_embeddings SCREAMING_SNAKE_CASE_: Optional[int] =type_vocab_size SCREAMING_SNAKE_CASE_: List[Any] =type_sequence_label_size SCREAMING_SNAKE_CASE_: Optional[Any] =initializer_range SCREAMING_SNAKE_CASE_: Dict =num_labels SCREAMING_SNAKE_CASE_: Tuple =num_choices SCREAMING_SNAKE_CASE_: Dict =relative_attention SCREAMING_SNAKE_CASE_: str =position_biased_input SCREAMING_SNAKE_CASE_: Any =pos_att_type SCREAMING_SNAKE_CASE_: List[str] =scope def lowerCamelCase__ ( self : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE_: List[str] =None if self.use_input_mask: SCREAMING_SNAKE_CASE_: Tuple =random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE_: Union[str, Any] =None if self.use_token_type_ids: SCREAMING_SNAKE_CASE_: int =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE_: int =None SCREAMING_SNAKE_CASE_: Dict =None SCREAMING_SNAKE_CASE_: Any =None if self.use_labels: SCREAMING_SNAKE_CASE_: str =ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE_: Dict =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE_: Union[str, Any] =DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , initializer_range=self.initializer_range , return_dict=lowerCAmelCase , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCamelCase__ ( self : Optional[Any] , lowerCAmelCase : int , lowerCAmelCase : List[str] , lowerCAmelCase : Optional[int] , lowerCAmelCase : List[Any] , lowerCAmelCase : int , lowerCAmelCase : Optional[int] , lowerCAmelCase : Optional[Any] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =TFDebertaVaModel(config=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[Any] ={"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} SCREAMING_SNAKE_CASE_: List[str] =[input_ids, input_mask] SCREAMING_SNAKE_CASE_: Union[str, Any] =model(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Union[str, Any] =model(lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase__ ( self : Optional[Any] , lowerCAmelCase : Dict , lowerCAmelCase : List[Any] , lowerCAmelCase : List[str] , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : int , lowerCAmelCase : List[Any] , lowerCAmelCase : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =TFDebertaVaForMaskedLM(config=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] ={ """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } SCREAMING_SNAKE_CASE_: Dict =model(lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCamelCase__ ( self : int , lowerCAmelCase : int , lowerCAmelCase : int , lowerCAmelCase : int , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Optional[Any] , lowerCAmelCase : str , lowerCAmelCase : Optional[Any] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =self.num_labels SCREAMING_SNAKE_CASE_: int =TFDebertaVaForSequenceClassification(config=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple ={ """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } SCREAMING_SNAKE_CASE_: Optional[int] =model(lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase__ ( self : int , lowerCAmelCase : Optional[Any] , lowerCAmelCase : Any , lowerCAmelCase : int , lowerCAmelCase : Dict , lowerCAmelCase : Dict , lowerCAmelCase : Optional[Any] , lowerCAmelCase : List[Any] ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE_: int =self.num_labels SCREAMING_SNAKE_CASE_: Optional[int] =TFDebertaVaForTokenClassification(config=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Any ={ """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } SCREAMING_SNAKE_CASE_: Union[str, Any] =model(lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCamelCase__ ( self : Tuple , lowerCAmelCase : Optional[Any] , lowerCAmelCase : Tuple , lowerCAmelCase : Dict , lowerCAmelCase : List[Any] , lowerCAmelCase : List[str] , lowerCAmelCase : Optional[int] , lowerCAmelCase : Optional[int] ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =TFDebertaVaForQuestionAnswering(config=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple ={ """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } SCREAMING_SNAKE_CASE_: Union[str, Any] =model(lowerCAmelCase ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCamelCase__ ( self : Union[str, Any] ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[str] =self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ): Optional[int] =config_and_inputs SCREAMING_SNAKE_CASE_: Tuple ={"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class a ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): UpperCamelCase : Optional[int] = ( ( TFDebertaVaModel, TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, ) if is_tf_available() else () ) UpperCamelCase : int = ( { 'feature-extraction': TFDebertaVaModel, 'fill-mask': TFDebertaVaForMaskedLM, 'question-answering': TFDebertaVaForQuestionAnswering, 'text-classification': TFDebertaVaForSequenceClassification, 'token-classification': TFDebertaVaForTokenClassification, 'zero-shot': TFDebertaVaForSequenceClassification, } if is_tf_available() else {} ) UpperCamelCase : Union[str, Any] = False UpperCamelCase : str = False def lowerCamelCase__ ( self : Any ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[str] =TFDebertaVaModelTester(self ) SCREAMING_SNAKE_CASE_: Union[str, Any] =ConfigTester(self , config_class=lowerCAmelCase , hidden_size=37 ) def lowerCamelCase__ ( self : List[str] ) -> Optional[Any]: '''simple docstring''' self.config_tester.run_common_tests() def lowerCamelCase__ ( self : Any ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase ) def lowerCamelCase__ ( self : Optional[Any] ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*lowerCAmelCase ) def lowerCamelCase__ ( self : List[Any] ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: int =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowerCAmelCase ) def lowerCamelCase__ ( self : int ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*lowerCAmelCase ) def lowerCamelCase__ ( self : List[str] ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowerCAmelCase ) @slow def lowerCamelCase__ ( self : List[str] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Union[str, Any] =TFDebertaVaModel.from_pretrained("""kamalkraj/deberta-v2-xlarge""" ) self.assertIsNotNone(lowerCAmelCase ) @require_tf class a ( unittest.TestCase ): @unittest.skip(reason="""Model not available yet""" ) def lowerCamelCase__ ( self : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' pass @slow def lowerCamelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =TFDebertaVaModel.from_pretrained("""kamalkraj/deberta-v2-xlarge""" ) SCREAMING_SNAKE_CASE_: Dict =tf.constant([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] ) SCREAMING_SNAKE_CASE_: Tuple =tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) SCREAMING_SNAKE_CASE_: List[str] =model(lowerCAmelCase , attention_mask=lowerCAmelCase )[0] SCREAMING_SNAKE_CASE_: Optional[int] =tf.constant( [[[0.2_3_5_6, 0.1_9_4_8, 0.0_3_6_9], [-0.1_0_6_3, 0.3_5_8_6, -0.5_1_5_2], [-0.6_3_9_9, -0.0_2_5_9, -0.2_5_2_5]]] ) tf.debugging.assert_near(output[:, 1:4, 1:4] , lowerCAmelCase , atol=1E-4 )
36
"""simple docstring""" from __future__ import annotations import math import random from typing import Any class a : def __init__( self : str ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: list[Any] =[] SCREAMING_SNAKE_CASE_: int =0 SCREAMING_SNAKE_CASE_: int =0 def lowerCamelCase__ ( self : Optional[Any] ) -> bool: '''simple docstring''' return self.head == self.tail def lowerCamelCase__ ( self : Tuple , lowerCAmelCase : Any ) -> None: '''simple docstring''' self.data.append(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =self.tail + 1 def lowerCamelCase__ ( self : int ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: int =self.data[self.head] SCREAMING_SNAKE_CASE_: Optional[int] =self.head + 1 return ret def lowerCamelCase__ ( self : Optional[Any] ) -> int: '''simple docstring''' return self.tail - self.head def lowerCamelCase__ ( self : str ) -> None: '''simple docstring''' print(self.data ) print("""**************""" ) print(self.data[self.head : self.tail] ) class a : def __init__( self : Union[str, Any] , lowerCAmelCase : Any ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =data SCREAMING_SNAKE_CASE_: MyNode | None =None SCREAMING_SNAKE_CASE_: MyNode | None =None SCREAMING_SNAKE_CASE_: int =1 def lowerCamelCase__ ( self : Optional[Any] ) -> Any: '''simple docstring''' return self.data def lowerCamelCase__ ( self : List[Any] ) -> MyNode | None: '''simple docstring''' return self.left def lowerCamelCase__ ( self : Dict ) -> MyNode | None: '''simple docstring''' return self.right def lowerCamelCase__ ( self : Any ) -> int: '''simple docstring''' return self.height def lowerCamelCase__ ( self : Any , lowerCAmelCase : Any ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[Any] =data def lowerCamelCase__ ( self : Dict , lowerCAmelCase : MyNode | None ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =node def lowerCamelCase__ ( self : List[Any] , lowerCAmelCase : MyNode | None ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: str =node def lowerCamelCase__ ( self : int , lowerCAmelCase : int ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =height def __magic_name__ ( lowercase ): if node is None: return 0 return node.get_height() def __magic_name__ ( lowercase , lowercase ): if a > b: return a return b def __magic_name__ ( lowercase ): print("""left rotation node:""" , node.get_data() ) SCREAMING_SNAKE_CASE_: List[Any] =node.get_left() assert ret is not None node.set_left(ret.get_right() ) ret.set_right(lowercase ) SCREAMING_SNAKE_CASE_: Tuple =my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowercase ) SCREAMING_SNAKE_CASE_: int =my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(lowercase ) return ret def __magic_name__ ( lowercase ): print("""right rotation node:""" , node.get_data() ) SCREAMING_SNAKE_CASE_: List[Any] =node.get_right() assert ret is not None node.set_right(ret.get_left() ) ret.set_left(lowercase ) SCREAMING_SNAKE_CASE_: List[Any] =my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowercase ) SCREAMING_SNAKE_CASE_: Optional[int] =my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(lowercase ) return ret def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Any =node.get_left() assert left_child is not None node.set_left(left_rotation(lowercase ) ) return right_rotation(lowercase ) def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Dict =node.get_right() assert right_child is not None node.set_right(right_rotation(lowercase ) ) return left_rotation(lowercase ) def __magic_name__ ( lowercase , lowercase ): if node is None: return MyNode(lowercase ) if data < node.get_data(): node.set_left(insert_node(node.get_left() , lowercase ) ) if ( get_height(node.get_left() ) - get_height(node.get_right() ) == 2 ): # an unbalance detected SCREAMING_SNAKE_CASE_: Union[str, Any] =node.get_left() assert left_child is not None if ( data < left_child.get_data() ): # new node is the left child of the left child SCREAMING_SNAKE_CASE_: Any =right_rotation(lowercase ) else: SCREAMING_SNAKE_CASE_: List[Any] =lr_rotation(lowercase ) else: node.set_right(insert_node(node.get_right() , lowercase ) ) if get_height(node.get_right() ) - get_height(node.get_left() ) == 2: SCREAMING_SNAKE_CASE_: Tuple =node.get_right() assert right_child is not None if data < right_child.get_data(): SCREAMING_SNAKE_CASE_: Optional[Any] =rl_rotation(lowercase ) else: SCREAMING_SNAKE_CASE_: Optional[int] =left_rotation(lowercase ) SCREAMING_SNAKE_CASE_: Tuple =my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowercase ) return node def __magic_name__ ( lowercase ): while True: SCREAMING_SNAKE_CASE_: Dict =root.get_right() if right_child is None: break SCREAMING_SNAKE_CASE_: str =right_child return root.get_data() def __magic_name__ ( lowercase ): while True: SCREAMING_SNAKE_CASE_: str =root.get_left() if left_child is None: break SCREAMING_SNAKE_CASE_: Dict =left_child return root.get_data() def __magic_name__ ( lowercase , lowercase ): SCREAMING_SNAKE_CASE_: str =root.get_left() SCREAMING_SNAKE_CASE_: List[Any] =root.get_right() if root.get_data() == data: if left_child is not None and right_child is not None: SCREAMING_SNAKE_CASE_: Union[str, Any] =get_left_most(lowercase ) root.set_data(lowercase ) root.set_right(del_node(lowercase , lowercase ) ) elif left_child is not None: SCREAMING_SNAKE_CASE_: Optional[int] =left_child elif right_child is not None: SCREAMING_SNAKE_CASE_: Any =right_child else: return None elif root.get_data() > data: if left_child is None: print("""No such data""" ) return root else: root.set_left(del_node(lowercase , lowercase ) ) else: # root.get_data() < data if right_child is None: return root else: root.set_right(del_node(lowercase , lowercase ) ) if get_height(lowercase ) - get_height(lowercase ) == 2: assert right_child is not None if get_height(right_child.get_right() ) > get_height(right_child.get_left() ): SCREAMING_SNAKE_CASE_: Tuple =left_rotation(lowercase ) else: SCREAMING_SNAKE_CASE_: Optional[Any] =rl_rotation(lowercase ) elif get_height(lowercase ) - get_height(lowercase ) == -2: assert left_child is not None if get_height(left_child.get_left() ) > get_height(left_child.get_right() ): SCREAMING_SNAKE_CASE_: Optional[Any] =right_rotation(lowercase ) else: SCREAMING_SNAKE_CASE_: str =lr_rotation(lowercase ) SCREAMING_SNAKE_CASE_: str =my_max(get_height(root.get_right() ) , get_height(root.get_left() ) ) + 1 root.set_height(lowercase ) return root class a : def __init__( self : int ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: MyNode | None =None def lowerCamelCase__ ( self : List[Any] ) -> int: '''simple docstring''' return get_height(self.root ) def lowerCamelCase__ ( self : Optional[int] , lowerCAmelCase : Any ) -> None: '''simple docstring''' print("""insert:""" + str(lowerCAmelCase ) ) SCREAMING_SNAKE_CASE_: Tuple =insert_node(self.root , lowerCAmelCase ) def lowerCamelCase__ ( self : List[Any] , lowerCAmelCase : Any ) -> None: '''simple docstring''' print("""delete:""" + str(lowerCAmelCase ) ) if self.root is None: print("""Tree is empty!""" ) return SCREAMING_SNAKE_CASE_: Union[str, Any] =del_node(self.root , lowerCAmelCase ) def __str__( self : List[str] , ) -> str: # a level traversale, gives a more intuitive look on the tree '''simple docstring''' SCREAMING_SNAKE_CASE_: List[Any] ="""""" SCREAMING_SNAKE_CASE_: str =MyQueue() q.push(self.root ) SCREAMING_SNAKE_CASE_: List[str] =self.get_height() if layer == 0: return output SCREAMING_SNAKE_CASE_: int =0 while not q.is_empty(): SCREAMING_SNAKE_CASE_: int =q.pop() SCREAMING_SNAKE_CASE_: List[Any] =""" """ * int(math.pow(2 , layer - 1 ) ) output += space if node is None: output += "*" q.push(lowerCAmelCase ) q.push(lowerCAmelCase ) else: output += str(node.get_data() ) q.push(node.get_left() ) q.push(node.get_right() ) output += space SCREAMING_SNAKE_CASE_: List[Any] =cnt + 1 for i in range(100 ): if cnt == math.pow(2 , lowerCAmelCase ) - 1: SCREAMING_SNAKE_CASE_: int =layer - 1 if layer == 0: output += "\n*************************************" return output output += "\n" break output += "\n*************************************" return output def __magic_name__ ( ): import doctest doctest.testmod() if __name__ == "__main__": _test() _UpperCAmelCase = AVLtree() _UpperCAmelCase = list(range(1_0)) random.shuffle(lst) for i in lst: t.insert(i) print(str(t)) random.shuffle(lst) for i in lst: t.del_node(i) print(str(t))
36
1
"""simple docstring""" import bza import gzip import lzma import os import shutil import struct import tarfile import warnings import zipfile from abc import ABC, abstractmethod from pathlib import Path from typing import Dict, List, Optional, Type, Union from .. import config from .filelock import FileLock from .logging import get_logger _UpperCAmelCase = get_logger(__name__) class a : def __init__( self : Union[str, Any] , lowerCAmelCase : Optional[str] = None ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =( os.path.join(lowerCAmelCase , config.EXTRACTED_DATASETS_DIR ) if cache_dir else config.EXTRACTED_DATASETS_PATH ) SCREAMING_SNAKE_CASE_: Dict =Extractor def lowerCamelCase__ ( self : int , lowerCAmelCase : str ) -> str: '''simple docstring''' from .file_utils import hash_url_to_filename # Path where we extract compressed archives # We extract in the cache dir, and get the extracted path name by hashing the original path" SCREAMING_SNAKE_CASE_: Union[str, Any] =os.path.abspath(lowerCAmelCase ) return os.path.join(self.extract_dir , hash_url_to_filename(lowerCAmelCase ) ) def lowerCamelCase__ ( self : List[Any] , lowerCAmelCase : str , lowerCAmelCase : bool ) -> bool: '''simple docstring''' return force_extract or ( not os.path.isfile(lowerCAmelCase ) and not (os.path.isdir(lowerCAmelCase ) and os.listdir(lowerCAmelCase )) ) def lowerCamelCase__ ( self : List[str] , lowerCAmelCase : str , lowerCAmelCase : bool = False ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[int] =self.extractor.infer_extractor_format(lowerCAmelCase ) if not extractor_format: return input_path SCREAMING_SNAKE_CASE_: int =self._get_output_path(lowerCAmelCase ) if self._do_extract(lowerCAmelCase , lowerCAmelCase ): self.extractor.extract(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) return output_path class a ( UpperCAmelCase__ ): @classmethod @abstractmethod def lowerCamelCase__ ( cls : Any , lowerCAmelCase : Union[Path, str] , **lowerCAmelCase : List[Any] ) -> bool: '''simple docstring''' ... @staticmethod @abstractmethod def lowerCamelCase__ ( lowerCAmelCase : Union[Path, str] , lowerCAmelCase : Union[Path, str] ) -> None: '''simple docstring''' ... class a ( UpperCAmelCase__ , UpperCAmelCase__ ): UpperCamelCase : List[bytes] = [] @staticmethod def lowerCamelCase__ ( lowerCAmelCase : Union[Path, str] , lowerCAmelCase : int ) -> Dict: '''simple docstring''' with open(lowerCAmelCase , """rb""" ) as f: return f.read(lowerCAmelCase ) @classmethod def lowerCamelCase__ ( cls : Tuple , lowerCAmelCase : Union[Path, str] , lowerCAmelCase : bytes = b"" ) -> bool: '''simple docstring''' if not magic_number: SCREAMING_SNAKE_CASE_: str =max(len(lowerCAmelCase ) for cls_magic_number in cls.magic_numbers ) try: SCREAMING_SNAKE_CASE_: Any =cls.read_magic_number(lowerCAmelCase , lowerCAmelCase ) except OSError: return False return any(magic_number.startswith(lowerCAmelCase ) for cls_magic_number in cls.magic_numbers ) class a ( UpperCAmelCase__ ): @classmethod def lowerCamelCase__ ( cls : str , lowerCAmelCase : Union[Path, str] , **lowerCAmelCase : Optional[Any] ) -> bool: '''simple docstring''' return tarfile.is_tarfile(lowerCAmelCase ) @staticmethod def lowerCamelCase__ ( lowerCAmelCase : Optional[Any] , lowerCAmelCase : int ) -> Union[str, Any]: '''simple docstring''' def resolved(lowerCAmelCase : str ) -> str: return os.path.realpath(os.path.abspath(lowerCAmelCase ) ) def badpath(lowerCAmelCase : str , lowerCAmelCase : str ) -> bool: # joinpath will ignore base if path is absolute return not resolved(os.path.join(lowerCAmelCase , lowerCAmelCase ) ).startswith(lowerCAmelCase ) def badlink(lowerCAmelCase : List[Any] , lowerCAmelCase : str ) -> bool: # Links are interpreted relative to the directory containing the link SCREAMING_SNAKE_CASE_: str =resolved(os.path.join(lowerCAmelCase , os.path.dirname(info.name ) ) ) return badpath(info.linkname , base=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Dict =resolved(lowerCAmelCase ) for finfo in members: if badpath(finfo.name , lowerCAmelCase ): logger.error(f'''Extraction of {finfo.name} is blocked (illegal path)''' ) elif finfo.issym() and badlink(lowerCAmelCase , lowerCAmelCase ): logger.error(f'''Extraction of {finfo.name} is blocked: Symlink to {finfo.linkname}''' ) elif finfo.islnk() and badlink(lowerCAmelCase , lowerCAmelCase ): logger.error(f'''Extraction of {finfo.name} is blocked: Hard link to {finfo.linkname}''' ) else: yield finfo @staticmethod def lowerCamelCase__ ( lowerCAmelCase : Union[Path, str] , lowerCAmelCase : Union[Path, str] ) -> None: '''simple docstring''' os.makedirs(lowerCAmelCase , exist_ok=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =tarfile.open(lowerCAmelCase ) tar_file.extractall(lowerCAmelCase , members=TarExtractor.safemembers(lowerCAmelCase , lowerCAmelCase ) ) tar_file.close() class a ( UpperCAmelCase__ ): UpperCamelCase : str = [B'\x1F\x8B'] @staticmethod def lowerCamelCase__ ( lowerCAmelCase : Union[Path, str] , lowerCAmelCase : Union[Path, str] ) -> None: '''simple docstring''' with gzip.open(lowerCAmelCase , """rb""" ) as gzip_file: with open(lowerCAmelCase , """wb""" ) as extracted_file: shutil.copyfileobj(lowerCAmelCase , lowerCAmelCase ) class a ( UpperCAmelCase__ ): UpperCamelCase : Dict = [ B'PK\x03\x04', B'PK\x05\x06', # empty archive B'PK\x07\x08', # spanned archive ] @classmethod def lowerCamelCase__ ( cls : List[Any] , lowerCAmelCase : Union[Path, str] , lowerCAmelCase : bytes = b"" ) -> bool: '''simple docstring''' if super().is_extractable(lowerCAmelCase , magic_number=lowerCAmelCase ): return True try: # Alternative version of zipfile.is_zipfile that has less false positives, but misses executable zip archives. # From: https://github.com/python/cpython/pull/5053 from zipfile import ( _CD_SIGNATURE, _ECD_DISK_NUMBER, _ECD_DISK_START, _ECD_ENTRIES_TOTAL, _ECD_OFFSET, _ECD_SIZE, _EndRecData, sizeCentralDir, stringCentralDir, structCentralDir, ) with open(lowerCAmelCase , """rb""" ) as fp: SCREAMING_SNAKE_CASE_: int =_EndRecData(lowerCAmelCase ) if endrec: if endrec[_ECD_ENTRIES_TOTAL] == 0 and endrec[_ECD_SIZE] == 0 and endrec[_ECD_OFFSET] == 0: return True # Empty zipfiles are still zipfiles elif endrec[_ECD_DISK_NUMBER] == endrec[_ECD_DISK_START]: fp.seek(endrec[_ECD_OFFSET] ) # Central directory is on the same disk if fp.tell() == endrec[_ECD_OFFSET] and endrec[_ECD_SIZE] >= sizeCentralDir: SCREAMING_SNAKE_CASE_: List[Any] =fp.read(lowerCAmelCase ) # CD is where we expect it to be if len(lowerCAmelCase ) == sizeCentralDir: SCREAMING_SNAKE_CASE_: Tuple =struct.unpack(lowerCAmelCase , lowerCAmelCase ) # CD is the right size if centdir[_CD_SIGNATURE] == stringCentralDir: return True # First central directory entry has correct magic number return False except Exception: # catch all errors in case future python versions change the zipfile internals return False @staticmethod def lowerCamelCase__ ( lowerCAmelCase : Union[Path, str] , lowerCAmelCase : Union[Path, str] ) -> None: '''simple docstring''' os.makedirs(lowerCAmelCase , exist_ok=lowerCAmelCase ) with zipfile.ZipFile(lowerCAmelCase , """r""" ) as zip_file: zip_file.extractall(lowerCAmelCase ) zip_file.close() class a ( UpperCAmelCase__ ): UpperCamelCase : List[Any] = [B'\xFD\x37\x7A\x58\x5A\x00'] @staticmethod def lowerCamelCase__ ( lowerCAmelCase : Union[Path, str] , lowerCAmelCase : Union[Path, str] ) -> None: '''simple docstring''' with lzma.open(lowerCAmelCase ) as compressed_file: with open(lowerCAmelCase , """wb""" ) as extracted_file: shutil.copyfileobj(lowerCAmelCase , lowerCAmelCase ) class a ( UpperCAmelCase__ ): UpperCamelCase : List[str] = [B'Rar!\x1a\x07\x00', B'Rar!\x1a\x07\x01\x00'] # RAR_ID # RAR5_ID @staticmethod def lowerCamelCase__ ( lowerCAmelCase : Union[Path, str] , lowerCAmelCase : Union[Path, str] ) -> None: '''simple docstring''' if not config.RARFILE_AVAILABLE: raise ImportError("""Please pip install rarfile""" ) import rarfile os.makedirs(lowerCAmelCase , exist_ok=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Dict =rarfile.RarFile(lowerCAmelCase ) rf.extractall(lowerCAmelCase ) rf.close() class a ( UpperCAmelCase__ ): UpperCamelCase : List[str] = [B'\x28\xb5\x2F\xFD'] @staticmethod def lowerCamelCase__ ( lowerCAmelCase : Union[Path, str] , lowerCAmelCase : Union[Path, str] ) -> None: '''simple docstring''' if not config.ZSTANDARD_AVAILABLE: raise ImportError("""Please pip install zstandard""" ) import zstandard as zstd SCREAMING_SNAKE_CASE_: int =zstd.ZstdDecompressor() with open(lowerCAmelCase , """rb""" ) as ifh, open(lowerCAmelCase , """wb""" ) as ofh: dctx.copy_stream(lowerCAmelCase , lowerCAmelCase ) class a ( UpperCAmelCase__ ): UpperCamelCase : int = [B'\x42\x5A\x68'] @staticmethod def lowerCamelCase__ ( lowerCAmelCase : Union[Path, str] , lowerCAmelCase : Union[Path, str] ) -> None: '''simple docstring''' with bza.open(lowerCAmelCase , """rb""" ) as compressed_file: with open(lowerCAmelCase , """wb""" ) as extracted_file: shutil.copyfileobj(lowerCAmelCase , lowerCAmelCase ) class a ( UpperCAmelCase__ ): UpperCamelCase : int = [B'\x37\x7A\xBC\xAF\x27\x1C'] @staticmethod def lowerCamelCase__ ( lowerCAmelCase : Union[Path, str] , lowerCAmelCase : Union[Path, str] ) -> None: '''simple docstring''' if not config.PY7ZR_AVAILABLE: raise ImportError("""Please pip install py7zr""" ) import pyazr os.makedirs(lowerCAmelCase , exist_ok=lowerCAmelCase ) with pyazr.SevenZipFile(lowerCAmelCase , """r""" ) as archive: archive.extractall(lowerCAmelCase ) class a ( UpperCAmelCase__ ): UpperCamelCase : Optional[int] = [B'\x04\x22\x4D\x18'] @staticmethod def lowerCamelCase__ ( lowerCAmelCase : Union[Path, str] , lowerCAmelCase : Union[Path, str] ) -> None: '''simple docstring''' if not config.LZ4_AVAILABLE: raise ImportError("""Please pip install lz4""" ) import lza.frame with lza.frame.open(lowerCAmelCase , """rb""" ) as compressed_file: with open(lowerCAmelCase , """wb""" ) as extracted_file: shutil.copyfileobj(lowerCAmelCase , lowerCAmelCase ) class a : # Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip) UpperCamelCase : Dict[str, Type[BaseExtractor]] = { "tar": TarExtractor, "gzip": GzipExtractor, "zip": ZipExtractor, "xz": XzExtractor, "rar": RarExtractor, "zstd": ZstdExtractor, "bz2": BzipaExtractor, "7z": SevenZipExtractor, # <Added version="2.4.0"/> "lz4": LzaExtractor, # <Added version="2.4.0"/> } @classmethod def lowerCamelCase__ ( cls : List[Any] ) -> Optional[int]: '''simple docstring''' return max( len(lowerCAmelCase ) for extractor in cls.extractors.values() if issubclass(lowerCAmelCase , lowerCAmelCase ) for extractor_magic_number in extractor.magic_numbers ) @staticmethod def lowerCamelCase__ ( lowerCAmelCase : Union[Path, str] , lowerCAmelCase : int ) -> Tuple: '''simple docstring''' try: return MagicNumberBaseExtractor.read_magic_number(lowerCAmelCase , magic_number_length=lowerCAmelCase ) except OSError: return b"" @classmethod def lowerCamelCase__ ( cls : str , lowerCAmelCase : Union[Path, str] , lowerCAmelCase : bool = False ) -> bool: '''simple docstring''' warnings.warn( """Method 'is_extractable' was deprecated in version 2.4.0 and will be removed in 3.0.0. """ """Use 'infer_extractor_format' instead.""" , category=lowerCAmelCase , ) SCREAMING_SNAKE_CASE_: Union[str, Any] =cls.infer_extractor_format(lowerCAmelCase ) if extractor_format: return True if not return_extractor else (True, cls.extractors[extractor_format]) return False if not return_extractor else (False, None) @classmethod def lowerCamelCase__ ( cls : Any , lowerCAmelCase : Union[Path, str] ) -> str: # <Added version="2.4.0"/> '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =cls._get_magic_number_max_length() SCREAMING_SNAKE_CASE_: Optional[Any] =cls._read_magic_number(lowerCAmelCase , lowerCAmelCase ) for extractor_format, extractor in cls.extractors.items(): if extractor.is_extractable(lowerCAmelCase , magic_number=lowerCAmelCase ): return extractor_format @classmethod def lowerCamelCase__ ( cls : List[Any] , lowerCAmelCase : Union[Path, str] , lowerCAmelCase : Union[Path, str] , lowerCAmelCase : Optional[str] = None , lowerCAmelCase : Optional[BaseExtractor] = "deprecated" , ) -> None: '''simple docstring''' os.makedirs(os.path.dirname(lowerCAmelCase ) , exist_ok=lowerCAmelCase ) # Prevent parallel extractions SCREAMING_SNAKE_CASE_: Dict =str(Path(lowerCAmelCase ).with_suffix(""".lock""" ) ) with FileLock(lowerCAmelCase ): shutil.rmtree(lowerCAmelCase , ignore_errors=lowerCAmelCase ) if extractor_format or extractor != "deprecated": if extractor != "deprecated" or not isinstance(lowerCAmelCase , lowerCAmelCase ): # passed as positional arg warnings.warn( """Parameter 'extractor' was deprecated in version 2.4.0 and will be removed in 3.0.0. """ """Use 'extractor_format' instead.""" , category=lowerCAmelCase , ) SCREAMING_SNAKE_CASE_: Any =extractor if extractor != """deprecated""" else extractor_format else: SCREAMING_SNAKE_CASE_: Any =cls.extractors[extractor_format] return extractor.extract(lowerCAmelCase , lowerCAmelCase ) else: warnings.warn( """Parameter 'extractor_format' was made required in version 2.4.0 and not passing it will raise an """ """exception in 3.0.0.""" , category=lowerCAmelCase , ) for extractor in cls.extractors.values(): if extractor.is_extractable(lowerCAmelCase ): return extractor.extract(lowerCAmelCase , lowerCAmelCase )
36
"""simple docstring""" import string def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: List[Any] ="""""" for i in sequence: SCREAMING_SNAKE_CASE_: List[Any] =ord(lowercase ) if 65 <= extract <= 90: output += chr(155 - extract ) elif 97 <= extract <= 122: output += chr(219 - extract ) else: output += i return output def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Any =string.ascii_letters SCREAMING_SNAKE_CASE_: Tuple =string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1] return "".join( letters_reversed[letters.index(lowercase )] if c in letters else c for c in sequence ) def __magic_name__ ( ): from timeit import timeit print("""Running performance benchmarks...""" ) SCREAMING_SNAKE_CASE_: int ="""from string import printable ; from __main__ import atbash, atbash_slow""" print(f'''> atbash_slow(): {timeit("atbash_slow(printable)" , setup=lowercase )} seconds''' ) print(f'''> atbash(): {timeit("atbash(printable)" , setup=lowercase )} seconds''' ) if __name__ == "__main__": for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"): print(f"""{example} encrypted in atbash: {atbash(example)}""") benchmark()
36
1
"""simple docstring""" def __magic_name__ ( lowercase , lowercase ): SCREAMING_SNAKE_CASE_: Union[str, Any] =len(lowercase ) SCREAMING_SNAKE_CASE_: Union[str, Any] =len(lowercase ) SCREAMING_SNAKE_CASE_: List[Any] =[[False for _ in range(m + 1 )] for _ in range(n + 1 )] SCREAMING_SNAKE_CASE_: List[Any] =True for i in range(lowercase ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: SCREAMING_SNAKE_CASE_: Optional[Any] =True if a[i].islower(): SCREAMING_SNAKE_CASE_: str =True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
36
"""simple docstring""" import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class a : def __init__( self : Union[str, Any] , lowerCAmelCase : List[str]=2 , lowerCAmelCase : int=3 , lowerCAmelCase : Optional[Any]=64 , lowerCAmelCase : Union[str, Any]=None ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Union[str, Any] =np.random.default_rng(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =length SCREAMING_SNAKE_CASE_: Union[str, Any] =rng.normal(size=(length,) ).astype(np.floataa ) SCREAMING_SNAKE_CASE_: Tuple =a * self.x + b + rng.normal(scale=0.1 , size=(length,) ).astype(np.floataa ) def __len__( self : List[Any] ) -> str: '''simple docstring''' return self.length def __getitem__( self : Union[str, Any] , lowerCAmelCase : Any ) -> List[str]: '''simple docstring''' return {"x": self.x[i], "y": self.y[i]} class a ( torch.nn.Module ): def __init__( self : Optional[int] , lowerCAmelCase : str=0 , lowerCAmelCase : List[Any]=0 , lowerCAmelCase : Optional[int]=False ) -> Tuple: '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE_: int =torch.nn.Parameter(torch.tensor([2, 3] ).float() ) SCREAMING_SNAKE_CASE_: int =torch.nn.Parameter(torch.tensor([2, 3] ).float() ) SCREAMING_SNAKE_CASE_: Dict =True def lowerCamelCase__ ( self : str , lowerCAmelCase : Tuple=None ) -> int: '''simple docstring''' if self.first_batch: print(f'''Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}''' ) SCREAMING_SNAKE_CASE_: Union[str, Any] =False return x * self.a[0] + self.b[0] class a ( torch.nn.Module ): def __init__( self : Union[str, Any] , lowerCAmelCase : Any=0 , lowerCAmelCase : List[Any]=0 , lowerCAmelCase : List[Any]=False ) -> str: '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE_: List[str] =torch.nn.Parameter(torch.tensor(lowerCAmelCase ).float() ) SCREAMING_SNAKE_CASE_: Optional[int] =torch.nn.Parameter(torch.tensor(lowerCAmelCase ).float() ) SCREAMING_SNAKE_CASE_: List[Any] =True def lowerCamelCase__ ( self : List[str] , lowerCAmelCase : int=None ) -> Any: '''simple docstring''' if self.first_batch: print(f'''Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}''' ) SCREAMING_SNAKE_CASE_: Optional[int] =False return x * self.a + self.b def __magic_name__ ( lowercase , lowercase = 16 ): from datasets import load_dataset from transformers import AutoTokenizer SCREAMING_SNAKE_CASE_: Optional[Any] =AutoTokenizer.from_pretrained("""bert-base-cased""" ) SCREAMING_SNAKE_CASE_: Optional[int] ={"""train""": """tests/test_samples/MRPC/train.csv""", """validation""": """tests/test_samples/MRPC/dev.csv"""} SCREAMING_SNAKE_CASE_: Any =load_dataset("""csv""" , data_files=lowercase ) SCREAMING_SNAKE_CASE_: Any =datasets["""train"""].unique("""label""" ) SCREAMING_SNAKE_CASE_: List[Any] ={v: i for i, v in enumerate(lowercase )} def tokenize_function(lowercase ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE_: Dict =tokenizer( examples["""sentence1"""] , examples["""sentence2"""] , truncation=lowercase , max_length=lowercase , padding="""max_length""" ) if "label" in examples: SCREAMING_SNAKE_CASE_: Optional[int] =[label_to_id[l] for l in examples["""label"""]] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset SCREAMING_SNAKE_CASE_: List[Any] =datasets.map( lowercase , batched=lowercase , remove_columns=["""sentence1""", """sentence2""", """label"""] , ) def collate_fn(lowercase ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(lowercase , padding="""max_length""" , max_length=128 , return_tensors="""pt""" ) return tokenizer.pad(lowercase , padding="""longest""" , return_tensors="""pt""" ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE_: Optional[int] =DataLoader(tokenized_datasets["""train"""] , shuffle=lowercase , collate_fn=lowercase , batch_size=2 ) SCREAMING_SNAKE_CASE_: Dict =DataLoader(tokenized_datasets["""validation"""] , shuffle=lowercase , collate_fn=lowercase , batch_size=1 ) return train_dataloader, eval_dataloader
36
1
"""simple docstring""" def __magic_name__ ( lowercase = 100 ): SCREAMING_SNAKE_CASE_: Any =0 SCREAMING_SNAKE_CASE_: str =0 for i in range(1 , n + 1 ): sum_of_squares += i**2 sum_of_ints += i return sum_of_ints**2 - sum_of_squares if __name__ == "__main__": print(f"""{solution() = }""")
36
"""simple docstring""" def __magic_name__ ( lowercase ): if upper_limit < 0: raise ValueError("""Limit for the Catalan sequence must be ≥ 0""" ) SCREAMING_SNAKE_CASE_: Tuple =[0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 SCREAMING_SNAKE_CASE_: Any =1 if upper_limit > 0: SCREAMING_SNAKE_CASE_: List[str] =1 # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i for i in range(2 , upper_limit + 1 ): for j in range(lowercase ): catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1] return catalan_list if __name__ == "__main__": print("""\n********* Catalan Numbers Using Dynamic Programming ************\n""") print("""\n*** Enter -1 at any time to quit ***""") print("""\nEnter the upper limit (≥ 0) for the Catalan number sequence: """, end="""""") try: while True: _UpperCAmelCase = int(input().strip()) if N < 0: print("""\n********* Goodbye!! ************""") break else: print(f"""The Catalan numbers from 0 through {N} are:""") print(catalan_numbers(N)) print("""Try another upper limit for the sequence: """, end="""""") except (NameError, ValueError): print("""\n********* Invalid input, goodbye! ************\n""") import doctest doctest.testmod()
36
1
"""simple docstring""" import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_MAPPING, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, ) from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class a : def __init__( self : List[Any] , lowerCAmelCase : Optional[Any] , lowerCAmelCase : List[Any]=13 , lowerCAmelCase : List[Any]=30 , lowerCAmelCase : Union[str, Any]=2 , lowerCAmelCase : Union[str, Any]=3 , lowerCAmelCase : int=True , lowerCAmelCase : Union[str, Any]=True , lowerCAmelCase : Dict=32 , lowerCAmelCase : Optional[int]=5 , lowerCAmelCase : Optional[int]=4 , lowerCAmelCase : Union[str, Any]=37 , lowerCAmelCase : Union[str, Any]="gelu" , lowerCAmelCase : Union[str, Any]=0.1 , lowerCAmelCase : Optional[int]=0.1 , lowerCAmelCase : List[Any]=10 , lowerCAmelCase : Optional[Any]=0.0_2 , lowerCAmelCase : Optional[Any]=3 , lowerCAmelCase : str=None , lowerCAmelCase : List[Any]=2 , ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[int] =parent SCREAMING_SNAKE_CASE_: List[Any] =batch_size SCREAMING_SNAKE_CASE_: Optional[Any] =image_size SCREAMING_SNAKE_CASE_: List[str] =patch_size SCREAMING_SNAKE_CASE_: Optional[Any] =num_channels SCREAMING_SNAKE_CASE_: Optional[Any] =is_training SCREAMING_SNAKE_CASE_: Tuple =use_labels SCREAMING_SNAKE_CASE_: int =hidden_size SCREAMING_SNAKE_CASE_: Optional[int] =num_hidden_layers SCREAMING_SNAKE_CASE_: Dict =num_attention_heads SCREAMING_SNAKE_CASE_: Optional[int] =intermediate_size SCREAMING_SNAKE_CASE_: Optional[Any] =hidden_act SCREAMING_SNAKE_CASE_: str =hidden_dropout_prob SCREAMING_SNAKE_CASE_: Tuple =attention_probs_dropout_prob SCREAMING_SNAKE_CASE_: Dict =type_sequence_label_size SCREAMING_SNAKE_CASE_: List[str] =initializer_range SCREAMING_SNAKE_CASE_: str =scope SCREAMING_SNAKE_CASE_: Any =encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) SCREAMING_SNAKE_CASE_: Tuple =(image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE_: Any =num_patches + 2 def lowerCamelCase__ ( self : List[Any] ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: str =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_: List[Any] =None if self.use_labels: SCREAMING_SNAKE_CASE_: Optional[Any] =ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE_: Optional[int] =self.get_config() return config, pixel_values, labels def lowerCamelCase__ ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' return DeiTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=lowerCAmelCase , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def lowerCamelCase__ ( self : Tuple , lowerCAmelCase : List[Any] , lowerCAmelCase : List[str] , lowerCAmelCase : Dict ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[int] =DeiTModel(config=lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() SCREAMING_SNAKE_CASE_: Any =model(lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase__ ( self : Dict , lowerCAmelCase : Any , lowerCAmelCase : Tuple , lowerCAmelCase : Optional[Any] ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =DeiTForMaskedImageModeling(config=lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() SCREAMING_SNAKE_CASE_: Union[str, Any] =model(lowerCAmelCase ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images SCREAMING_SNAKE_CASE_: Union[str, Any] =1 SCREAMING_SNAKE_CASE_: List[Any] =DeiTForMaskedImageModeling(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() SCREAMING_SNAKE_CASE_: int =floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_: List[Any] =model(lowerCAmelCase ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def lowerCamelCase__ ( self : int , lowerCAmelCase : Optional[Any] , lowerCAmelCase : str , lowerCAmelCase : List[Any] ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[Any] =self.type_sequence_label_size SCREAMING_SNAKE_CASE_: Tuple =DeiTForImageClassification(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() SCREAMING_SNAKE_CASE_: Dict =model(lowerCAmelCase , labels=lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE_: Union[str, Any] =1 SCREAMING_SNAKE_CASE_: Optional[int] =DeiTForImageClassification(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() SCREAMING_SNAKE_CASE_: Dict =floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_: Tuple =model(lowerCAmelCase , labels=lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def lowerCamelCase__ ( self : Dict ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[Any] =self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ): List[str] =config_and_inputs SCREAMING_SNAKE_CASE_: Union[str, Any] ={"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class a ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): UpperCamelCase : Dict = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) UpperCamelCase : List[str] = ( { 'feature-extraction': DeiTModel, 'image-classification': (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) UpperCamelCase : List[Any] = False UpperCamelCase : List[str] = False UpperCamelCase : Union[str, Any] = False def lowerCamelCase__ ( self : Any ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =DeiTModelTester(self ) SCREAMING_SNAKE_CASE_: Union[str, Any] =ConfigTester(self , config_class=lowerCAmelCase , has_text_modality=lowerCAmelCase , hidden_size=37 ) def lowerCamelCase__ ( self : Tuple ) -> List[str]: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="""DeiT does not use inputs_embeds""" ) def lowerCamelCase__ ( self : int ) -> str: '''simple docstring''' pass def lowerCamelCase__ ( self : Optional[int] ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Union[str, Any] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_: Optional[Any] =model_class(lowerCAmelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE_: Optional[int] =model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCAmelCase , nn.Linear ) ) def lowerCamelCase__ ( self : Tuple ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[str] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_: List[Any] =model_class(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: int =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE_: List[Any] =[*signature.parameters.keys()] SCREAMING_SNAKE_CASE_: Tuple =["""pixel_values"""] self.assertListEqual(arg_names[:1] , lowerCAmelCase ) def lowerCamelCase__ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase ) def lowerCamelCase__ ( self : Dict ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*lowerCAmelCase ) def lowerCamelCase__ ( self : int ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase ) def lowerCamelCase__ ( self : Optional[int] , lowerCAmelCase : Any , lowerCAmelCase : Any , lowerCAmelCase : Dict=False ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE_: Union[str, Any] =super()._prepare_for_class(lowerCAmelCase , lowerCAmelCase , return_labels=lowerCAmelCase ) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def lowerCamelCase__ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Tuple =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_: List[Any] =True for model_class in self.all_model_classes: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(lowerCAmelCase ) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE_: List[Any] =model_class(lowerCAmelCase ) model.to(lowerCAmelCase ) model.train() SCREAMING_SNAKE_CASE_: Union[str, Any] =self._prepare_for_class(lowerCAmelCase , lowerCAmelCase , return_labels=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Union[str, Any] =model(**lowerCAmelCase ).loss loss.backward() def lowerCamelCase__ ( self : Tuple ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[int] =self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE_: List[str] =False SCREAMING_SNAKE_CASE_: int =True for model_class in self.all_model_classes: if model_class in get_values(lowerCAmelCase ) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE_: Tuple =model_class(lowerCAmelCase ) model.gradient_checkpointing_enable() model.to(lowerCAmelCase ) model.train() SCREAMING_SNAKE_CASE_: List[Any] =self._prepare_for_class(lowerCAmelCase , lowerCAmelCase , return_labels=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: str =model(**lowerCAmelCase ).loss loss.backward() def lowerCamelCase__ ( self : Union[str, Any] ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Tuple =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_: Any =[ {"""title""": """multi_label_classification""", """num_labels""": 2, """dtype""": torch.float}, {"""title""": """single_label_classification""", """num_labels""": 1, """dtype""": torch.long}, {"""title""": """regression""", """num_labels""": 1, """dtype""": torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(lowerCAmelCase ), *get_values(lowerCAmelCase ), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=f'''Testing {model_class} with {problem_type["title"]}''' ): SCREAMING_SNAKE_CASE_: Dict =problem_type["""title"""] SCREAMING_SNAKE_CASE_: Any =problem_type["""num_labels"""] SCREAMING_SNAKE_CASE_: Any =model_class(lowerCAmelCase ) model.to(lowerCAmelCase ) model.train() SCREAMING_SNAKE_CASE_: Optional[int] =self._prepare_for_class(lowerCAmelCase , lowerCAmelCase , return_labels=lowerCAmelCase ) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE_: Optional[int] =inputs["""labels"""].unsqueeze(1 ).repeat(1 , problem_type["""num_labels"""] ) SCREAMING_SNAKE_CASE_: Optional[Any] =inputs["""labels"""].to(problem_type["""dtype"""] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=lowerCAmelCase ) as warning_list: SCREAMING_SNAKE_CASE_: Dict =model(**lowerCAmelCase ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( f'''Something is going wrong in the regression problem: intercepted {w.message}''' ) loss.backward() @slow def lowerCamelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_: str =DeiTModel.from_pretrained(lowerCAmelCase ) self.assertIsNotNone(lowerCAmelCase ) def __magic_name__ ( ): SCREAMING_SNAKE_CASE_: Optional[int] =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class a ( unittest.TestCase ): @cached_property def lowerCamelCase__ ( self : Any ) -> List[str]: '''simple docstring''' return ( DeiTImageProcessor.from_pretrained("""facebook/deit-base-distilled-patch16-224""" ) if is_vision_available() else None ) @slow def lowerCamelCase__ ( self : int ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =DeiTForImageClassificationWithTeacher.from_pretrained("""facebook/deit-base-distilled-patch16-224""" ).to( lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =self.default_image_processor SCREAMING_SNAKE_CASE_: Optional[int] =prepare_img() SCREAMING_SNAKE_CASE_: int =image_processor(images=lowerCAmelCase , return_tensors="""pt""" ).to(lowerCAmelCase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_: Any =model(**lowerCAmelCase ) # verify the logits SCREAMING_SNAKE_CASE_: List[str] =torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: int =torch.tensor([-1.0_2_6_6, 0.1_9_1_2, -1.2_8_6_1] ).to(lowerCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCAmelCase , atol=1E-4 ) ) @slow @require_accelerate @require_torch_gpu def lowerCamelCase__ ( self : int ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: str =DeiTModel.from_pretrained( """facebook/deit-base-distilled-patch16-224""" , torch_dtype=torch.floataa , device_map="""auto""" ) SCREAMING_SNAKE_CASE_: Tuple =self.default_image_processor SCREAMING_SNAKE_CASE_: Optional[Any] =prepare_img() SCREAMING_SNAKE_CASE_: List[Any] =image_processor(images=lowerCAmelCase , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE_: Optional[Any] =inputs.pixel_values.to(lowerCAmelCase ) # forward pass to make sure inference works in fp16 with torch.no_grad(): SCREAMING_SNAKE_CASE_: Optional[Any] =model(lowerCAmelCase )
36
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig _UpperCAmelCase = { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/config.json""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/config.json""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/config.json""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/config.json""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/config.json""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/config.json""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json""", } class a ( UpperCAmelCase__ ): UpperCamelCase : Any = 'albert' def __init__( self : Dict , lowerCAmelCase : List[str]=3_0000 , lowerCAmelCase : List[Any]=128 , lowerCAmelCase : List[str]=4096 , lowerCAmelCase : str=12 , lowerCAmelCase : str=1 , lowerCAmelCase : Tuple=64 , lowerCAmelCase : Dict=1_6384 , lowerCAmelCase : int=1 , lowerCAmelCase : str="gelu_new" , lowerCAmelCase : Dict=0 , lowerCAmelCase : Optional[Any]=0 , lowerCAmelCase : str=512 , lowerCAmelCase : Optional[int]=2 , lowerCAmelCase : List[Any]=0.0_2 , lowerCAmelCase : Union[str, Any]=1E-12 , lowerCAmelCase : Tuple=0.1 , lowerCAmelCase : List[Any]="absolute" , lowerCAmelCase : List[Any]=0 , lowerCAmelCase : int=2 , lowerCAmelCase : Optional[int]=3 , **lowerCAmelCase : int , ) -> Tuple: '''simple docstring''' super().__init__(pad_token_id=lowerCAmelCase , bos_token_id=lowerCAmelCase , eos_token_id=lowerCAmelCase , **lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =vocab_size SCREAMING_SNAKE_CASE_: Optional[int] =embedding_size SCREAMING_SNAKE_CASE_: Optional[int] =hidden_size SCREAMING_SNAKE_CASE_: Tuple =num_hidden_layers SCREAMING_SNAKE_CASE_: Any =num_hidden_groups SCREAMING_SNAKE_CASE_: List[Any] =num_attention_heads SCREAMING_SNAKE_CASE_: List[Any] =inner_group_num SCREAMING_SNAKE_CASE_: Optional[int] =hidden_act SCREAMING_SNAKE_CASE_: int =intermediate_size SCREAMING_SNAKE_CASE_: Any =hidden_dropout_prob SCREAMING_SNAKE_CASE_: Union[str, Any] =attention_probs_dropout_prob SCREAMING_SNAKE_CASE_: int =max_position_embeddings SCREAMING_SNAKE_CASE_: Any =type_vocab_size SCREAMING_SNAKE_CASE_: int =initializer_range SCREAMING_SNAKE_CASE_: List[Any] =layer_norm_eps SCREAMING_SNAKE_CASE_: Dict =classifier_dropout_prob SCREAMING_SNAKE_CASE_: int =position_embedding_type class a ( UpperCAmelCase__ ): @property def lowerCamelCase__ ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": SCREAMING_SNAKE_CASE_: str ={0: """batch""", 1: """choice""", 2: """sequence"""} else: SCREAMING_SNAKE_CASE_: Dict ={0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
36
1
"""simple docstring""" 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 _UpperCAmelCase = logging.getLogger(__name__) torch.set_grad_enabled(False) _UpperCAmelCase = """cuda""" if torch.cuda.is_available() else """cpu""" def __magic_name__ ( lowercase , lowercase=100 , lowercase=" " ): SCREAMING_SNAKE_CASE_: Optional[int] =text.split(lowercase ) return [character.join(text[i : i + n] ).strip() for i in range(0 , len(lowercase ) , lowercase )] def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: int =[], [] for title, text in zip(documents["""title"""] , documents["""text"""] ): if text is not None: for passage in split_text(lowercase ): titles.append(title if title is not None else """""" ) texts.append(lowercase ) return {"title": titles, "text": texts} def __magic_name__ ( lowercase , lowercase , lowercase ): SCREAMING_SNAKE_CASE_: Dict =ctx_tokenizer( documents["""title"""] , documents["""text"""] , truncation=lowercase , padding="""longest""" , return_tensors="""pt""" )["""input_ids"""] SCREAMING_SNAKE_CASE_: List[Any] =ctx_encoder(input_ids.to(device=lowercase ) , return_dict=lowercase ).pooler_output return {"embeddings": embeddings.detach().cpu().numpy()} def __magic_name__ ( lowercase , lowercase , lowercase , ): ###################################### 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 SCREAMING_SNAKE_CASE_: Optional[Any] =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 SCREAMING_SNAKE_CASE_: str =dataset.map(lowercase , batched=lowercase , num_proc=processing_args.num_proc ) # And compute the embeddings SCREAMING_SNAKE_CASE_: Dict =DPRContextEncoder.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ).to(device=lowercase ) SCREAMING_SNAKE_CASE_: str =DPRContextEncoderTokenizerFast.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ) SCREAMING_SNAKE_CASE_: Dict =Features( {"""text""": Value("""string""" ), """title""": Value("""string""" ), """embeddings""": Sequence(Value("""float32""" ) )} ) # optional, save as float32 instead of float64 to save space SCREAMING_SNAKE_CASE_: Optional[Any] =dataset.map( partial(lowercase , ctx_encoder=lowercase , ctx_tokenizer=lowercase ) , batched=lowercase , batch_size=processing_args.batch_size , features=lowercase , ) # And finally save your dataset SCREAMING_SNAKE_CASE_: str =os.path.join(rag_example_args.output_dir , """my_knowledge_dataset""" ) dataset.save_to_disk(lowercase ) # 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 SCREAMING_SNAKE_CASE_: int =faiss.IndexHNSWFlat(index_hnsw_args.d , index_hnsw_args.m , faiss.METRIC_INNER_PRODUCT ) dataset.add_faiss_index("""embeddings""" , custom_index=lowercase ) # And save the index SCREAMING_SNAKE_CASE_: List[Any] =os.path.join(rag_example_args.output_dir , """my_knowledge_dataset_hnsw_index.faiss""" ) dataset.get_index("""embeddings""" ).save(lowercase ) # dataset.load_faiss_index("embeddings", index_path) # to reload the index @dataclass class a : UpperCamelCase : str = field( default=str(Path(UpperCAmelCase__ ).parent / 'test_run' / 'dummy-kb' / 'my_knowledge_dataset.csv' ) , metadata={'help': 'Path to a tab-separated csv file with columns \'title\' and \'text\''} , ) UpperCamelCase : Optional[str] = field( default=UpperCAmelCase__ , metadata={'help': 'Question that is passed as input to RAG. Default is \'What does Moses\' rod turn into ?\'.'} , ) UpperCamelCase : str = field( default='facebook/rag-sequence-nq' , metadata={'help': 'The RAG model to use. Either \'facebook/rag-sequence-nq\' or \'facebook/rag-token-nq\''} , ) UpperCamelCase : 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\'' ) } , ) UpperCamelCase : Optional[str] = field( default=str(Path(UpperCAmelCase__ ).parent / 'test_run' / 'dummy-kb' ) , metadata={'help': 'Path to a directory where the dataset passages and the index will be saved'} , ) @dataclass class a : UpperCamelCase : Optional[int] = field( default=UpperCAmelCase__ , metadata={ 'help': 'The number of processes to use to split the documents into passages. Default is single process.' } , ) UpperCamelCase : int = field( default=1_6 , metadata={ 'help': 'The batch size to use when computing the passages embeddings using the DPR context encoder.' } , ) @dataclass class a : UpperCamelCase : int = field( default=7_6_8 , metadata={'help': 'The dimension of the embeddings to pass to the HNSW Faiss index.'} , ) UpperCamelCase : int = field( default=1_2_8 , 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) _UpperCAmelCase = HfArgumentParser((RagExampleArguments, ProcessingArguments, IndexHnswArguments)) _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase = parser.parse_args_into_dataclasses() with TemporaryDirectory() as tmp_dir: _UpperCAmelCase = rag_example_args.output_dir or tmp_dir main(rag_example_args, processing_args, index_hnsw_args)
36
"""simple docstring""" from collections import Counter from pathlib import Path from typing import Optional, Tuple import yaml class a ( yaml.SafeLoader ): def lowerCamelCase__ ( self : int , lowerCAmelCase : List[str] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =[self.constructed_objects[key_node] for key_node, _ in node.value] SCREAMING_SNAKE_CASE_: Any =[tuple(lowerCAmelCase ) if isinstance(lowerCAmelCase , lowerCAmelCase ) else key for key in keys] SCREAMING_SNAKE_CASE_: Dict =Counter(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =[key for key in counter if counter[key] > 1] if duplicate_keys: raise TypeError(f'''Got duplicate yaml keys: {duplicate_keys}''' ) def lowerCamelCase__ ( self : Tuple , lowerCAmelCase : str , lowerCAmelCase : Optional[int]=False ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =super().construct_mapping(lowerCAmelCase , deep=lowerCAmelCase ) self._check_no_duplicates_on_constructed_node(lowerCAmelCase ) return mapping def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Dict =list(readme_content.splitlines() ) if full_content and full_content[0] == "---" and "---" in full_content[1:]: SCREAMING_SNAKE_CASE_: Union[str, Any] =full_content[1:].index("""---""" ) + 1 SCREAMING_SNAKE_CASE_: List[str] ="""\n""".join(full_content[1:sep_idx] ) return yamlblock, "\n".join(full_content[sep_idx + 1 :] ) return None, "\n".join(lowercase ) class a ( UpperCAmelCase__ ): # class attributes UpperCamelCase : Tuple = {'train_eval_index'} # train-eval-index in the YAML metadata @classmethod def lowerCamelCase__ ( cls : List[Any] , lowerCAmelCase : Path ) -> "DatasetMetadata": '''simple docstring''' with open(lowerCAmelCase , encoding="""utf-8""" ) as readme_file: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Union[str, Any] =_split_yaml_from_readme(readme_file.read() ) if yaml_string is not None: return cls.from_yaml_string(lowerCAmelCase ) else: return cls() def lowerCamelCase__ ( self : Any , lowerCAmelCase : Path ) -> List[str]: '''simple docstring''' if path.exists(): with open(lowerCAmelCase , encoding="""utf-8""" ) as readme_file: SCREAMING_SNAKE_CASE_: str =readme_file.read() else: SCREAMING_SNAKE_CASE_: str =None SCREAMING_SNAKE_CASE_: Tuple =self._to_readme(lowerCAmelCase ) with open(lowerCAmelCase , """w""" , encoding="""utf-8""" ) as readme_file: readme_file.write(lowerCAmelCase ) def lowerCamelCase__ ( self : Optional[Any] , lowerCAmelCase : Optional[str] = None ) -> str: '''simple docstring''' if readme_content is not None: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[str] =_split_yaml_from_readme(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] ="""---\n""" + self.to_yaml_string() + """---\n""" + content else: SCREAMING_SNAKE_CASE_: List[Any] ="""---\n""" + self.to_yaml_string() + """---\n""" return full_content @classmethod def lowerCamelCase__ ( cls : Optional[int] , lowerCAmelCase : str ) -> "DatasetMetadata": '''simple docstring''' SCREAMING_SNAKE_CASE_: int =yaml.load(lowerCAmelCase , Loader=_NoDuplicateSafeLoader ) or {} # Convert the YAML keys to DatasetMetadata fields SCREAMING_SNAKE_CASE_: List[Any] ={ (key.replace("""-""" , """_""" ) if key.replace("""-""" , """_""" ) in cls._FIELDS_WITH_DASHES else key): value for key, value in metadata_dict.items() } return cls(**lowerCAmelCase ) def lowerCamelCase__ ( self : Dict ) -> str: '''simple docstring''' return yaml.safe_dump( { (key.replace("""_""" , """-""" ) if key in self._FIELDS_WITH_DASHES else key): value for key, value in self.items() } , sort_keys=lowerCAmelCase , allow_unicode=lowerCAmelCase , encoding="""utf-8""" , ).decode("""utf-8""" ) _UpperCAmelCase = { """image-classification""": [], """translation""": [], """image-segmentation""": [], """fill-mask""": [], """automatic-speech-recognition""": [], """token-classification""": [], """sentence-similarity""": [], """audio-classification""": [], """question-answering""": [], """summarization""": [], """zero-shot-classification""": [], """table-to-text""": [], """feature-extraction""": [], """other""": [], """multiple-choice""": [], """text-classification""": [], """text-to-image""": [], """text2text-generation""": [], """zero-shot-image-classification""": [], """tabular-classification""": [], """tabular-regression""": [], """image-to-image""": [], """tabular-to-text""": [], """unconditional-image-generation""": [], """text-retrieval""": [], """text-to-speech""": [], """object-detection""": [], """audio-to-audio""": [], """text-generation""": [], """conversational""": [], """table-question-answering""": [], """visual-question-answering""": [], """image-to-text""": [], """reinforcement-learning""": [], """voice-activity-detection""": [], """time-series-forecasting""": [], """document-question-answering""": [], } if __name__ == "__main__": from argparse import ArgumentParser _UpperCAmelCase = ArgumentParser(usage="""Validate the yaml metadata block of a README.md file.""") ap.add_argument("""readme_filepath""") _UpperCAmelCase = ap.parse_args() _UpperCAmelCase = Path(args.readme_filepath) _UpperCAmelCase = DatasetMetadata.from_readme(readme_filepath) print(dataset_metadata) dataset_metadata.to_readme(readme_filepath)
36
1
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL _UpperCAmelCase = logging.get_logger(__name__) class a ( UpperCAmelCase__ ): UpperCamelCase : Tuple = ['pixel_values'] def __init__( self : str , lowerCAmelCase : bool = True , lowerCAmelCase : Dict[str, int] = None , lowerCAmelCase : PILImageResampling = PIL.Image.BICUBIC , lowerCAmelCase : bool = True , lowerCAmelCase : Dict[str, int] = None , lowerCAmelCase : Union[int, float] = 1 / 255 , lowerCAmelCase : bool = True , lowerCAmelCase : bool = True , lowerCAmelCase : Optional[Union[float, List[float]]] = None , lowerCAmelCase : Optional[Union[float, List[float]]] = None , **lowerCAmelCase : Optional[int] , ) -> None: '''simple docstring''' super().__init__(**lowerCAmelCase ) SCREAMING_SNAKE_CASE_: str =size if size is not None else {"""height""": 256, """width""": 256} SCREAMING_SNAKE_CASE_: Union[str, Any] =get_size_dict(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[Any] =crop_size if crop_size is not None else {"""height""": 224, """width""": 224} SCREAMING_SNAKE_CASE_: Union[str, Any] =get_size_dict(lowerCAmelCase , param_name="""crop_size""" ) SCREAMING_SNAKE_CASE_: List[str] =do_resize SCREAMING_SNAKE_CASE_: List[str] =size SCREAMING_SNAKE_CASE_: Optional[int] =resample SCREAMING_SNAKE_CASE_: Any =do_center_crop SCREAMING_SNAKE_CASE_: Optional[Any] =crop_size SCREAMING_SNAKE_CASE_: Any =do_rescale SCREAMING_SNAKE_CASE_: Union[str, Any] =rescale_factor SCREAMING_SNAKE_CASE_: List[str] =do_normalize SCREAMING_SNAKE_CASE_: Tuple =image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE_: Union[str, Any] =image_std if image_std is not None else IMAGENET_STANDARD_STD def lowerCamelCase__ ( self : List[str] , lowerCAmelCase : np.ndarray , lowerCAmelCase : Dict[str, int] , lowerCAmelCase : PILImageResampling = PIL.Image.BICUBIC , lowerCAmelCase : Optional[Union[str, ChannelDimension]] = None , **lowerCAmelCase : Tuple , ) -> np.ndarray: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =get_size_dict(lowerCAmelCase ) if "height" not in size or "width" not in size: raise ValueError(f'''The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}''' ) return resize( lowerCAmelCase , size=(size["""height"""], size["""width"""]) , resample=lowerCAmelCase , data_format=lowerCAmelCase , **lowerCAmelCase ) def lowerCamelCase__ ( self : Optional[Any] , lowerCAmelCase : np.ndarray , lowerCAmelCase : Dict[str, int] , lowerCAmelCase : Optional[Union[str, ChannelDimension]] = None , **lowerCAmelCase : Tuple , ) -> np.ndarray: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[Any] =get_size_dict(lowerCAmelCase ) if "height" not in size or "width" not in size: raise ValueError(f'''The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}''' ) return center_crop(lowerCAmelCase , size=(size["""height"""], size["""width"""]) , data_format=lowerCAmelCase , **lowerCAmelCase ) def lowerCamelCase__ ( self : Dict , lowerCAmelCase : np.ndarray , lowerCAmelCase : Union[int, float] , lowerCAmelCase : Optional[Union[str, ChannelDimension]] = None , **lowerCAmelCase : Tuple , ) -> Tuple: '''simple docstring''' return rescale(lowerCAmelCase , scale=lowerCAmelCase , data_format=lowerCAmelCase , **lowerCAmelCase ) def lowerCamelCase__ ( self : List[Any] , lowerCAmelCase : np.ndarray , lowerCAmelCase : Union[float, List[float]] , lowerCAmelCase : Union[float, List[float]] , lowerCAmelCase : Optional[Union[str, ChannelDimension]] = None , **lowerCAmelCase : Tuple , ) -> np.ndarray: '''simple docstring''' return normalize(lowerCAmelCase , mean=lowerCAmelCase , std=lowerCAmelCase , data_format=lowerCAmelCase , **lowerCAmelCase ) def lowerCamelCase__ ( self : Dict , lowerCAmelCase : ImageInput , lowerCAmelCase : bool = None , lowerCAmelCase : Dict[str, int] = None , lowerCAmelCase : Optional[int]=None , lowerCAmelCase : bool = None , lowerCAmelCase : Dict[str, int] = None , lowerCAmelCase : bool = None , lowerCAmelCase : float = None , lowerCAmelCase : bool = None , lowerCAmelCase : Optional[Union[float, List[float]]] = None , lowerCAmelCase : Optional[Union[float, List[float]]] = None , lowerCAmelCase : Optional[Union[str, TensorType]] = None , lowerCAmelCase : ChannelDimension = ChannelDimension.FIRST , **lowerCAmelCase : int , ) -> PIL.Image.Image: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE_: Optional[Any] =resample if resample is not None else self.resample SCREAMING_SNAKE_CASE_: Optional[int] =do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE_: Dict =do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE_: List[Any] =rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE_: Dict =do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE_: Optional[Any] =image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE_: Union[str, Any] =image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE_: Union[str, Any] =size if size is not None else self.size SCREAMING_SNAKE_CASE_: List[str] =get_size_dict(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE_: List[Any] =get_size_dict(lowerCAmelCase , param_name="""crop_size""" ) SCREAMING_SNAKE_CASE_: int =make_list_of_images(lowerCAmelCase ) if not valid_images(lowerCAmelCase ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE_: Optional[Any] =[to_numpy_array(lowerCAmelCase ) for image in images] if do_resize: SCREAMING_SNAKE_CASE_: List[str] =[self.resize(image=lowerCAmelCase , size=lowerCAmelCase , resample=lowerCAmelCase ) for image in images] if do_center_crop: SCREAMING_SNAKE_CASE_: Optional[Any] =[self.center_crop(image=lowerCAmelCase , size=lowerCAmelCase ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE_: Tuple =[self.rescale(image=lowerCAmelCase , scale=lowerCAmelCase ) for image in images] if do_normalize: SCREAMING_SNAKE_CASE_: str =[self.normalize(image=lowerCAmelCase , mean=lowerCAmelCase , std=lowerCAmelCase ) for image in images] SCREAMING_SNAKE_CASE_: List[str] =[to_channel_dimension_format(lowerCAmelCase , lowerCAmelCase ) for image in images] SCREAMING_SNAKE_CASE_: List[Any] ={"""pixel_values""": images} return BatchFeature(data=lowerCAmelCase , tensor_type=lowerCAmelCase )
36
"""simple docstring""" import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from xgboost import XGBClassifier def __magic_name__ ( lowercase ): return (data["data"], data["target"]) def __magic_name__ ( lowercase , lowercase ): SCREAMING_SNAKE_CASE_: Dict =XGBClassifier() classifier.fit(lowercase , lowercase ) return classifier def __magic_name__ ( ): SCREAMING_SNAKE_CASE_: Optional[Any] =load_iris() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Tuple =data_handling(lowercase ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[Any] =train_test_split( lowercase , lowercase , test_size=0.25 ) SCREAMING_SNAKE_CASE_: Tuple =iris["""target_names"""] # Create an XGBoost Classifier from the training data SCREAMING_SNAKE_CASE_: Optional[int] =xgboost(lowercase , lowercase ) # Display the confusion matrix of the classifier with both training and test sets ConfusionMatrixDisplay.from_estimator( lowercase , lowercase , lowercase , display_labels=lowercase , cmap="""Blues""" , normalize="""true""" , ) plt.title("""Normalized Confusion Matrix - IRIS Dataset""" ) plt.show() if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
36
1
"""simple docstring""" import string def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: List[Any] ="""""" for i in sequence: SCREAMING_SNAKE_CASE_: List[Any] =ord(lowercase ) if 65 <= extract <= 90: output += chr(155 - extract ) elif 97 <= extract <= 122: output += chr(219 - extract ) else: output += i return output def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Any =string.ascii_letters SCREAMING_SNAKE_CASE_: Tuple =string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1] return "".join( letters_reversed[letters.index(lowercase )] if c in letters else c for c in sequence ) def __magic_name__ ( ): from timeit import timeit print("""Running performance benchmarks...""" ) SCREAMING_SNAKE_CASE_: int ="""from string import printable ; from __main__ import atbash, atbash_slow""" print(f'''> atbash_slow(): {timeit("atbash_slow(printable)" , setup=lowercase )} seconds''' ) print(f'''> atbash(): {timeit("atbash(printable)" , setup=lowercase )} seconds''' ) if __name__ == "__main__": for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"): print(f"""{example} encrypted in atbash: {atbash(example)}""") benchmark()
36
"""simple docstring""" from typing import Dict import numpy as np import torch from . import residue_constants as rc from .tensor_utils import tensor_tree_map, tree_map def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Optional[Any] =[] SCREAMING_SNAKE_CASE_: List[str] =[] SCREAMING_SNAKE_CASE_: Any =[] for rt in rc.restypes: SCREAMING_SNAKE_CASE_: Optional[int] =rc.restype_name_to_atomaa_names[rc.restype_atoa[rt]] restype_atomaa_to_atomaa_list.append([(rc.atom_order[name] if name else 0) for name in atom_names] ) SCREAMING_SNAKE_CASE_: Any ={name: i for i, name in enumerate(lowercase )} restype_atomaa_to_atomaa_list.append( [(atom_name_to_idxaa[name] if name in atom_name_to_idxaa else 0) for name in rc.atom_types] ) restype_atomaa_mask_list.append([(1.0 if name else 0.0) for name in atom_names] ) # Add dummy mapping for restype 'UNK' restype_atomaa_to_atomaa_list.append([0] * 14 ) restype_atomaa_to_atomaa_list.append([0] * 37 ) restype_atomaa_mask_list.append([0.0] * 14 ) SCREAMING_SNAKE_CASE_: Union[str, Any] =torch.tensor( lowercase , dtype=torch.intaa , device=protein["""aatype"""].device , ) SCREAMING_SNAKE_CASE_: Optional[Any] =torch.tensor( lowercase , dtype=torch.intaa , device=protein["""aatype"""].device , ) SCREAMING_SNAKE_CASE_: List[str] =torch.tensor( lowercase , dtype=torch.floataa , device=protein["""aatype"""].device , ) SCREAMING_SNAKE_CASE_: Optional[Any] =protein["""aatype"""].to(torch.long ) # create the mapping for (residx, atom14) --> atom37, i.e. an array # with shape (num_res, 14) containing the atom37 indices for this protein SCREAMING_SNAKE_CASE_: List[str] =restype_atomaa_to_atomaa[protein_aatype] SCREAMING_SNAKE_CASE_: Any =restype_atomaa_mask[protein_aatype] SCREAMING_SNAKE_CASE_: Tuple =residx_atomaa_mask SCREAMING_SNAKE_CASE_: Dict =residx_atomaa_to_atomaa.long() # create the gather indices for mapping back SCREAMING_SNAKE_CASE_: Dict =restype_atomaa_to_atomaa[protein_aatype] SCREAMING_SNAKE_CASE_: Optional[int] =residx_atomaa_to_atomaa.long() # create the corresponding mask SCREAMING_SNAKE_CASE_: Optional[int] =torch.zeros([21, 37] , dtype=torch.floataa , device=protein["""aatype"""].device ) for restype, restype_letter in enumerate(rc.restypes ): SCREAMING_SNAKE_CASE_: int =rc.restype_atoa[restype_letter] SCREAMING_SNAKE_CASE_: Any =rc.residue_atoms[restype_name] for atom_name in atom_names: SCREAMING_SNAKE_CASE_: Optional[int] =rc.atom_order[atom_name] SCREAMING_SNAKE_CASE_: Dict =1 SCREAMING_SNAKE_CASE_: List[str] =restype_atomaa_mask[protein_aatype] SCREAMING_SNAKE_CASE_: List[Any] =residx_atomaa_mask return protein def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Any =tree_map(lambda lowercase : torch.tensor(lowercase , device=batch["""aatype"""].device ) , lowercase , np.ndarray ) SCREAMING_SNAKE_CASE_: int =tensor_tree_map(lambda lowercase : np.array(lowercase ) , make_atomaa_masks(lowercase ) ) return out
36
1
"""simple docstring""" from math import pi, sqrt def __magic_name__ ( lowercase ): if num <= 0: raise ValueError("""math domain error""" ) if num > 171.5: raise OverflowError("""math range error""" ) elif num - int(lowercase ) not in (0, 0.5): raise NotImplementedError("""num must be an integer or a half-integer""" ) elif num == 0.5: return sqrt(lowercase ) else: return 1.0 if num == 1 else (num - 1) * gamma(num - 1 ) def __magic_name__ ( ): assert gamma(0.5 ) == sqrt(lowercase ) assert gamma(1 ) == 1.0 assert gamma(2 ) == 1.0 if __name__ == "__main__": from doctest import testmod testmod() _UpperCAmelCase = 1.0 while num: _UpperCAmelCase = float(input("""Gamma of: """)) print(f"""gamma({num}) = {gamma(num)}""") print("""\nEnter 0 to exit...""")
36
"""simple docstring""" from pathlib import Path from typing import List from transformers import is_torch_available, is_vision_available from transformers.testing_utils import get_tests_dir, is_tool_test from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText if is_torch_available(): import torch if is_vision_available(): from PIL import Image _UpperCAmelCase = ["""text""", """image""", """audio"""] def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: str =[] for input_type in input_types: if input_type == "text": inputs.append("""Text input""" ) elif input_type == "image": inputs.append( Image.open(Path(get_tests_dir("""fixtures/tests_samples/COCO""" ) ) / """000000039769.png""" ).resize((512, 512) ) ) elif input_type == "audio": inputs.append(torch.ones(3000 ) ) elif isinstance(lowercase , lowercase ): inputs.append(create_inputs(lowercase ) ) else: raise ValueError(f'''Invalid type requested: {input_type}''' ) return inputs def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: int =[] for output in outputs: if isinstance(lowercase , (str, AgentText) ): output_types.append("""text""" ) elif isinstance(lowercase , (Image.Image, AgentImage) ): output_types.append("""image""" ) elif isinstance(lowercase , (torch.Tensor, AgentAudio) ): output_types.append("""audio""" ) else: raise ValueError(f'''Invalid output: {output}''' ) return output_types @is_tool_test class a : def lowerCamelCase__ ( self : Tuple ) -> List[Any]: '''simple docstring''' self.assertTrue(hasattr(self.tool , """inputs""" ) ) self.assertTrue(hasattr(self.tool , """outputs""" ) ) SCREAMING_SNAKE_CASE_: Optional[int] =self.tool.inputs for _input in inputs: if isinstance(_input , lowerCAmelCase ): for __input in _input: self.assertTrue(__input in authorized_types ) else: self.assertTrue(_input in authorized_types ) SCREAMING_SNAKE_CASE_: Any =self.tool.outputs for _output in outputs: self.assertTrue(_output in authorized_types ) def lowerCamelCase__ ( self : str ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =create_inputs(self.tool.inputs ) SCREAMING_SNAKE_CASE_: List[Any] =self.tool(*lowerCAmelCase ) # There is a single output if len(self.tool.outputs ) == 1: SCREAMING_SNAKE_CASE_: str =[outputs] self.assertListEqual(output_types(lowerCAmelCase ) , self.tool.outputs ) def lowerCamelCase__ ( self : str ) -> Optional[Any]: '''simple docstring''' self.assertTrue(hasattr(self.tool , """description""" ) ) self.assertTrue(hasattr(self.tool , """default_checkpoint""" ) ) self.assertTrue(self.tool.description.startswith("""This is a tool that""" ) ) def lowerCamelCase__ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: str =create_inputs(self.tool.inputs ) SCREAMING_SNAKE_CASE_: Tuple =self.tool(*lowerCAmelCase ) if not isinstance(lowerCAmelCase , lowerCAmelCase ): SCREAMING_SNAKE_CASE_: int =[outputs] self.assertEqual(len(lowerCAmelCase ) , len(self.tool.outputs ) ) for output, output_type in zip(lowerCAmelCase , self.tool.outputs ): SCREAMING_SNAKE_CASE_: int =AGENT_TYPE_MAPPING[output_type] self.assertTrue(isinstance(lowerCAmelCase , lowerCAmelCase ) ) def lowerCamelCase__ ( self : List[Any] ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =create_inputs(self.tool.inputs ) SCREAMING_SNAKE_CASE_: Union[str, Any] =[] for _input, input_type in zip(lowerCAmelCase , self.tool.inputs ): if isinstance(lowerCAmelCase , lowerCAmelCase ): _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input ) for _input_type in input_type] ) else: _inputs.append(AGENT_TYPE_MAPPING[input_type](_input ) ) # Should not raise an error SCREAMING_SNAKE_CASE_: Dict =self.tool(*lowerCAmelCase ) if not isinstance(lowerCAmelCase , lowerCAmelCase ): SCREAMING_SNAKE_CASE_: List[str] =[outputs] self.assertEqual(len(lowerCAmelCase ) , len(self.tool.outputs ) )
36
1
"""simple docstring""" from copy import deepcopy import torch import torch.nn.functional as F from torch.optim import AdamW from torch.optim.lr_scheduler import LambdaLR from torch.utils.data import DataLoader from accelerate.accelerator import Accelerator from accelerate.state import GradientState from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import DistributedType, is_torch_version, set_seed def __magic_name__ ( lowercase , lowercase , lowercase , lowercase ): for param, grad_param in zip(model_a.parameters() , model_b.parameters() ): if not param.requires_grad: continue if not did_step: # Grads should not be in sync assert ( torch.allclose(param.grad , grad_param.grad ) is False ), f'''Gradients in sync when they should not be at iteration {iteration}:\nmodel_a grad ({param.grad}) == model_b grad ({grad_param.grad})''' else: # Grads should be in sync assert ( torch.allclose(param.grad , grad_param.grad ) is True ), f'''Gradients not in sync when they should be at iteration {iteration}:\nmodel_a grad ({param.grad}) != model_b grad ({grad_param.grad})''' def __magic_name__ ( lowercase , lowercase , lowercase , lowercase , lowercase=True ): model.train() SCREAMING_SNAKE_CASE_: Any =model(lowercase ) SCREAMING_SNAKE_CASE_: int =F.mse_loss(lowercase , target.to(output.device ) ) if not do_backward: loss /= accelerator.gradient_accumulation_steps loss.backward() else: accelerator.backward(lowercase ) def __magic_name__ ( lowercase , lowercase=False ): set_seed(42 ) SCREAMING_SNAKE_CASE_: int =RegressionModel() SCREAMING_SNAKE_CASE_: List[str] =deepcopy(lowercase ) SCREAMING_SNAKE_CASE_: List[str] =RegressionDataset(length=80 ) SCREAMING_SNAKE_CASE_: Optional[int] =DataLoader(lowercase , batch_size=16 ) model.to(accelerator.device ) if sched: SCREAMING_SNAKE_CASE_: Dict =AdamW(params=model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE_: Dict =AdamW(params=ddp_model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE_: int =LambdaLR(lowercase , lr_lambda=lambda lowercase : epoch**0.65 ) SCREAMING_SNAKE_CASE_: Optional[int] =LambdaLR(lowercase , lr_lambda=lambda lowercase : epoch**0.65 ) # Make a copy of `model` if sched: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[int] =accelerator.prepare(lowercase , lowercase , lowercase , lowercase ) else: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Dict =accelerator.prepare(lowercase , lowercase ) if sched: return (model, opt, sched, dataloader, ddp_model, ddp_opt, ddp_sched) return model, ddp_model, dataloader def __magic_name__ ( lowercase ): # Test when on a single CPU or GPU that the context manager does nothing SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[Any] =get_training_setup(lowercase ) # Use a single batch SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Dict =next(iter(lowercase ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[int] =accelerator.gather((ddp_input, ddp_target) ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Dict =input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(lowercase , lowercase , lowercase , lowercase ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(lowercase ): step_model(lowercase , lowercase , lowercase , lowercase ) else: # Sync grads step_model(lowercase , lowercase , lowercase , lowercase ) # Since `no_sync` is a noop, `ddp_model` and `model` grads should always be in sync check_model_parameters(lowercase , lowercase , lowercase , lowercase ) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue assert torch.allclose( param.grad , ddp_param.grad ), f'''Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})''' # Shuffle ddp_input on each iteration torch.manual_seed(1337 + iteration ) SCREAMING_SNAKE_CASE_: Optional[Any] =ddp_input[torch.randperm(len(lowercase ) )] def __magic_name__ ( lowercase ): # Test on distributed setup that context manager behaves properly SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Union[str, Any] =get_training_setup(lowercase ) # Use a single batch SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Union[str, Any] =next(iter(lowercase ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Tuple =accelerator.gather((ddp_input, ddp_target) ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[Any] =input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(lowercase , lowercase , lowercase , lowercase ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(lowercase ): step_model(lowercase , lowercase , lowercase , lowercase ) else: # Sync grads step_model(lowercase , lowercase , lowercase , lowercase ) # DDP model and model should only be in sync when not (iteration % 2 == 0) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue if iteration % 2 == 0: # Grads should not be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is False ), f'''Gradients in sync when they should not be:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})''' else: # Grads should be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is True ), f'''Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})''' # Shuffle ddp_input on each iteration torch.manual_seed(1337 + iteration ) SCREAMING_SNAKE_CASE_: Optional[Any] =ddp_input[torch.randperm(len(lowercase ) )] def __magic_name__ ( lowercase=False , lowercase=False ): SCREAMING_SNAKE_CASE_: Optional[Any] =Accelerator( split_batches=lowercase , dispatch_batches=lowercase , gradient_accumulation_steps=2 ) # Test that context manager behaves properly SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: str =get_training_setup(lowercase ) for iteration, batch in enumerate(lowercase ): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[Any] =batch.values() # Gather the distributed inputs and targs for the base model SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[Any] =accelerator.gather((ddp_input, ddp_target) ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[Any] =input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(lowercase , lowercase , lowercase , lowercase , lowercase ) # Do "gradient accumulation" (noop) with accelerator.accumulate(lowercase ): step_model(lowercase , lowercase , lowercase , lowercase ) # DDP model and model should only be in sync when not (iteration % 2 == 0) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue if ((iteration + 1) % 2 == 0) or (iteration == len(lowercase ) - 1): # Grads should be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is True ), f'''Gradients not in sync when they should be at iteration {iteration}:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})''' else: # Grads should not be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is False ), f'''Gradients in sync when they should not be at iteration {iteration}:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})''' # Shuffle ddp_input on each iteration torch.manual_seed(1337 + iteration ) SCREAMING_SNAKE_CASE_: int =ddp_input[torch.randperm(len(lowercase ) )] GradientState._reset_state() def __magic_name__ ( lowercase=False , lowercase=False ): SCREAMING_SNAKE_CASE_: Dict =Accelerator( split_batches=lowercase , dispatch_batches=lowercase , gradient_accumulation_steps=2 ) # Test that context manager behaves properly SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: str =get_training_setup(lowercase , lowercase ) for iteration, batch in enumerate(lowercase ): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[Any] =batch.values() # Gather the distributed inputs and targs for the base model SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: str =accelerator.gather((ddp_input, ddp_target) ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Dict =input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" model.train() ddp_model.train() step_model(lowercase , lowercase , lowercase , lowercase , lowercase ) opt.step() if ((iteration + 1) % 2 == 0) or ((iteration + 1) == len(lowercase )): if split_batches: sched.step() else: for _ in range(accelerator.num_processes ): sched.step() opt.zero_grad() # Perform gradient accumulation under wrapper with accelerator.accumulate(lowercase ): step_model(lowercase , lowercase , lowercase , lowercase ) ddp_opt.step() ddp_sched.step() ddp_opt.zero_grad() # Learning rates should be the same assert ( opt.param_groups[0]["lr"] == ddp_opt.param_groups[0]["lr"] ), f'''Learning rates found in each optimizer did not align\nopt: {opt.param_groups[0]["lr"]}\nDDP opt: {ddp_opt.param_groups[0]["lr"]}\n''' SCREAMING_SNAKE_CASE_: str =(((iteration + 1) % 2) == 0) or ((iteration + 1) == len(lowercase )) if accelerator.num_processes > 1: check_model_parameters(lowercase , lowercase , lowercase , lowercase ) # Shuffle ddp_input on each iteration torch.manual_seed(1337 + iteration ) GradientState._reset_state() def __magic_name__ ( ): SCREAMING_SNAKE_CASE_: List[Any] =Accelerator() SCREAMING_SNAKE_CASE_: Tuple =RegressionDataset(length=80 ) SCREAMING_SNAKE_CASE_: Optional[int] =DataLoader(lowercase , batch_size=16 ) SCREAMING_SNAKE_CASE_: str =RegressionDataset(length=96 ) SCREAMING_SNAKE_CASE_: Optional[Any] =DataLoader(lowercase , batch_size=16 ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[Any] =accelerator.prepare(lowercase , lowercase ) assert accelerator.gradient_state.active_dataloader is None for iteration, _ in enumerate(lowercase ): assert id(accelerator.gradient_state.active_dataloader ) == id(lowercase ) if iteration < len(lowercase ) - 1: assert not accelerator.gradient_state.end_of_dataloader if iteration == 1: for batch_num, _ in enumerate(lowercase ): assert id(accelerator.gradient_state.active_dataloader ) == id(lowercase ) if batch_num < len(lowercase ) - 1: assert not accelerator.gradient_state.end_of_dataloader else: assert accelerator.gradient_state.end_of_dataloader else: assert accelerator.gradient_state.end_of_dataloader assert accelerator.gradient_state.active_dataloader is None def __magic_name__ ( ): SCREAMING_SNAKE_CASE_: Optional[Any] =Accelerator() SCREAMING_SNAKE_CASE_: Any =accelerator.state if state.local_process_index == 0: print("""**Test `accumulate` gradient accumulation with dataloader break**""" ) test_dataloader_break() if state.distributed_type == DistributedType.NO: if state.local_process_index == 0: print("""**Test NOOP `no_sync` context manager**""" ) test_noop_sync(lowercase ) if state.distributed_type in (DistributedType.MULTI_GPU, DistributedType.MULTI_CPU): if state.local_process_index == 0: print("""**Test Distributed `no_sync` context manager**""" ) test_distributed_sync(lowercase ) if state.distributed_type == DistributedType.MULTI_GPU: for split_batch in [True, False]: for dispatch_batches in [True, False]: if state.local_process_index == 0: print( """**Test `accumulate` gradient accumulation, """ , f'''`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**''' , ) test_gradient_accumulation(lowercase , lowercase ) # Currently will break on torch 2.0 +, need to investigate why if is_torch_version("""<""" , """2.0""" ) or state.distributed_type == DistributedType.NO: if state.local_process_index == 0: print( """**Test `accumulate` gradient accumulation with optimizer and scheduler, """ , """`split_batches=False`, `dispatch_batches=False`**""" , ) test_gradient_accumulation_with_opt_and_scheduler() if state.distributed_type == DistributedType.MULTI_GPU: for split_batch in [True, False]: for dispatch_batches in [True, False]: if not split_batch and not dispatch_batches: continue if state.local_process_index == 0: print( """**Test `accumulate` gradient accumulation with optimizer and scheduler, """ , f'''`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**''' , ) test_gradient_accumulation_with_opt_and_scheduler(lowercase , lowercase ) def __magic_name__ ( lowercase ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
36
"""simple docstring""" from __future__ import annotations def __magic_name__ ( lowercase , lowercase ): SCREAMING_SNAKE_CASE_: List[Any] =sorted(numsa + numsa ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Tuple =divmod(len(lowercase ) , 2 ) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() _UpperCAmelCase = [float(x) for x in input("""Enter the elements of first array: """).split()] _UpperCAmelCase = [float(x) for x in input("""Enter the elements of second array: """).split()] print(f"""The median of two arrays is: {median_of_two_arrays(array_a, array_a)}""")
36
1
"""simple docstring""" import json import logging import math import os import sys from dataclasses import dataclass, field from typing import Optional from datasets import Dataset, load_dataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoModelForMaskedLM, AutoTokenizer, DataCollatorForWholeWordMask, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process _UpperCAmelCase = logging.getLogger(__name__) _UpperCAmelCase = list(MODEL_FOR_MASKED_LM_MAPPING.keys()) _UpperCAmelCase = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class a : UpperCamelCase : Optional[str] = field( default=UpperCAmelCase__ , metadata={ 'help': ( 'The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.' ) } , ) UpperCamelCase : Optional[str] = field( default=UpperCAmelCase__ , metadata={'help': 'If training from scratch, pass a model type from the list: ' + ', '.join(UpperCAmelCase__ )} , ) UpperCamelCase : Optional[str] = field( default=UpperCAmelCase__ , metadata={ 'help': ( 'Override some existing default config settings when a model is trained from scratch. Example: ' 'n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index' ) } , ) UpperCamelCase : Optional[str] = field( default=UpperCAmelCase__ , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) UpperCamelCase : Optional[str] = field( default=UpperCAmelCase__ , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) UpperCamelCase : Optional[str] = field( default=UpperCAmelCase__ , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) UpperCamelCase : bool = field( default=UpperCAmelCase__ , metadata={'help': 'Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'} , ) UpperCamelCase : str = field( default='main' , metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'} , ) UpperCamelCase : bool = field( default=UpperCAmelCase__ , metadata={ 'help': ( 'Will use the token generated when running `huggingface-cli login` (necessary to use this script ' 'with private models).' ) } , ) def lowerCamelCase__ ( self : List[Any] ) -> List[str]: '''simple docstring''' if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None): raise ValueError( """--config_overrides can't be used in combination with --config_name or --model_name_or_path""" ) @dataclass class a : UpperCamelCase : Optional[str] = field( default=UpperCAmelCase__ , metadata={'help': 'The name of the dataset to use (via the datasets library).'} ) UpperCamelCase : Optional[str] = field( default=UpperCAmelCase__ , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} ) UpperCamelCase : Optional[str] = field(default=UpperCAmelCase__ , metadata={'help': 'The input training data file (a text file).'} ) UpperCamelCase : Optional[str] = field( default=UpperCAmelCase__ , metadata={'help': 'An optional input evaluation data file to evaluate the perplexity on (a text file).'} , ) UpperCamelCase : Optional[str] = field( default=UpperCAmelCase__ , metadata={'help': 'An optional input train ref data file for whole word masking in Chinese.'} , ) UpperCamelCase : Optional[str] = field( default=UpperCAmelCase__ , metadata={'help': 'An optional input validation ref data file for whole word masking in Chinese.'} , ) UpperCamelCase : bool = field( default=UpperCAmelCase__ , metadata={'help': 'Overwrite the cached training and evaluation sets'} ) UpperCamelCase : Optional[int] = field( default=5 , metadata={ 'help': 'The percentage of the train set used as validation set in case there\'s no validation split' } , ) UpperCamelCase : Optional[int] = field( default=UpperCAmelCase__ , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated. Default to the max input length of the model.' ) } , ) UpperCamelCase : Optional[int] = field( default=UpperCAmelCase__ , metadata={'help': 'The number of processes to use for the preprocessing.'} , ) UpperCamelCase : float = field( default=0.15 , metadata={'help': 'Ratio of tokens to mask for masked language modeling loss'} ) UpperCamelCase : bool = field( default=UpperCAmelCase__ , metadata={ 'help': ( 'Whether to pad all samples to `max_seq_length`. ' 'If False, will pad the samples dynamically when batching to the maximum length in the batch.' ) } , ) def lowerCamelCase__ ( self : Optional[int] ) -> Optional[Any]: '''simple docstring''' if self.train_file is not None: SCREAMING_SNAKE_CASE_: Any =self.train_file.split(""".""" )[-1] assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file." if self.validation_file is not None: SCREAMING_SNAKE_CASE_: List[str] =self.validation_file.split(""".""" )[-1] assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file." def __magic_name__ ( lowercase , lowercase ): with open(lowercase , """r""" , encoding="""utf-8""" ) as f: SCREAMING_SNAKE_CASE_: int =[json.loads(lowercase ) for line in f.read().splitlines() if (len(lowercase ) > 0 and not line.isspace())] assert len(lowercase ) == len(lowercase ) SCREAMING_SNAKE_CASE_: Union[str, Any] ={c: dataset[c] for c in dataset.column_names} SCREAMING_SNAKE_CASE_: List[str] =refs return Dataset.from_dict(lowercase ) def __magic_name__ ( ): # 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. SCREAMING_SNAKE_CASE_: Any =HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(""".json""" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[Any] =parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Dict =parser.parse_args_into_dataclasses() # Detecting last checkpoint. SCREAMING_SNAKE_CASE_: Union[str, Any] =None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: SCREAMING_SNAKE_CASE_: Tuple =get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f'''Output directory ({training_args.output_dir}) already exists and is not empty. ''' """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None: logger.info( f'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ''' """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , handlers=[logging.StreamHandler(sys.stdout )] , ) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank ) else logging.WARN ) # Log on each process the small summary: logger.warning( f'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}''' + f'''distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}''' ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("""Training/evaluation parameters %s""" , lowercase ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. SCREAMING_SNAKE_CASE_: List[str] =load_dataset(data_args.dataset_name , data_args.dataset_config_name ) if "validation" not in datasets.keys(): SCREAMING_SNAKE_CASE_: Optional[Any] =load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=f'''train[:{data_args.validation_split_percentage}%]''' , ) SCREAMING_SNAKE_CASE_: Optional[int] =load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=f'''train[{data_args.validation_split_percentage}%:]''' , ) else: SCREAMING_SNAKE_CASE_: List[Any] ={} if data_args.train_file is not None: SCREAMING_SNAKE_CASE_: List[str] =data_args.train_file if data_args.validation_file is not None: SCREAMING_SNAKE_CASE_: Union[str, Any] =data_args.validation_file SCREAMING_SNAKE_CASE_: Union[str, Any] =data_args.train_file.split(""".""" )[-1] if extension == "txt": SCREAMING_SNAKE_CASE_: Union[str, Any] ="""text""" SCREAMING_SNAKE_CASE_: Optional[int] =load_dataset(lowercase , data_files=lowercase ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. SCREAMING_SNAKE_CASE_: Any ={ """cache_dir""": model_args.cache_dir, """revision""": model_args.model_revision, """use_auth_token""": True if model_args.use_auth_token else None, } if model_args.config_name: SCREAMING_SNAKE_CASE_: int =AutoConfig.from_pretrained(model_args.config_name , **lowercase ) elif model_args.model_name_or_path: SCREAMING_SNAKE_CASE_: Optional[Any] =AutoConfig.from_pretrained(model_args.model_name_or_path , **lowercase ) else: SCREAMING_SNAKE_CASE_: List[str] =CONFIG_MAPPING[model_args.model_type]() logger.warning("""You are instantiating a new config instance from scratch.""" ) if model_args.config_overrides is not None: logger.info(f'''Overriding config: {model_args.config_overrides}''' ) config.update_from_string(model_args.config_overrides ) logger.info(f'''New config: {config}''' ) SCREAMING_SNAKE_CASE_: List[Any] ={ """cache_dir""": model_args.cache_dir, """use_fast""": model_args.use_fast_tokenizer, """revision""": model_args.model_revision, """use_auth_token""": True if model_args.use_auth_token else None, } if model_args.tokenizer_name: SCREAMING_SNAKE_CASE_: Optional[Any] =AutoTokenizer.from_pretrained(model_args.tokenizer_name , **lowercase ) elif model_args.model_name_or_path: SCREAMING_SNAKE_CASE_: Optional[Any] =AutoTokenizer.from_pretrained(model_args.model_name_or_path , **lowercase ) else: raise ValueError( """You are instantiating a new tokenizer from scratch. This is not supported by this script.""" """You can do it from another script, save it, and load it from here, using --tokenizer_name.""" ) if model_args.model_name_or_path: SCREAMING_SNAKE_CASE_: Dict =AutoModelForMaskedLM.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=lowercase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info("""Training new model from scratch""" ) SCREAMING_SNAKE_CASE_: str =AutoModelForMaskedLM.from_config(lowercase ) model.resize_token_embeddings(len(lowercase ) ) # Preprocessing the datasets. # First we tokenize all the texts. if training_args.do_train: SCREAMING_SNAKE_CASE_: str =datasets["""train"""].column_names else: SCREAMING_SNAKE_CASE_: List[Any] =datasets["""validation"""].column_names SCREAMING_SNAKE_CASE_: Dict ="""text""" if """text""" in column_names else column_names[0] SCREAMING_SNAKE_CASE_: List[str] ="""max_length""" if data_args.pad_to_max_length else False def tokenize_function(lowercase ): # Remove empty lines SCREAMING_SNAKE_CASE_: List[str] =[line for line in examples["""text"""] if len(lowercase ) > 0 and not line.isspace()] return tokenizer(examples["""text"""] , padding=lowercase , truncation=lowercase , max_length=data_args.max_seq_length ) SCREAMING_SNAKE_CASE_: int =datasets.map( lowercase , batched=lowercase , num_proc=data_args.preprocessing_num_workers , remove_columns=[text_column_name] , load_from_cache_file=not data_args.overwrite_cache , ) # Add the chinese references if provided if data_args.train_ref_file is not None: SCREAMING_SNAKE_CASE_: Dict =add_chinese_references(tokenized_datasets["""train"""] , data_args.train_ref_file ) if data_args.validation_ref_file is not None: SCREAMING_SNAKE_CASE_: List[Any] =add_chinese_references( tokenized_datasets["""validation"""] , data_args.validation_ref_file ) # If we have ref files, need to avoid it removed by trainer SCREAMING_SNAKE_CASE_: Dict =data_args.train_ref_file or data_args.validation_ref_file if has_ref: SCREAMING_SNAKE_CASE_: Tuple =False # Data collator # This one will take care of randomly masking the tokens. SCREAMING_SNAKE_CASE_: Tuple =DataCollatorForWholeWordMask(tokenizer=lowercase , mlm_probability=data_args.mlm_probability ) # Initialize our Trainer SCREAMING_SNAKE_CASE_: Optional[Any] =Trainer( model=lowercase , args=lowercase , train_dataset=tokenized_datasets["""train"""] if training_args.do_train else None , eval_dataset=tokenized_datasets["""validation"""] if training_args.do_eval else None , tokenizer=lowercase , data_collator=lowercase , ) # Training if training_args.do_train: if last_checkpoint is not None: SCREAMING_SNAKE_CASE_: Optional[Any] =last_checkpoint elif model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path ): SCREAMING_SNAKE_CASE_: Dict =model_args.model_name_or_path else: SCREAMING_SNAKE_CASE_: Union[str, Any] =None SCREAMING_SNAKE_CASE_: str =trainer.train(resume_from_checkpoint=lowercase ) trainer.save_model() # Saves the tokenizer too for easy upload SCREAMING_SNAKE_CASE_: Any =os.path.join(training_args.output_dir , """train_results.txt""" ) if trainer.is_world_process_zero(): with open(lowercase , """w""" ) as writer: logger.info("""***** Train results *****""" ) for key, value in sorted(train_result.metrics.items() ): logger.info(f''' {key} = {value}''' ) writer.write(f'''{key} = {value}\n''' ) # 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""" ) ) # Evaluation SCREAMING_SNAKE_CASE_: List[str] ={} if training_args.do_eval: logger.info("""*** Evaluate ***""" ) SCREAMING_SNAKE_CASE_: List[Any] =trainer.evaluate() SCREAMING_SNAKE_CASE_: Dict =math.exp(eval_output["""eval_loss"""] ) SCREAMING_SNAKE_CASE_: Tuple =perplexity SCREAMING_SNAKE_CASE_: List[str] =os.path.join(training_args.output_dir , """eval_results_mlm_wwm.txt""" ) if trainer.is_world_process_zero(): with open(lowercase , """w""" ) as writer: logger.info("""***** Eval results *****""" ) for key, value in sorted(results.items() ): logger.info(f''' {key} = {value}''' ) writer.write(f'''{key} = {value}\n''' ) return results def __magic_name__ ( lowercase ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
36
"""simple docstring""" import copy import inspect import unittest from transformers import PretrainedConfig, SwiftFormerConfig from transformers.testing_utils import ( require_torch, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwiftFormerForImageClassification, SwiftFormerModel from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class a : def __init__( self : Any , lowerCAmelCase : Any , lowerCAmelCase : List[str]=13 , lowerCAmelCase : Dict=3 , lowerCAmelCase : Optional[Any]=True , lowerCAmelCase : Dict=True , lowerCAmelCase : Dict=0.1 , lowerCAmelCase : str=0.1 , lowerCAmelCase : List[str]=224 , lowerCAmelCase : List[str]=1000 , lowerCAmelCase : Optional[Any]=[3, 3, 6, 4] , lowerCAmelCase : int=[48, 56, 112, 220] , ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[int] =parent SCREAMING_SNAKE_CASE_: Any =batch_size SCREAMING_SNAKE_CASE_: Tuple =num_channels SCREAMING_SNAKE_CASE_: Union[str, Any] =is_training SCREAMING_SNAKE_CASE_: Tuple =use_labels SCREAMING_SNAKE_CASE_: Optional[int] =hidden_dropout_prob SCREAMING_SNAKE_CASE_: Tuple =attention_probs_dropout_prob SCREAMING_SNAKE_CASE_: List[Any] =num_labels SCREAMING_SNAKE_CASE_: int =image_size SCREAMING_SNAKE_CASE_: Optional[Any] =layer_depths SCREAMING_SNAKE_CASE_: List[Any] =embed_dims def lowerCamelCase__ ( self : List[Any] ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[str] =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_: List[Any] =None if self.use_labels: SCREAMING_SNAKE_CASE_: List[str] =ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE_: Tuple =self.get_config() return config, pixel_values, labels def lowerCamelCase__ ( self : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' return SwiftFormerConfig( depths=self.layer_depths , embed_dims=self.embed_dims , mlp_ratio=4 , downsamples=[True, True, True, True] , hidden_act="""gelu""" , num_labels=self.num_labels , down_patch_size=3 , down_stride=2 , down_pad=1 , drop_rate=0.0 , drop_path_rate=0.0 , use_layer_scale=lowerCAmelCase , layer_scale_init_value=1E-5 , ) def lowerCamelCase__ ( self : Any , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Optional[Any] , lowerCAmelCase : Optional[int] ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[str] =SwiftFormerModel(config=lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() SCREAMING_SNAKE_CASE_: Any =model(lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dims[-1], 7, 7) ) def lowerCamelCase__ ( self : Union[str, Any] , lowerCAmelCase : List[Any] , lowerCAmelCase : Optional[int] , lowerCAmelCase : Union[str, Any] ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[Any] =self.num_labels SCREAMING_SNAKE_CASE_: Dict =SwiftFormerForImageClassification(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() SCREAMING_SNAKE_CASE_: Dict =model(lowerCAmelCase , labels=lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) SCREAMING_SNAKE_CASE_: int =SwiftFormerForImageClassification(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() SCREAMING_SNAKE_CASE_: Tuple =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_: Dict =model(lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase__ ( self : int ) -> Optional[Any]: '''simple docstring''' ((SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_)): str =self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_: Tuple ={"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class a ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): UpperCamelCase : Optional[int] = (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else () UpperCamelCase : Tuple = ( {'feature-extraction': SwiftFormerModel, 'image-classification': SwiftFormerForImageClassification} if is_torch_available() else {} ) UpperCamelCase : Any = False UpperCamelCase : Optional[int] = False UpperCamelCase : Optional[Any] = False UpperCamelCase : Dict = False UpperCamelCase : List[str] = False def lowerCamelCase__ ( self : Dict ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =SwiftFormerModelTester(self ) SCREAMING_SNAKE_CASE_: Union[str, Any] =ConfigTester( self , config_class=lowerCAmelCase , has_text_modality=lowerCAmelCase , hidden_size=37 , num_attention_heads=12 , num_hidden_layers=12 , ) def lowerCamelCase__ ( self : Tuple ) -> int: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="""SwiftFormer does not use inputs_embeds""" ) def lowerCamelCase__ ( self : Tuple ) -> List[str]: '''simple docstring''' pass def lowerCamelCase__ ( self : Optional[int] ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[str] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_: Any =model_class(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[Any] =model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCAmelCase , nn.Linear ) ) def lowerCamelCase__ ( self : str ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[Any] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_: int =model_class(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[Any] =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE_: Any =[*signature.parameters.keys()] SCREAMING_SNAKE_CASE_: Tuple =["""pixel_values"""] self.assertListEqual(arg_names[:1] , lowerCAmelCase ) def lowerCamelCase__ ( self : int ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase ) def lowerCamelCase__ ( self : Any ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: int =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase ) @slow def lowerCamelCase__ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_: Optional[Any] =SwiftFormerModel.from_pretrained(lowerCAmelCase ) self.assertIsNotNone(lowerCAmelCase ) @unittest.skip(reason="""SwiftFormer does not output attentions""" ) def lowerCamelCase__ ( self : Optional[int] ) -> str: '''simple docstring''' pass def lowerCamelCase__ ( self : List[Any] ) -> List[str]: '''simple docstring''' def check_hidden_states_output(lowerCAmelCase : Optional[int] , lowerCAmelCase : str , lowerCAmelCase : Optional[int] ): SCREAMING_SNAKE_CASE_: Optional[Any] =model_class(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_: List[str] =model(**self._prepare_for_class(lowerCAmelCase , lowerCAmelCase ) ) SCREAMING_SNAKE_CASE_: Dict =outputs.hidden_states SCREAMING_SNAKE_CASE_: List[Any] =8 self.assertEqual(len(lowerCAmelCase ) , lowerCAmelCase ) # TODO # SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width) # with the width and height being successively divided by 2, after every 2 blocks for i in range(len(lowerCAmelCase ) ): self.assertEqual( hidden_states[i].shape , torch.Size( [ self.model_tester.batch_size, self.model_tester.embed_dims[i // 2], (self.model_tester.image_size // 4) // 2 ** (i // 2), (self.model_tester.image_size // 4) // 2 ** (i // 2), ] ) , ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: int =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_: Dict =True check_hidden_states_output(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE_: Any =True check_hidden_states_output(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) def lowerCamelCase__ ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' def _config_zero_init(lowerCAmelCase : str ): SCREAMING_SNAKE_CASE_: Dict =copy.deepcopy(lowerCAmelCase ) for key in configs_no_init.__dict__.keys(): if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key: setattr(lowerCAmelCase , lowerCAmelCase , 1E-10 ) if isinstance(getattr(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) , lowerCAmelCase ): SCREAMING_SNAKE_CASE_: Tuple =_config_zero_init(getattr(lowerCAmelCase , lowerCAmelCase ) ) setattr(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) return configs_no_init SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[Any] =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_: List[Any] =_config_zero_init(lowerCAmelCase ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_: Any =model_class(config=lowerCAmelCase ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1E9) / 1E9).round().item() , [0.0, 1.0] , msg=f'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def lowerCamelCase__ ( self : List[str] ) -> List[str]: '''simple docstring''' pass def __magic_name__ ( ): SCREAMING_SNAKE_CASE_: List[Any] =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class a ( unittest.TestCase ): @cached_property def lowerCamelCase__ ( self : str ) -> str: '''simple docstring''' return ViTImageProcessor.from_pretrained("""MBZUAI/swiftformer-xs""" ) if is_vision_available() else None @slow def lowerCamelCase__ ( self : Union[str, Any] ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: str =SwiftFormerForImageClassification.from_pretrained("""MBZUAI/swiftformer-xs""" ).to(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: str =self.default_image_processor SCREAMING_SNAKE_CASE_: int =prepare_img() SCREAMING_SNAKE_CASE_: Union[str, Any] =image_processor(images=lowerCAmelCase , return_tensors="""pt""" ).to(lowerCAmelCase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_: Dict =model(**lowerCAmelCase ) # verify the logits SCREAMING_SNAKE_CASE_: Optional[Any] =torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =torch.tensor([[-2.1_703E00, 2.1_107E00, -2.0_811E00]] ).to(lowerCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCAmelCase , atol=1E-4 ) )
36
1
"""simple docstring""" import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger _UpperCAmelCase = """<<<<<<< This should probably be modified because it mentions: """ _UpperCAmelCase = """======= >>>>>>> """ _UpperCAmelCase = [ """TextEncoderConfig""", """ByteTextEncoder""", """SubwordTextEncoder""", """encoder_config""", """maybe_build_from_corpus""", """manual_dir""", ] _UpperCAmelCase = [ # (pattern, replacement) # Order is important here for some replacements (r"""tfds\.core""", r"""datasets"""), (r"""tf\.io\.gfile\.GFile""", r"""open"""), (r"""tf\.([\w\d]+)""", r"""datasets.Value('\1')"""), (r"""tfds\.features\.Text\(\)""", r"""datasets.Value('string')"""), (r"""tfds\.features\.Text\(""", r"""datasets.Value('string'),"""), (r"""features\s*=\s*tfds.features.FeaturesDict\(""", r"""features=datasets.Features("""), (r"""tfds\.features\.FeaturesDict\(""", r"""dict("""), (r"""The TensorFlow Datasets Authors""", r"""The TensorFlow Datasets Authors and the HuggingFace Datasets Authors"""), (r"""tfds\.""", r"""datasets."""), (r"""dl_manager\.manual_dir""", r"""self.config.data_dir"""), (r"""self\.builder_config""", r"""self.config"""), ] def __magic_name__ ( lowercase ): return ConvertCommand(args.tfds_path , args.datasets_directory ) class a ( UpperCAmelCase__ ): @staticmethod def lowerCamelCase__ ( lowerCAmelCase : ArgumentParser ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =parser.add_parser( """convert""" , help="""Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.""" , ) train_parser.add_argument( """--tfds_path""" , type=lowerCAmelCase , required=lowerCAmelCase , help="""Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.""" , ) train_parser.add_argument( """--datasets_directory""" , type=lowerCAmelCase , required=lowerCAmelCase , help="""Path to the HuggingFace Datasets folder.""" ) train_parser.set_defaults(func=lowerCAmelCase ) def __init__( self : Tuple , lowerCAmelCase : str , lowerCAmelCase : str , *lowerCAmelCase : int ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =get_logger("""datasets-cli/converting""" ) SCREAMING_SNAKE_CASE_: int =tfds_path SCREAMING_SNAKE_CASE_: Tuple =datasets_directory def lowerCamelCase__ ( self : Optional[int] ) -> str: '''simple docstring''' if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE_: Any =os.path.abspath(self._tfds_path ) elif os.path.isfile(self._tfds_path ): SCREAMING_SNAKE_CASE_: str =os.path.dirname(self._tfds_path ) else: raise ValueError("""--tfds_path is neither a directory nor a file. Please check path.""" ) SCREAMING_SNAKE_CASE_: str =os.path.abspath(self._datasets_directory ) self._logger.info(f'''Converting datasets from {abs_tfds_path} to {abs_datasets_path}''' ) SCREAMING_SNAKE_CASE_: Dict =[] SCREAMING_SNAKE_CASE_: Any =[] SCREAMING_SNAKE_CASE_: Tuple ={} if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE_: Optional[int] =os.listdir(lowerCAmelCase ) else: SCREAMING_SNAKE_CASE_: str =[os.path.basename(self._tfds_path )] for f_name in file_names: self._logger.info(f'''Looking at file {f_name}''' ) SCREAMING_SNAKE_CASE_: Any =os.path.join(lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Dict =os.path.join(lowerCAmelCase , lowerCAmelCase ) if not os.path.isfile(lowerCAmelCase ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info("""Skipping file""" ) continue with open(lowerCAmelCase , encoding="""utf-8""" ) as f: SCREAMING_SNAKE_CASE_: List[str] =f.readlines() SCREAMING_SNAKE_CASE_: Optional[int] =[] SCREAMING_SNAKE_CASE_: str =False SCREAMING_SNAKE_CASE_: List[Any] =False SCREAMING_SNAKE_CASE_: Dict =[] for line in lines: SCREAMING_SNAKE_CASE_: List[str] =line # Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: SCREAMING_SNAKE_CASE_: Dict ="""import datasets\n""" elif "import tensorflow" in out_line: # order is important here SCREAMING_SNAKE_CASE_: int ="""""" continue elif "from absl import logging" in out_line: SCREAMING_SNAKE_CASE_: int ="""from datasets import logging\n""" elif "getLogger" in out_line: SCREAMING_SNAKE_CASE_: int =out_line.replace("""getLogger""" , """get_logger""" ) elif any(expression in out_line for expression in TO_HIGHLIGHT ): SCREAMING_SNAKE_CASE_: Dict =True SCREAMING_SNAKE_CASE_: Optional[int] =list(filter(lambda lowerCAmelCase : e in out_line , lowerCAmelCase ) ) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(lowerCAmelCase ) + """\n""" ) out_lines.append(lowerCAmelCase ) out_lines.append(lowerCAmelCase ) continue else: for pattern, replacement in TO_CONVERT: SCREAMING_SNAKE_CASE_: Optional[Any] =re.sub(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) # Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: SCREAMING_SNAKE_CASE_: Any =re.match(R"""from\stensorflow_datasets.*import\s([^\.\r\n]+)""" , lowerCAmelCase ) tfds_imports.extend(imp.strip() for imp in match.group(1 ).split(""",""" ) ) SCREAMING_SNAKE_CASE_: Union[str, Any] ="""from . import """ + match.group(1 ) # Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(f'''Error converting {out_line.strip()}''' ) if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line: SCREAMING_SNAKE_CASE_: Optional[int] =True out_lines.append(lowerCAmelCase ) if is_builder or "wmt" in f_name: # We create a new directory for each dataset SCREAMING_SNAKE_CASE_: Any =f_name.replace(""".py""" , """""" ) SCREAMING_SNAKE_CASE_: str =os.path.join(lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: int =os.path.join(lowerCAmelCase , lowerCAmelCase ) os.makedirs(lowerCAmelCase , exist_ok=lowerCAmelCase ) self._logger.info(f'''Adding directory {output_dir}''' ) imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} ) else: # Utilities will be moved at the end utils_files.append(lowerCAmelCase ) if needs_manual_update: with_manual_update.append(lowerCAmelCase ) with open(lowerCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.writelines(lowerCAmelCase ) self._logger.info(f'''Converted in {output_file}''' ) for utils_file in utils_files: try: SCREAMING_SNAKE_CASE_: Optional[int] =os.path.basename(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: str =imports_to_builder_map[f_name.replace(""".py""" , """""" )] self._logger.info(f'''Moving {dest_folder} to {utils_file}''' ) shutil.copy(lowerCAmelCase , lowerCAmelCase ) except KeyError: self._logger.error(f'''Cannot find destination folder for {utils_file}. Please copy manually.''' ) if with_manual_update: for file_path in with_manual_update: self._logger.warning( f'''You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.''' )
36
"""simple docstring""" from math import pi def __magic_name__ ( lowercase , lowercase ): return 2 * pi * radius * (angle / 360) if __name__ == "__main__": print(arc_length(9_0, 1_0))
36
1
"""simple docstring""" def __magic_name__ ( lowercase , lowercase , lowercase=False ): if isinstance(lowercase , lowercase ) and isinstance(lowercase , lowercase ): SCREAMING_SNAKE_CASE_: Tuple =len(set_a.intersection(lowercase ) ) if alternative_union: SCREAMING_SNAKE_CASE_: int =len(lowercase ) + len(lowercase ) else: SCREAMING_SNAKE_CASE_: Optional[int] =len(set_a.union(lowercase ) ) return intersection / union if isinstance(lowercase , (list, tuple) ) and isinstance(lowercase , (list, tuple) ): SCREAMING_SNAKE_CASE_: Optional[Any] =[element for element in set_a if element in set_b] if alternative_union: SCREAMING_SNAKE_CASE_: Dict =len(lowercase ) + len(lowercase ) return len(lowercase ) / union else: SCREAMING_SNAKE_CASE_: Union[str, Any] =set_a + [element for element in set_b if element not in set_a] return len(lowercase ) / len(lowercase ) return len(lowercase ) / len(lowercase ) return None if __name__ == "__main__": _UpperCAmelCase = {"""a""", """b""", """c""", """d""", """e"""} _UpperCAmelCase = {"""c""", """d""", """e""", """f""", """h""", """i"""} print(jaccard_similarity(set_a, set_b))
36
"""simple docstring""" 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 a ( unittest.TestCase ): def lowerCamelCase__ ( self : Dict ) -> str: '''simple docstring''' super().tearDown() gc.collect() def lowerCamelCase__ ( self : Optional[Any] ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Dict =FlaxStableDiffusionPipeline.from_pretrained( """stabilityai/stable-diffusion-2""" , revision="""bf16""" , dtype=jnp.bfloataa , ) SCREAMING_SNAKE_CASE_: Union[str, Any] ="""A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE_: Any =jax.device_count() SCREAMING_SNAKE_CASE_: Dict =num_samples * [prompt] SCREAMING_SNAKE_CASE_: List[Any] =sd_pipe.prepare_inputs(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Union[str, Any] =replicate(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =shard(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Dict =jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE_: Union[str, Any] =jax.random.split(lowerCAmelCase , jax.device_count() ) SCREAMING_SNAKE_CASE_: Tuple =sd_pipe(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , num_inference_steps=25 , jit=lowerCAmelCase )[0] assert images.shape == (jax.device_count(), 1, 768, 768, 3) SCREAMING_SNAKE_CASE_: Dict =images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) SCREAMING_SNAKE_CASE_: Dict =images[0, 253:256, 253:256, -1] SCREAMING_SNAKE_CASE_: Optional[int] =jnp.asarray(jax.device_get(image_slice.flatten() ) ) SCREAMING_SNAKE_CASE_: Optional[int] =jnp.array([0.4_2_3_8, 0.4_4_1_4, 0.4_3_9_5, 0.4_4_5_3, 0.4_6_2_9, 0.4_5_9_0, 0.4_5_3_1, 0.4_5_5_0_8, 0.4_5_1_2] ) print(f'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2 def lowerCamelCase__ ( self : List[str] ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE_: int ="""stabilityai/stable-diffusion-2""" SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[int] =FlaxDPMSolverMultistepScheduler.from_pretrained(lowerCAmelCase , subfolder="""scheduler""" ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[int] =FlaxStableDiffusionPipeline.from_pretrained( lowerCAmelCase , scheduler=lowerCAmelCase , revision="""bf16""" , dtype=jnp.bfloataa , ) SCREAMING_SNAKE_CASE_: Optional[int] =scheduler_params SCREAMING_SNAKE_CASE_: Tuple ="""A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE_: Union[str, Any] =jax.device_count() SCREAMING_SNAKE_CASE_: Optional[Any] =num_samples * [prompt] SCREAMING_SNAKE_CASE_: List[Any] =sd_pipe.prepare_inputs(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple =replicate(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =shard(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Any =jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE_: Any =jax.random.split(lowerCAmelCase , jax.device_count() ) SCREAMING_SNAKE_CASE_: Tuple =sd_pipe(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , num_inference_steps=25 , jit=lowerCAmelCase )[0] assert images.shape == (jax.device_count(), 1, 768, 768, 3) SCREAMING_SNAKE_CASE_: str =images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) SCREAMING_SNAKE_CASE_: Any =images[0, 253:256, 253:256, -1] SCREAMING_SNAKE_CASE_: Optional[Any] =jnp.asarray(jax.device_get(image_slice.flatten() ) ) SCREAMING_SNAKE_CASE_: Optional[int] =jnp.array([0.4_3_3_6, 0.4_2_9_6_9, 0.4_4_5_3, 0.4_1_9_9, 0.4_2_9_7, 0.4_5_3_1, 0.4_4_3_4, 0.4_4_3_4, 0.4_2_9_7] ) print(f'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2
36
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { """abeja/gpt-neox-japanese-2.7b""": """https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/config.json""", } class a ( UpperCAmelCase__ ): UpperCamelCase : Optional[int] = 'gpt_neox_japanese' def __init__( self : Tuple , lowerCAmelCase : Optional[Any]=3_2000 , lowerCAmelCase : Dict=2560 , lowerCAmelCase : Tuple=32 , lowerCAmelCase : str=32 , lowerCAmelCase : List[str]=4 , lowerCAmelCase : Any="gelu" , lowerCAmelCase : List[str]=1.0_0 , lowerCAmelCase : Tuple=1_0000 , lowerCAmelCase : Any=2048 , lowerCAmelCase : Union[str, Any]=0.0_2 , lowerCAmelCase : Optional[Any]=1E-5 , lowerCAmelCase : Union[str, Any]=True , lowerCAmelCase : str=3_1996 , lowerCAmelCase : Tuple=3_1999 , lowerCAmelCase : Optional[int]=0.1 , lowerCAmelCase : int=0.0 , **lowerCAmelCase : int , ) -> Any: '''simple docstring''' super().__init__(bos_token_id=lowerCAmelCase , eos_token_id=lowerCAmelCase , **lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Union[str, Any] =vocab_size SCREAMING_SNAKE_CASE_: int =max_position_embeddings SCREAMING_SNAKE_CASE_: str =hidden_size SCREAMING_SNAKE_CASE_: int =num_hidden_layers SCREAMING_SNAKE_CASE_: Dict =num_attention_heads SCREAMING_SNAKE_CASE_: int =intermediate_multiple_size SCREAMING_SNAKE_CASE_: str =hidden_act SCREAMING_SNAKE_CASE_: int =rotary_pct SCREAMING_SNAKE_CASE_: Tuple =rotary_emb_base SCREAMING_SNAKE_CASE_: List[Any] =initializer_range SCREAMING_SNAKE_CASE_: Optional[Any] =layer_norm_eps SCREAMING_SNAKE_CASE_: Any =use_cache SCREAMING_SNAKE_CASE_: Optional[Any] =attention_dropout SCREAMING_SNAKE_CASE_: Dict =hidden_dropout
36
"""simple docstring""" def __magic_name__ ( lowercase = 200_0000 ): SCREAMING_SNAKE_CASE_: List[Any] =[0 for i in range(n + 1 )] SCREAMING_SNAKE_CASE_: Union[str, Any] =1 SCREAMING_SNAKE_CASE_: Optional[Any] =1 for i in range(2 , int(n**0.5 ) + 1 ): if primality_list[i] == 0: for j in range(i * i , n + 1 , lowercase ): SCREAMING_SNAKE_CASE_: Optional[int] =1 SCREAMING_SNAKE_CASE_: Dict =0 for i in range(lowercase ): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(f"""{solution() = }""")
36
1
"""simple docstring""" from ..utils import DummyObject, requires_backends class a ( metaclass=UpperCAmelCase__ ): UpperCamelCase : str = ['note_seq'] def __init__( self : int , *lowerCAmelCase : Union[str, Any] , **lowerCAmelCase : str ) -> Dict: '''simple docstring''' requires_backends(self , ["""note_seq"""] ) @classmethod def lowerCamelCase__ ( cls : Dict , *lowerCAmelCase : Optional[int] , **lowerCAmelCase : Any ) -> Any: '''simple docstring''' requires_backends(cls , ["""note_seq"""] ) @classmethod def lowerCamelCase__ ( cls : Tuple , *lowerCAmelCase : Union[str, Any] , **lowerCAmelCase : List[str] ) -> List[str]: '''simple docstring''' requires_backends(cls , ["""note_seq"""] )
36
"""simple docstring""" import argparse import torch from transformers import BertForMaskedLM if __name__ == "__main__": _UpperCAmelCase = argparse.ArgumentParser( description=( """Extraction some layers of the full BertForMaskedLM or RObertaForMaskedLM for Transfer Learned""" """ Distillation""" ) ) parser.add_argument("""--model_type""", default="""bert""", choices=["""bert"""]) parser.add_argument("""--model_name""", default="""bert-base-uncased""", type=str) parser.add_argument("""--dump_checkpoint""", default="""serialization_dir/tf_bert-base-uncased_0247911.pth""", type=str) parser.add_argument("""--vocab_transform""", action="""store_true""") _UpperCAmelCase = parser.parse_args() if args.model_type == "bert": _UpperCAmelCase = BertForMaskedLM.from_pretrained(args.model_name) _UpperCAmelCase = """bert""" else: raise ValueError("""args.model_type should be \"bert\".""") _UpperCAmelCase = model.state_dict() _UpperCAmelCase = {} for w in ["word_embeddings", "position_embeddings"]: _UpperCAmelCase = state_dict[f"""{prefix}.embeddings.{w}.weight"""] for w in ["weight", "bias"]: _UpperCAmelCase = state_dict[f"""{prefix}.embeddings.LayerNorm.{w}"""] _UpperCAmelCase = 0 for teacher_idx in [0, 2, 4, 7, 9, 1_1]: for w in ["weight", "bias"]: _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.query.{w}""" ] _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.key.{w}""" ] _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.value.{w}""" ] _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.output.dense.{w}""" ] _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.output.LayerNorm.{w}""" ] _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.intermediate.dense.{w}""" ] _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.output.dense.{w}""" ] _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.output.LayerNorm.{w}""" ] std_idx += 1 _UpperCAmelCase = state_dict["""cls.predictions.decoder.weight"""] _UpperCAmelCase = state_dict["""cls.predictions.bias"""] if args.vocab_transform: for w in ["weight", "bias"]: _UpperCAmelCase = state_dict[f"""cls.predictions.transform.dense.{w}"""] _UpperCAmelCase = state_dict[f"""cls.predictions.transform.LayerNorm.{w}"""] print(f"""N layers selected for distillation: {std_idx}""") print(f"""Number of params transferred for distillation: {len(compressed_sd.keys())}""") print(f"""Save transferred checkpoint to {args.dump_checkpoint}.""") torch.save(compressed_sd, args.dump_checkpoint)
36
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _UpperCAmelCase = {"""configuration_vit_mae""": ["""VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ViTMAEConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ """VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST""", """ViTMAEForPreTraining""", """ViTMAELayer""", """ViTMAEModel""", """ViTMAEPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ """TFViTMAEForPreTraining""", """TFViTMAEModel""", """TFViTMAEPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_vit_mae import VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMAEConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_mae import ( VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMAEForPreTraining, ViTMAELayer, ViTMAEModel, ViTMAEPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit_mae import TFViTMAEForPreTraining, TFViTMAEModel, TFViTMAEPreTrainedModel else: import sys _UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
36
"""simple docstring""" def __magic_name__ ( lowercase , lowercase ): return int((input_a, input_a).count(0 ) == 0 ) def __magic_name__ ( ): assert and_gate(0 , 0 ) == 0 assert and_gate(0 , 1 ) == 0 assert and_gate(1 , 0 ) == 0 assert and_gate(1 , 1 ) == 1 if __name__ == "__main__": test_and_gate() print(and_gate(1, 0)) print(and_gate(0, 0)) print(and_gate(0, 1)) print(and_gate(1, 1))
36
1
"""simple docstring""" import inspect from typing import Callable, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import DiffusionPipeline from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import logging _UpperCAmelCase = logging.get_logger(__name__) # pylint: disable=invalid-name class a ( UpperCAmelCase__ ): def __init__( self : str , lowerCAmelCase : AutoencoderKL , lowerCAmelCase : CLIPTextModel , lowerCAmelCase : CLIPTokenizer , lowerCAmelCase : UNetaDConditionModel , lowerCAmelCase : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , lowerCAmelCase : StableDiffusionSafetyChecker , lowerCAmelCase : CLIPImageProcessor , ) -> str: '''simple docstring''' super().__init__() self.register_modules( vae=lowerCAmelCase , text_encoder=lowerCAmelCase , tokenizer=lowerCAmelCase , unet=lowerCAmelCase , scheduler=lowerCAmelCase , safety_checker=lowerCAmelCase , feature_extractor=lowerCAmelCase , ) def lowerCamelCase__ ( self : Optional[Any] , lowerCAmelCase : Optional[Union[str, int]] = "auto" ) -> Tuple: '''simple docstring''' if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory SCREAMING_SNAKE_CASE_: Union[str, Any] =self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(lowerCAmelCase ) def lowerCamelCase__ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' self.enable_attention_slicing(lowerCAmelCase ) @torch.no_grad() def __call__( self : Optional[int] , lowerCAmelCase : Union[str, List[str]] , lowerCAmelCase : int = 512 , lowerCAmelCase : int = 512 , lowerCAmelCase : int = 50 , lowerCAmelCase : float = 7.5 , lowerCAmelCase : Optional[Union[str, List[str]]] = None , lowerCAmelCase : Optional[int] = 1 , lowerCAmelCase : float = 0.0 , lowerCAmelCase : Optional[torch.Generator] = None , lowerCAmelCase : Optional[torch.FloatTensor] = None , lowerCAmelCase : Optional[str] = "pil" , lowerCAmelCase : bool = True , lowerCAmelCase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , lowerCAmelCase : int = 1 , lowerCAmelCase : Optional[torch.FloatTensor] = None , **lowerCAmelCase : Tuple , ) -> Optional[Any]: '''simple docstring''' if isinstance(lowerCAmelCase , lowerCAmelCase ): SCREAMING_SNAKE_CASE_: int =1 elif isinstance(lowerCAmelCase , lowerCAmelCase ): SCREAMING_SNAKE_CASE_: str =len(lowerCAmelCase ) else: raise ValueError(f'''`prompt` has to be of type `str` or `list` but is {type(lowerCAmelCase )}''' ) if height % 8 != 0 or width % 8 != 0: raise ValueError(f'''`height` and `width` have to be divisible by 8 but are {height} and {width}.''' ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(lowerCAmelCase , lowerCAmelCase ) or callback_steps <= 0) ): raise ValueError( f'''`callback_steps` has to be a positive integer but is {callback_steps} of type''' f''' {type(lowerCAmelCase )}.''' ) # get prompt text embeddings SCREAMING_SNAKE_CASE_: int =self.tokenizer( lowerCAmelCase , padding="""max_length""" , max_length=self.tokenizer.model_max_length , return_tensors="""pt""" , ) SCREAMING_SNAKE_CASE_: List[str] =text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: SCREAMING_SNAKE_CASE_: Optional[int] =self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( """The following part of your input was truncated because CLIP can only handle sequences up to""" f''' {self.tokenizer.model_max_length} tokens: {removed_text}''' ) SCREAMING_SNAKE_CASE_: Optional[Any] =text_input_ids[:, : self.tokenizer.model_max_length] if text_embeddings is None: SCREAMING_SNAKE_CASE_: List[str] =self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Dict =text_embeddings.shape SCREAMING_SNAKE_CASE_: Any =text_embeddings.repeat(1 , lowerCAmelCase , 1 ) SCREAMING_SNAKE_CASE_: Any =text_embeddings.view(bs_embed * num_images_per_prompt , lowerCAmelCase , -1 ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. SCREAMING_SNAKE_CASE_: int =guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: SCREAMING_SNAKE_CASE_: List[str] if negative_prompt is None: SCREAMING_SNAKE_CASE_: Union[str, Any] =[""""""] elif type(lowerCAmelCase ) is not type(lowerCAmelCase ): raise TypeError( f'''`negative_prompt` should be the same type to `prompt`, but got {type(lowerCAmelCase )} !=''' f''' {type(lowerCAmelCase )}.''' ) elif isinstance(lowerCAmelCase , lowerCAmelCase ): SCREAMING_SNAKE_CASE_: Any =[negative_prompt] elif batch_size != len(lowerCAmelCase ): raise ValueError( f'''`negative_prompt`: {negative_prompt} has batch size {len(lowerCAmelCase )}, but `prompt`:''' f''' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches''' """ the batch size of `prompt`.""" ) else: SCREAMING_SNAKE_CASE_: Optional[int] =negative_prompt SCREAMING_SNAKE_CASE_: List[Any] =text_input_ids.shape[-1] SCREAMING_SNAKE_CASE_: Tuple =self.tokenizer( lowerCAmelCase , padding="""max_length""" , max_length=lowerCAmelCase , truncation=lowerCAmelCase , return_tensors="""pt""" , ) SCREAMING_SNAKE_CASE_: Optional[int] =self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method SCREAMING_SNAKE_CASE_: Union[str, Any] =uncond_embeddings.shape[1] SCREAMING_SNAKE_CASE_: Tuple =uncond_embeddings.repeat(lowerCAmelCase , lowerCAmelCase , 1 ) SCREAMING_SNAKE_CASE_: Tuple =uncond_embeddings.view(batch_size * num_images_per_prompt , lowerCAmelCase , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes SCREAMING_SNAKE_CASE_: Tuple =torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. SCREAMING_SNAKE_CASE_: Tuple =(batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) SCREAMING_SNAKE_CASE_: int =(batch_size * num_images_per_prompt, self.unet.config.in_channels, 64, 64) SCREAMING_SNAKE_CASE_: str =text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps SCREAMING_SNAKE_CASE_: int =torch.randn( lowerCAmelCase , generator=lowerCAmelCase , device="""cpu""" , dtype=lowerCAmelCase ).to(self.device ) SCREAMING_SNAKE_CASE_: Union[str, Any] =torch.randn(lowerCAmelCase , generator=lowerCAmelCase , device="""cpu""" , dtype=lowerCAmelCase ).to( self.device ) else: SCREAMING_SNAKE_CASE_: List[str] =torch.randn( lowerCAmelCase , generator=lowerCAmelCase , device=self.device , dtype=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =torch.randn(lowerCAmelCase , generator=lowerCAmelCase , device=self.device , dtype=lowerCAmelCase ) else: if latents_reference.shape != latents_shape: raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''' ) SCREAMING_SNAKE_CASE_: List[str] =latents_reference.to(self.device ) SCREAMING_SNAKE_CASE_: Optional[int] =latents.to(self.device ) # This is the key part of the pipeline where we # try to ensure that the generated images w/ the same seed # but different sizes actually result in similar images SCREAMING_SNAKE_CASE_: int =(latents_shape[3] - latents_shape_reference[3]) // 2 SCREAMING_SNAKE_CASE_: Optional[int] =(latents_shape[2] - latents_shape_reference[2]) // 2 SCREAMING_SNAKE_CASE_: List[Any] =latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx SCREAMING_SNAKE_CASE_: Optional[Any] =latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy SCREAMING_SNAKE_CASE_: Any =0 if dx < 0 else dx SCREAMING_SNAKE_CASE_: Tuple =0 if dy < 0 else dy SCREAMING_SNAKE_CASE_: Optional[Any] =max(-dx , 0 ) SCREAMING_SNAKE_CASE_: int =max(-dy , 0 ) # import pdb # pdb.set_trace() SCREAMING_SNAKE_CASE_: Optional[Any] =latents_reference[:, :, dy : dy + h, dx : dx + w] # set timesteps self.scheduler.set_timesteps(lowerCAmelCase ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand SCREAMING_SNAKE_CASE_: List[Any] =self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler SCREAMING_SNAKE_CASE_: Tuple =latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] SCREAMING_SNAKE_CASE_: Dict ="""eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) SCREAMING_SNAKE_CASE_: Any ={} if accepts_eta: SCREAMING_SNAKE_CASE_: Union[str, Any] =eta for i, t in enumerate(self.progress_bar(lowerCAmelCase ) ): # expand the latents if we are doing classifier free guidance SCREAMING_SNAKE_CASE_: Tuple =torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents SCREAMING_SNAKE_CASE_: Optional[Any] =self.scheduler.scale_model_input(lowerCAmelCase , lowerCAmelCase ) # predict the noise residual SCREAMING_SNAKE_CASE_: Any =self.unet(lowerCAmelCase , lowerCAmelCase , encoder_hidden_states=lowerCAmelCase ).sample # perform guidance if do_classifier_free_guidance: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[Any] =noise_pred.chunk(2 ) SCREAMING_SNAKE_CASE_: int =noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 SCREAMING_SNAKE_CASE_: Dict =self.scheduler.step(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , **lowerCAmelCase ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Union[str, Any] =1 / 0.1_8_2_1_5 * latents SCREAMING_SNAKE_CASE_: Dict =self.vae.decode(lowerCAmelCase ).sample SCREAMING_SNAKE_CASE_: Optional[Any] =(image / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 SCREAMING_SNAKE_CASE_: Union[str, Any] =image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if self.safety_checker is not None: SCREAMING_SNAKE_CASE_: Optional[int] =self.feature_extractor(self.numpy_to_pil(lowerCAmelCase ) , return_tensors="""pt""" ).to( self.device ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Tuple =self.safety_checker( images=lowerCAmelCase , clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype ) ) else: SCREAMING_SNAKE_CASE_: int =None if output_type == "pil": SCREAMING_SNAKE_CASE_: Tuple =self.numpy_to_pil(lowerCAmelCase ) if not return_dict: return (image, has_nsfw_concept) return StableDiffusionPipelineOutput(images=lowerCAmelCase , nsfw_content_detected=lowerCAmelCase )
36
"""simple docstring""" import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() _UpperCAmelCase = logging.get_logger("""transformers.models.speecht5""") def __magic_name__ ( lowercase , lowercase , lowercase ): hf_model.apply_weight_norm() SCREAMING_SNAKE_CASE_: Tuple =checkpoint["""input_conv.weight_g"""] SCREAMING_SNAKE_CASE_: Optional[int] =checkpoint["""input_conv.weight_v"""] SCREAMING_SNAKE_CASE_: Optional[int] =checkpoint["""input_conv.bias"""] for i in range(len(config.upsample_rates ) ): SCREAMING_SNAKE_CASE_: Any =checkpoint[f'''upsamples.{i}.1.weight_g'''] SCREAMING_SNAKE_CASE_: Any =checkpoint[f'''upsamples.{i}.1.weight_v'''] SCREAMING_SNAKE_CASE_: List[str] =checkpoint[f'''upsamples.{i}.1.bias'''] for i in range(len(config.upsample_rates ) * len(config.resblock_kernel_sizes ) ): for j in range(len(config.resblock_dilation_sizes ) ): SCREAMING_SNAKE_CASE_: Dict =checkpoint[f'''blocks.{i}.convs1.{j}.1.weight_g'''] SCREAMING_SNAKE_CASE_: Any =checkpoint[f'''blocks.{i}.convs1.{j}.1.weight_v'''] SCREAMING_SNAKE_CASE_: Union[str, Any] =checkpoint[f'''blocks.{i}.convs1.{j}.1.bias'''] SCREAMING_SNAKE_CASE_: Dict =checkpoint[f'''blocks.{i}.convs2.{j}.1.weight_g'''] SCREAMING_SNAKE_CASE_: Any =checkpoint[f'''blocks.{i}.convs2.{j}.1.weight_v'''] SCREAMING_SNAKE_CASE_: List[Any] =checkpoint[f'''blocks.{i}.convs2.{j}.1.bias'''] SCREAMING_SNAKE_CASE_: Tuple =checkpoint["""output_conv.1.weight_g"""] SCREAMING_SNAKE_CASE_: List[str] =checkpoint["""output_conv.1.weight_v"""] SCREAMING_SNAKE_CASE_: Optional[int] =checkpoint["""output_conv.1.bias"""] hf_model.remove_weight_norm() @torch.no_grad() def __magic_name__ ( lowercase , lowercase , lowercase , lowercase=None , lowercase=None , ): if config_path is not None: SCREAMING_SNAKE_CASE_: List[Any] =SpeechTaHifiGanConfig.from_pretrained(lowercase ) else: SCREAMING_SNAKE_CASE_: Optional[Any] =SpeechTaHifiGanConfig() SCREAMING_SNAKE_CASE_: Union[str, Any] =SpeechTaHifiGan(lowercase ) SCREAMING_SNAKE_CASE_: Any =torch.load(lowercase ) load_weights(orig_checkpoint["""model"""]["""generator"""] , lowercase , lowercase ) SCREAMING_SNAKE_CASE_: List[Any] =np.load(lowercase ) SCREAMING_SNAKE_CASE_: Any =stats[0].reshape(-1 ) SCREAMING_SNAKE_CASE_: str =stats[1].reshape(-1 ) SCREAMING_SNAKE_CASE_: Dict =torch.from_numpy(lowercase ).float() SCREAMING_SNAKE_CASE_: Dict =torch.from_numpy(lowercase ).float() model.save_pretrained(lowercase ) if repo_id: print("""Pushing to the hub...""" ) model.push_to_hub(lowercase ) if __name__ == "__main__": _UpperCAmelCase = argparse.ArgumentParser() parser.add_argument("""--checkpoint_path""", required=True, default=None, type=str, help="""Path to original checkpoint""") parser.add_argument("""--stats_path""", required=True, default=None, type=str, help="""Path to stats.npy file""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--pytorch_dump_folder_path""", required=True, default=None, type=str, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--push_to_hub""", default=None, type=str, help="""Where to upload the converted model on the 🤗 hub.""" ) _UpperCAmelCase = parser.parse_args() convert_hifigan_checkpoint( args.checkpoint_path, args.stats_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
36
1
"""simple docstring""" from __future__ import annotations import math import random from typing import Any class a : def __init__( self : str ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: list[Any] =[] SCREAMING_SNAKE_CASE_: int =0 SCREAMING_SNAKE_CASE_: int =0 def lowerCamelCase__ ( self : Optional[Any] ) -> bool: '''simple docstring''' return self.head == self.tail def lowerCamelCase__ ( self : Tuple , lowerCAmelCase : Any ) -> None: '''simple docstring''' self.data.append(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =self.tail + 1 def lowerCamelCase__ ( self : int ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: int =self.data[self.head] SCREAMING_SNAKE_CASE_: Optional[int] =self.head + 1 return ret def lowerCamelCase__ ( self : Optional[Any] ) -> int: '''simple docstring''' return self.tail - self.head def lowerCamelCase__ ( self : str ) -> None: '''simple docstring''' print(self.data ) print("""**************""" ) print(self.data[self.head : self.tail] ) class a : def __init__( self : Union[str, Any] , lowerCAmelCase : Any ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =data SCREAMING_SNAKE_CASE_: MyNode | None =None SCREAMING_SNAKE_CASE_: MyNode | None =None SCREAMING_SNAKE_CASE_: int =1 def lowerCamelCase__ ( self : Optional[Any] ) -> Any: '''simple docstring''' return self.data def lowerCamelCase__ ( self : List[Any] ) -> MyNode | None: '''simple docstring''' return self.left def lowerCamelCase__ ( self : Dict ) -> MyNode | None: '''simple docstring''' return self.right def lowerCamelCase__ ( self : Any ) -> int: '''simple docstring''' return self.height def lowerCamelCase__ ( self : Any , lowerCAmelCase : Any ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[Any] =data def lowerCamelCase__ ( self : Dict , lowerCAmelCase : MyNode | None ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =node def lowerCamelCase__ ( self : List[Any] , lowerCAmelCase : MyNode | None ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: str =node def lowerCamelCase__ ( self : int , lowerCAmelCase : int ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =height def __magic_name__ ( lowercase ): if node is None: return 0 return node.get_height() def __magic_name__ ( lowercase , lowercase ): if a > b: return a return b def __magic_name__ ( lowercase ): print("""left rotation node:""" , node.get_data() ) SCREAMING_SNAKE_CASE_: List[Any] =node.get_left() assert ret is not None node.set_left(ret.get_right() ) ret.set_right(lowercase ) SCREAMING_SNAKE_CASE_: Tuple =my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowercase ) SCREAMING_SNAKE_CASE_: int =my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(lowercase ) return ret def __magic_name__ ( lowercase ): print("""right rotation node:""" , node.get_data() ) SCREAMING_SNAKE_CASE_: List[Any] =node.get_right() assert ret is not None node.set_right(ret.get_left() ) ret.set_left(lowercase ) SCREAMING_SNAKE_CASE_: List[Any] =my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowercase ) SCREAMING_SNAKE_CASE_: Optional[int] =my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(lowercase ) return ret def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Any =node.get_left() assert left_child is not None node.set_left(left_rotation(lowercase ) ) return right_rotation(lowercase ) def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Dict =node.get_right() assert right_child is not None node.set_right(right_rotation(lowercase ) ) return left_rotation(lowercase ) def __magic_name__ ( lowercase , lowercase ): if node is None: return MyNode(lowercase ) if data < node.get_data(): node.set_left(insert_node(node.get_left() , lowercase ) ) if ( get_height(node.get_left() ) - get_height(node.get_right() ) == 2 ): # an unbalance detected SCREAMING_SNAKE_CASE_: Union[str, Any] =node.get_left() assert left_child is not None if ( data < left_child.get_data() ): # new node is the left child of the left child SCREAMING_SNAKE_CASE_: Any =right_rotation(lowercase ) else: SCREAMING_SNAKE_CASE_: List[Any] =lr_rotation(lowercase ) else: node.set_right(insert_node(node.get_right() , lowercase ) ) if get_height(node.get_right() ) - get_height(node.get_left() ) == 2: SCREAMING_SNAKE_CASE_: Tuple =node.get_right() assert right_child is not None if data < right_child.get_data(): SCREAMING_SNAKE_CASE_: Optional[Any] =rl_rotation(lowercase ) else: SCREAMING_SNAKE_CASE_: Optional[int] =left_rotation(lowercase ) SCREAMING_SNAKE_CASE_: Tuple =my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowercase ) return node def __magic_name__ ( lowercase ): while True: SCREAMING_SNAKE_CASE_: Dict =root.get_right() if right_child is None: break SCREAMING_SNAKE_CASE_: str =right_child return root.get_data() def __magic_name__ ( lowercase ): while True: SCREAMING_SNAKE_CASE_: str =root.get_left() if left_child is None: break SCREAMING_SNAKE_CASE_: Dict =left_child return root.get_data() def __magic_name__ ( lowercase , lowercase ): SCREAMING_SNAKE_CASE_: str =root.get_left() SCREAMING_SNAKE_CASE_: List[Any] =root.get_right() if root.get_data() == data: if left_child is not None and right_child is not None: SCREAMING_SNAKE_CASE_: Union[str, Any] =get_left_most(lowercase ) root.set_data(lowercase ) root.set_right(del_node(lowercase , lowercase ) ) elif left_child is not None: SCREAMING_SNAKE_CASE_: Optional[int] =left_child elif right_child is not None: SCREAMING_SNAKE_CASE_: Any =right_child else: return None elif root.get_data() > data: if left_child is None: print("""No such data""" ) return root else: root.set_left(del_node(lowercase , lowercase ) ) else: # root.get_data() < data if right_child is None: return root else: root.set_right(del_node(lowercase , lowercase ) ) if get_height(lowercase ) - get_height(lowercase ) == 2: assert right_child is not None if get_height(right_child.get_right() ) > get_height(right_child.get_left() ): SCREAMING_SNAKE_CASE_: Tuple =left_rotation(lowercase ) else: SCREAMING_SNAKE_CASE_: Optional[Any] =rl_rotation(lowercase ) elif get_height(lowercase ) - get_height(lowercase ) == -2: assert left_child is not None if get_height(left_child.get_left() ) > get_height(left_child.get_right() ): SCREAMING_SNAKE_CASE_: Optional[Any] =right_rotation(lowercase ) else: SCREAMING_SNAKE_CASE_: str =lr_rotation(lowercase ) SCREAMING_SNAKE_CASE_: str =my_max(get_height(root.get_right() ) , get_height(root.get_left() ) ) + 1 root.set_height(lowercase ) return root class a : def __init__( self : int ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: MyNode | None =None def lowerCamelCase__ ( self : List[Any] ) -> int: '''simple docstring''' return get_height(self.root ) def lowerCamelCase__ ( self : Optional[int] , lowerCAmelCase : Any ) -> None: '''simple docstring''' print("""insert:""" + str(lowerCAmelCase ) ) SCREAMING_SNAKE_CASE_: Tuple =insert_node(self.root , lowerCAmelCase ) def lowerCamelCase__ ( self : List[Any] , lowerCAmelCase : Any ) -> None: '''simple docstring''' print("""delete:""" + str(lowerCAmelCase ) ) if self.root is None: print("""Tree is empty!""" ) return SCREAMING_SNAKE_CASE_: Union[str, Any] =del_node(self.root , lowerCAmelCase ) def __str__( self : List[str] , ) -> str: # a level traversale, gives a more intuitive look on the tree '''simple docstring''' SCREAMING_SNAKE_CASE_: List[Any] ="""""" SCREAMING_SNAKE_CASE_: str =MyQueue() q.push(self.root ) SCREAMING_SNAKE_CASE_: List[str] =self.get_height() if layer == 0: return output SCREAMING_SNAKE_CASE_: int =0 while not q.is_empty(): SCREAMING_SNAKE_CASE_: int =q.pop() SCREAMING_SNAKE_CASE_: List[Any] =""" """ * int(math.pow(2 , layer - 1 ) ) output += space if node is None: output += "*" q.push(lowerCAmelCase ) q.push(lowerCAmelCase ) else: output += str(node.get_data() ) q.push(node.get_left() ) q.push(node.get_right() ) output += space SCREAMING_SNAKE_CASE_: List[Any] =cnt + 1 for i in range(100 ): if cnt == math.pow(2 , lowerCAmelCase ) - 1: SCREAMING_SNAKE_CASE_: int =layer - 1 if layer == 0: output += "\n*************************************" return output output += "\n" break output += "\n*************************************" return output def __magic_name__ ( ): import doctest doctest.testmod() if __name__ == "__main__": _test() _UpperCAmelCase = AVLtree() _UpperCAmelCase = list(range(1_0)) random.shuffle(lst) for i in lst: t.insert(i) print(str(t)) random.shuffle(lst) for i in lst: t.del_node(i) print(str(t))
36
"""simple docstring""" import argparse import requests import torch from PIL import Image from transformers import ViTMAEConfig, ViTMAEForPreTraining, ViTMAEImageProcessor def __magic_name__ ( lowercase ): if "cls_token" in name: SCREAMING_SNAKE_CASE_: Optional[int] =name.replace("""cls_token""" , """vit.embeddings.cls_token""" ) if "mask_token" in name: SCREAMING_SNAKE_CASE_: Optional[int] =name.replace("""mask_token""" , """decoder.mask_token""" ) if "decoder_pos_embed" in name: SCREAMING_SNAKE_CASE_: int =name.replace("""decoder_pos_embed""" , """decoder.decoder_pos_embed""" ) if "pos_embed" in name and "decoder" not in name: SCREAMING_SNAKE_CASE_: str =name.replace("""pos_embed""" , """vit.embeddings.position_embeddings""" ) if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE_: str =name.replace("""patch_embed.proj""" , """vit.embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: SCREAMING_SNAKE_CASE_: int =name.replace("""patch_embed.norm""" , """vit.embeddings.norm""" ) if "decoder_blocks" in name: SCREAMING_SNAKE_CASE_: List[Any] =name.replace("""decoder_blocks""" , """decoder.decoder_layers""" ) if "blocks" in name: SCREAMING_SNAKE_CASE_: str =name.replace("""blocks""" , """vit.encoder.layer""" ) if "attn.proj" in name: SCREAMING_SNAKE_CASE_: Optional[Any] =name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: SCREAMING_SNAKE_CASE_: Union[str, Any] =name.replace("""attn""" , """attention.self""" ) if "norm1" in name: SCREAMING_SNAKE_CASE_: Optional[Any] =name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: SCREAMING_SNAKE_CASE_: int =name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE_: int =name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE_: Dict =name.replace("""mlp.fc2""" , """output.dense""" ) if "decoder_embed" in name: SCREAMING_SNAKE_CASE_: List[str] =name.replace("""decoder_embed""" , """decoder.decoder_embed""" ) if "decoder_norm" in name: SCREAMING_SNAKE_CASE_: Tuple =name.replace("""decoder_norm""" , """decoder.decoder_norm""" ) if "decoder_pred" in name: SCREAMING_SNAKE_CASE_: Any =name.replace("""decoder_pred""" , """decoder.decoder_pred""" ) if "norm.weight" in name and "decoder" not in name: SCREAMING_SNAKE_CASE_: List[str] =name.replace("""norm.weight""" , """vit.layernorm.weight""" ) if "norm.bias" in name and "decoder" not in name: SCREAMING_SNAKE_CASE_: List[str] =name.replace("""norm.bias""" , """vit.layernorm.bias""" ) return name def __magic_name__ ( lowercase , lowercase ): for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE_: Optional[int] =orig_state_dict.pop(lowercase ) if "qkv" in key: SCREAMING_SNAKE_CASE_: Dict =key.split(""".""" ) SCREAMING_SNAKE_CASE_: Optional[Any] =int(key_split[1] ) if "decoder_blocks" in key: SCREAMING_SNAKE_CASE_: int =config.decoder_hidden_size SCREAMING_SNAKE_CASE_: Optional[int] ="""decoder.decoder_layers.""" if "weight" in key: SCREAMING_SNAKE_CASE_: Dict =val[:dim, :] SCREAMING_SNAKE_CASE_: Tuple =val[dim : dim * 2, :] SCREAMING_SNAKE_CASE_: str =val[-dim:, :] elif "bias" in key: SCREAMING_SNAKE_CASE_: List[Any] =val[:dim] SCREAMING_SNAKE_CASE_: Tuple =val[dim : dim * 2] SCREAMING_SNAKE_CASE_: List[Any] =val[-dim:] else: SCREAMING_SNAKE_CASE_: Any =config.hidden_size SCREAMING_SNAKE_CASE_: Union[str, Any] ="""vit.encoder.layer.""" if "weight" in key: SCREAMING_SNAKE_CASE_: Optional[Any] =val[:dim, :] SCREAMING_SNAKE_CASE_: Optional[Any] =val[dim : dim * 2, :] SCREAMING_SNAKE_CASE_: Dict =val[-dim:, :] elif "bias" in key: SCREAMING_SNAKE_CASE_: Optional[Any] =val[:dim] SCREAMING_SNAKE_CASE_: Any =val[dim : dim * 2] SCREAMING_SNAKE_CASE_: Optional[Any] =val[-dim:] else: SCREAMING_SNAKE_CASE_: Tuple =val return orig_state_dict def __magic_name__ ( lowercase , lowercase ): SCREAMING_SNAKE_CASE_: Dict =ViTMAEConfig() if "large" in checkpoint_url: SCREAMING_SNAKE_CASE_: List[Any] =1024 SCREAMING_SNAKE_CASE_: Dict =4096 SCREAMING_SNAKE_CASE_: Tuple =24 SCREAMING_SNAKE_CASE_: int =16 elif "huge" in checkpoint_url: SCREAMING_SNAKE_CASE_: Union[str, Any] =14 SCREAMING_SNAKE_CASE_: Any =1280 SCREAMING_SNAKE_CASE_: Dict =5120 SCREAMING_SNAKE_CASE_: Optional[int] =32 SCREAMING_SNAKE_CASE_: Optional[Any] =16 SCREAMING_SNAKE_CASE_: Tuple =ViTMAEForPreTraining(lowercase ) SCREAMING_SNAKE_CASE_: Optional[int] =torch.hub.load_state_dict_from_url(lowercase , map_location="""cpu""" )["""model"""] SCREAMING_SNAKE_CASE_: Optional[Any] =ViTMAEImageProcessor(size=config.image_size ) SCREAMING_SNAKE_CASE_: str =convert_state_dict(lowercase , lowercase ) model.load_state_dict(lowercase ) model.eval() SCREAMING_SNAKE_CASE_: Tuple ="""https://user-images.githubusercontent.com/11435359/147738734-196fd92f-9260-48d5-ba7e-bf103d29364d.jpg""" SCREAMING_SNAKE_CASE_: List[Any] =Image.open(requests.get(lowercase , stream=lowercase ).raw ) SCREAMING_SNAKE_CASE_: int =ViTMAEImageProcessor(size=config.image_size ) SCREAMING_SNAKE_CASE_: int =image_processor(images=lowercase , return_tensors="""pt""" ) # forward pass torch.manual_seed(2 ) SCREAMING_SNAKE_CASE_: Optional[Any] =model(**lowercase ) SCREAMING_SNAKE_CASE_: Optional[int] =outputs.logits if "large" in checkpoint_url: SCREAMING_SNAKE_CASE_: Dict =torch.tensor( [[-0.7_309, -0.7_128, -1.0_169], [-1.0_161, -0.9_058, -1.1_878], [-1.0_478, -0.9_411, -1.1_911]] ) elif "huge" in checkpoint_url: SCREAMING_SNAKE_CASE_: Tuple =torch.tensor( [[-1.1_599, -0.9_199, -1.2_221], [-1.1_952, -0.9_269, -1.2_307], [-1.2_143, -0.9_337, -1.2_262]] ) else: SCREAMING_SNAKE_CASE_: Any =torch.tensor( [[-0.9_192, -0.8_481, -1.1_259], [-1.1_349, -1.0_034, -1.2_599], [-1.1_757, -1.0_429, -1.2_726]] ) # verify logits assert torch.allclose(logits[0, :3, :3] , lowercase , atol=1e-4 ) print(f'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowercase ) if __name__ == "__main__": _UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--checkpoint_url""", default="""https://dl.fbaipublicfiles.com/mae/visualize/mae_visualize_vit_base.pth""", type=str, help="""URL of the checkpoint you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) _UpperCAmelCase = parser.parse_args() convert_vit_mae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
36
1
"""simple docstring""" def __magic_name__ ( lowercase ): if len(lowercase ) <= 1: return lst SCREAMING_SNAKE_CASE_: List[str] =1 while i < len(lowercase ): if lst[i - 1] <= lst[i]: i += 1 else: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[int] =lst[i], lst[i - 1] i -= 1 if i == 0: SCREAMING_SNAKE_CASE_: Tuple =1 return lst if __name__ == "__main__": _UpperCAmelCase = input("""Enter numbers separated by a comma:\n""").strip() _UpperCAmelCase = [int(item) for item in user_input.split(""",""")] print(gnome_sort(unsorted))
36
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _UpperCAmelCase = { """configuration_xlm""": ["""XLM_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XLMConfig""", """XLMOnnxConfig"""], """tokenization_xlm""": ["""XLMTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ """XLM_PRETRAINED_MODEL_ARCHIVE_LIST""", """XLMForMultipleChoice""", """XLMForQuestionAnswering""", """XLMForQuestionAnsweringSimple""", """XLMForSequenceClassification""", """XLMForTokenClassification""", """XLMModel""", """XLMPreTrainedModel""", """XLMWithLMHeadModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ """TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFXLMForMultipleChoice""", """TFXLMForQuestionAnsweringSimple""", """TFXLMForSequenceClassification""", """TFXLMForTokenClassification""", """TFXLMMainLayer""", """TFXLMModel""", """TFXLMPreTrainedModel""", """TFXLMWithLMHeadModel""", ] if TYPE_CHECKING: from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig from .tokenization_xlm import XLMTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm import ( XLM_PRETRAINED_MODEL_ARCHIVE_LIST, XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMPreTrainedModel, XLMWithLMHeadModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm import ( TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMForMultipleChoice, TFXLMForQuestionAnsweringSimple, TFXLMForSequenceClassification, TFXLMForTokenClassification, TFXLMMainLayer, TFXLMModel, TFXLMPreTrainedModel, TFXLMWithLMHeadModel, ) else: import sys _UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
36
1
"""simple docstring""" import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device _UpperCAmelCase = False class a ( unittest.TestCase ): pass @slow @require_torch_gpu class a ( unittest.TestCase ): def lowerCamelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[Any] =VersatileDiffusionImageVariationPipeline.from_pretrained("""shi-labs/versatile-diffusion""" ) pipe.to(lowerCAmelCase ) pipe.set_progress_bar_config(disable=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: str =load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg""" ) SCREAMING_SNAKE_CASE_: Optional[int] =torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_: Dict =pipe( image=lowerCAmelCase , generator=lowerCAmelCase , guidance_scale=7.5 , num_inference_steps=50 , output_type="""numpy""" , ).images SCREAMING_SNAKE_CASE_: int =image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_: Tuple =np.array([0.0_4_4_1, 0.0_4_6_9, 0.0_5_0_7, 0.0_5_7_5, 0.0_6_3_2, 0.0_6_5_0, 0.0_8_6_5, 0.0_9_0_9, 0.0_9_4_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
36
"""simple docstring""" def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: int =False while is_sorted is False: # Until all the indices are traversed keep looping SCREAMING_SNAKE_CASE_: Tuple =True for i in range(0 , len(lowercase ) - 1 , 2 ): # iterating over all even indices if input_list[i] > input_list[i + 1]: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[int] =input_list[i + 1], input_list[i] # swapping if elements not in order SCREAMING_SNAKE_CASE_: Tuple =False for i in range(1 , len(lowercase ) - 1 , 2 ): # iterating over all odd indices if input_list[i] > input_list[i + 1]: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: str =input_list[i + 1], input_list[i] # swapping if elements not in order SCREAMING_SNAKE_CASE_: str =False return input_list if __name__ == "__main__": print("""Enter list to be sorted""") _UpperCAmelCase = [int(x) for x in input().split()] # inputing elements of the list in one line _UpperCAmelCase = odd_even_sort(input_list) print("""The sorted list is""") print(sorted_list)
36
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { """shi-labs/nat-mini-in1k-224""": """https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json""", # See all Nat models at https://huggingface.co/models?filter=nat } class a ( UpperCAmelCase__ , UpperCAmelCase__ ): UpperCamelCase : List[Any] = 'nat' UpperCamelCase : Optional[Any] = { 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers', } def __init__( self : Optional[Any] , lowerCAmelCase : Optional[int]=4 , lowerCAmelCase : int=3 , lowerCAmelCase : Any=64 , lowerCAmelCase : Union[str, Any]=[3, 4, 6, 5] , lowerCAmelCase : Optional[Any]=[2, 4, 8, 16] , lowerCAmelCase : Any=7 , lowerCAmelCase : int=3.0 , lowerCAmelCase : Optional[int]=True , lowerCAmelCase : Optional[int]=0.0 , lowerCAmelCase : int=0.0 , lowerCAmelCase : List[Any]=0.1 , lowerCAmelCase : Dict="gelu" , lowerCAmelCase : Dict=0.0_2 , lowerCAmelCase : Optional[Any]=1E-5 , lowerCAmelCase : str=0.0 , lowerCAmelCase : Dict=None , lowerCAmelCase : Dict=None , **lowerCAmelCase : str , ) -> Any: '''simple docstring''' super().__init__(**lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Dict =patch_size SCREAMING_SNAKE_CASE_: Any =num_channels SCREAMING_SNAKE_CASE_: List[Any] =embed_dim SCREAMING_SNAKE_CASE_: List[str] =depths SCREAMING_SNAKE_CASE_: str =len(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =num_heads SCREAMING_SNAKE_CASE_: List[str] =kernel_size SCREAMING_SNAKE_CASE_: Dict =mlp_ratio SCREAMING_SNAKE_CASE_: Tuple =qkv_bias SCREAMING_SNAKE_CASE_: Any =hidden_dropout_prob SCREAMING_SNAKE_CASE_: List[Any] =attention_probs_dropout_prob SCREAMING_SNAKE_CASE_: List[str] =drop_path_rate SCREAMING_SNAKE_CASE_: List[Any] =hidden_act SCREAMING_SNAKE_CASE_: Union[str, Any] =layer_norm_eps SCREAMING_SNAKE_CASE_: Optional[int] =initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model SCREAMING_SNAKE_CASE_: List[str] =int(embed_dim * 2 ** (len(lowerCAmelCase ) - 1) ) SCREAMING_SNAKE_CASE_: Any =layer_scale_init_value SCREAMING_SNAKE_CASE_: Any =["""stem"""] + [f'''stage{idx}''' for idx in range(1 , len(lowerCAmelCase ) + 1 )] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[int] =get_aligned_output_features_output_indices( out_features=lowerCAmelCase , out_indices=lowerCAmelCase , stage_names=self.stage_names )
36
"""simple docstring""" def __magic_name__ ( lowercase ): return str(lowercase ) == str(lowercase )[::-1] def __magic_name__ ( lowercase ): return int(lowercase ) + int(str(lowercase )[::-1] ) def __magic_name__ ( lowercase = 1_0000 ): SCREAMING_SNAKE_CASE_: List[str] =[] for num in range(1 , lowercase ): SCREAMING_SNAKE_CASE_: List[Any] =0 SCREAMING_SNAKE_CASE_: int =num while iterations < 50: SCREAMING_SNAKE_CASE_: Optional[Any] =sum_reverse(lowercase ) iterations += 1 if is_palindrome(lowercase ): break else: lychrel_nums.append(lowercase ) return len(lowercase ) if __name__ == "__main__": print(f"""{solution() = }""")
36
1
"""simple docstring""" import fire from transformers import AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer def __magic_name__ ( lowercase , lowercase , **lowercase ): SCREAMING_SNAKE_CASE_: Optional[Any] =AutoConfig.from_pretrained(lowercase , **lowercase ) SCREAMING_SNAKE_CASE_: Optional[int] =AutoModelForSeqaSeqLM.from_config(lowercase ) model.save_pretrained(lowercase ) AutoTokenizer.from_pretrained(lowercase ).save_pretrained(lowercase ) return model if __name__ == "__main__": fire.Fire(save_randomly_initialized_version)
36
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available from ...utils import OptionalDependencyNotAvailable _UpperCAmelCase = {"""configuration_dpt""": ["""DPT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """DPTConfig"""]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = ["""DPTFeatureExtractor"""] _UpperCAmelCase = ["""DPTImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ """DPT_PRETRAINED_MODEL_ARCHIVE_LIST""", """DPTForDepthEstimation""", """DPTForSemanticSegmentation""", """DPTModel""", """DPTPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_dpt import DPTFeatureExtractor from .image_processing_dpt import DPTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dpt import ( DPT_PRETRAINED_MODEL_ARCHIVE_LIST, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel, DPTPreTrainedModel, ) else: import sys _UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
36
1
"""simple docstring""" import os import pytest from transformers.dynamic_module_utils import get_imports _UpperCAmelCase = """ import os """ _UpperCAmelCase = """ def foo(): import os return False """ _UpperCAmelCase = """ def foo(): def bar(): if True: import os return False return bar() """ _UpperCAmelCase = """ import os try: import bar except ImportError: raise ValueError() """ _UpperCAmelCase = """ import os def foo(): try: import bar except ImportError: raise ValueError() """ _UpperCAmelCase = """ import os try: import bar except (ImportError, AttributeError): raise ValueError() """ _UpperCAmelCase = """ import os try: import bar except ImportError as e: raise ValueError() """ _UpperCAmelCase = """ import os try: import bar except: raise ValueError() """ _UpperCAmelCase = """ import os try: import bar import baz except ImportError: raise ValueError() """ _UpperCAmelCase = """ import os try: import bar import baz except ImportError: x = 1 raise ValueError() """ _UpperCAmelCase = [ TOP_LEVEL_IMPORT, IMPORT_IN_FUNCTION, DEEPLY_NESTED_IMPORT, TOP_LEVEL_TRY_IMPORT, GENERIC_EXCEPT_IMPORT, MULTILINE_TRY_IMPORT, MULTILINE_BOTH_IMPORT, MULTIPLE_EXCEPTS_IMPORT, EXCEPT_AS_IMPORT, TRY_IMPORT_IN_FUNCTION, ] @pytest.mark.parametrize("""case""" , lowercase ) def __magic_name__ ( lowercase , lowercase ): SCREAMING_SNAKE_CASE_: Union[str, Any] =os.path.join(lowercase , """test_file.py""" ) with open(lowercase , """w""" ) as _tmp_file: _tmp_file.write(lowercase ) SCREAMING_SNAKE_CASE_: Any =get_imports(lowercase ) assert parsed_imports == ["os"]
36
"""simple docstring""" from __future__ import annotations import math import random from typing import Any class a : def __init__( self : str ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: list[Any] =[] SCREAMING_SNAKE_CASE_: int =0 SCREAMING_SNAKE_CASE_: int =0 def lowerCamelCase__ ( self : Optional[Any] ) -> bool: '''simple docstring''' return self.head == self.tail def lowerCamelCase__ ( self : Tuple , lowerCAmelCase : Any ) -> None: '''simple docstring''' self.data.append(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =self.tail + 1 def lowerCamelCase__ ( self : int ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: int =self.data[self.head] SCREAMING_SNAKE_CASE_: Optional[int] =self.head + 1 return ret def lowerCamelCase__ ( self : Optional[Any] ) -> int: '''simple docstring''' return self.tail - self.head def lowerCamelCase__ ( self : str ) -> None: '''simple docstring''' print(self.data ) print("""**************""" ) print(self.data[self.head : self.tail] ) class a : def __init__( self : Union[str, Any] , lowerCAmelCase : Any ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =data SCREAMING_SNAKE_CASE_: MyNode | None =None SCREAMING_SNAKE_CASE_: MyNode | None =None SCREAMING_SNAKE_CASE_: int =1 def lowerCamelCase__ ( self : Optional[Any] ) -> Any: '''simple docstring''' return self.data def lowerCamelCase__ ( self : List[Any] ) -> MyNode | None: '''simple docstring''' return self.left def lowerCamelCase__ ( self : Dict ) -> MyNode | None: '''simple docstring''' return self.right def lowerCamelCase__ ( self : Any ) -> int: '''simple docstring''' return self.height def lowerCamelCase__ ( self : Any , lowerCAmelCase : Any ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[Any] =data def lowerCamelCase__ ( self : Dict , lowerCAmelCase : MyNode | None ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =node def lowerCamelCase__ ( self : List[Any] , lowerCAmelCase : MyNode | None ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: str =node def lowerCamelCase__ ( self : int , lowerCAmelCase : int ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =height def __magic_name__ ( lowercase ): if node is None: return 0 return node.get_height() def __magic_name__ ( lowercase , lowercase ): if a > b: return a return b def __magic_name__ ( lowercase ): print("""left rotation node:""" , node.get_data() ) SCREAMING_SNAKE_CASE_: List[Any] =node.get_left() assert ret is not None node.set_left(ret.get_right() ) ret.set_right(lowercase ) SCREAMING_SNAKE_CASE_: Tuple =my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowercase ) SCREAMING_SNAKE_CASE_: int =my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(lowercase ) return ret def __magic_name__ ( lowercase ): print("""right rotation node:""" , node.get_data() ) SCREAMING_SNAKE_CASE_: List[Any] =node.get_right() assert ret is not None node.set_right(ret.get_left() ) ret.set_left(lowercase ) SCREAMING_SNAKE_CASE_: List[Any] =my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowercase ) SCREAMING_SNAKE_CASE_: Optional[int] =my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(lowercase ) return ret def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Any =node.get_left() assert left_child is not None node.set_left(left_rotation(lowercase ) ) return right_rotation(lowercase ) def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Dict =node.get_right() assert right_child is not None node.set_right(right_rotation(lowercase ) ) return left_rotation(lowercase ) def __magic_name__ ( lowercase , lowercase ): if node is None: return MyNode(lowercase ) if data < node.get_data(): node.set_left(insert_node(node.get_left() , lowercase ) ) if ( get_height(node.get_left() ) - get_height(node.get_right() ) == 2 ): # an unbalance detected SCREAMING_SNAKE_CASE_: Union[str, Any] =node.get_left() assert left_child is not None if ( data < left_child.get_data() ): # new node is the left child of the left child SCREAMING_SNAKE_CASE_: Any =right_rotation(lowercase ) else: SCREAMING_SNAKE_CASE_: List[Any] =lr_rotation(lowercase ) else: node.set_right(insert_node(node.get_right() , lowercase ) ) if get_height(node.get_right() ) - get_height(node.get_left() ) == 2: SCREAMING_SNAKE_CASE_: Tuple =node.get_right() assert right_child is not None if data < right_child.get_data(): SCREAMING_SNAKE_CASE_: Optional[Any] =rl_rotation(lowercase ) else: SCREAMING_SNAKE_CASE_: Optional[int] =left_rotation(lowercase ) SCREAMING_SNAKE_CASE_: Tuple =my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowercase ) return node def __magic_name__ ( lowercase ): while True: SCREAMING_SNAKE_CASE_: Dict =root.get_right() if right_child is None: break SCREAMING_SNAKE_CASE_: str =right_child return root.get_data() def __magic_name__ ( lowercase ): while True: SCREAMING_SNAKE_CASE_: str =root.get_left() if left_child is None: break SCREAMING_SNAKE_CASE_: Dict =left_child return root.get_data() def __magic_name__ ( lowercase , lowercase ): SCREAMING_SNAKE_CASE_: str =root.get_left() SCREAMING_SNAKE_CASE_: List[Any] =root.get_right() if root.get_data() == data: if left_child is not None and right_child is not None: SCREAMING_SNAKE_CASE_: Union[str, Any] =get_left_most(lowercase ) root.set_data(lowercase ) root.set_right(del_node(lowercase , lowercase ) ) elif left_child is not None: SCREAMING_SNAKE_CASE_: Optional[int] =left_child elif right_child is not None: SCREAMING_SNAKE_CASE_: Any =right_child else: return None elif root.get_data() > data: if left_child is None: print("""No such data""" ) return root else: root.set_left(del_node(lowercase , lowercase ) ) else: # root.get_data() < data if right_child is None: return root else: root.set_right(del_node(lowercase , lowercase ) ) if get_height(lowercase ) - get_height(lowercase ) == 2: assert right_child is not None if get_height(right_child.get_right() ) > get_height(right_child.get_left() ): SCREAMING_SNAKE_CASE_: Tuple =left_rotation(lowercase ) else: SCREAMING_SNAKE_CASE_: Optional[Any] =rl_rotation(lowercase ) elif get_height(lowercase ) - get_height(lowercase ) == -2: assert left_child is not None if get_height(left_child.get_left() ) > get_height(left_child.get_right() ): SCREAMING_SNAKE_CASE_: Optional[Any] =right_rotation(lowercase ) else: SCREAMING_SNAKE_CASE_: str =lr_rotation(lowercase ) SCREAMING_SNAKE_CASE_: str =my_max(get_height(root.get_right() ) , get_height(root.get_left() ) ) + 1 root.set_height(lowercase ) return root class a : def __init__( self : int ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: MyNode | None =None def lowerCamelCase__ ( self : List[Any] ) -> int: '''simple docstring''' return get_height(self.root ) def lowerCamelCase__ ( self : Optional[int] , lowerCAmelCase : Any ) -> None: '''simple docstring''' print("""insert:""" + str(lowerCAmelCase ) ) SCREAMING_SNAKE_CASE_: Tuple =insert_node(self.root , lowerCAmelCase ) def lowerCamelCase__ ( self : List[Any] , lowerCAmelCase : Any ) -> None: '''simple docstring''' print("""delete:""" + str(lowerCAmelCase ) ) if self.root is None: print("""Tree is empty!""" ) return SCREAMING_SNAKE_CASE_: Union[str, Any] =del_node(self.root , lowerCAmelCase ) def __str__( self : List[str] , ) -> str: # a level traversale, gives a more intuitive look on the tree '''simple docstring''' SCREAMING_SNAKE_CASE_: List[Any] ="""""" SCREAMING_SNAKE_CASE_: str =MyQueue() q.push(self.root ) SCREAMING_SNAKE_CASE_: List[str] =self.get_height() if layer == 0: return output SCREAMING_SNAKE_CASE_: int =0 while not q.is_empty(): SCREAMING_SNAKE_CASE_: int =q.pop() SCREAMING_SNAKE_CASE_: List[Any] =""" """ * int(math.pow(2 , layer - 1 ) ) output += space if node is None: output += "*" q.push(lowerCAmelCase ) q.push(lowerCAmelCase ) else: output += str(node.get_data() ) q.push(node.get_left() ) q.push(node.get_right() ) output += space SCREAMING_SNAKE_CASE_: List[Any] =cnt + 1 for i in range(100 ): if cnt == math.pow(2 , lowerCAmelCase ) - 1: SCREAMING_SNAKE_CASE_: int =layer - 1 if layer == 0: output += "\n*************************************" return output output += "\n" break output += "\n*************************************" return output def __magic_name__ ( ): import doctest doctest.testmod() if __name__ == "__main__": _test() _UpperCAmelCase = AVLtree() _UpperCAmelCase = list(range(1_0)) random.shuffle(lst) for i in lst: t.insert(i) print(str(t)) random.shuffle(lst) for i in lst: t.del_node(i) print(str(t))
36
1
"""simple docstring""" _UpperCAmelCase = """ # Transformers installation ! pip install transformers datasets # To install from source instead of the last release, comment the command above and uncomment the following one. # ! pip install git+https://github.com/huggingface/transformers.git """ _UpperCAmelCase = [{"""type""": """code""", """content""": INSTALL_CONTENT}] _UpperCAmelCase = { """{processor_class}""": """FakeProcessorClass""", """{model_class}""": """FakeModelClass""", """{object_class}""": """FakeObjectClass""", }
36
"""simple docstring""" import string def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: List[Any] ="""""" for i in sequence: SCREAMING_SNAKE_CASE_: List[Any] =ord(lowercase ) if 65 <= extract <= 90: output += chr(155 - extract ) elif 97 <= extract <= 122: output += chr(219 - extract ) else: output += i return output def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Any =string.ascii_letters SCREAMING_SNAKE_CASE_: Tuple =string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1] return "".join( letters_reversed[letters.index(lowercase )] if c in letters else c for c in sequence ) def __magic_name__ ( ): from timeit import timeit print("""Running performance benchmarks...""" ) SCREAMING_SNAKE_CASE_: int ="""from string import printable ; from __main__ import atbash, atbash_slow""" print(f'''> atbash_slow(): {timeit("atbash_slow(printable)" , setup=lowercase )} seconds''' ) print(f'''> atbash(): {timeit("atbash(printable)" , setup=lowercase )} seconds''' ) if __name__ == "__main__": for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"): print(f"""{example} encrypted in atbash: {atbash(example)}""") benchmark()
36
1
"""simple docstring""" import argparse import requests import torch from PIL import Image from transformers import ViTMAEConfig, ViTMAEForPreTraining, ViTMAEImageProcessor def __magic_name__ ( lowercase ): if "cls_token" in name: SCREAMING_SNAKE_CASE_: Optional[int] =name.replace("""cls_token""" , """vit.embeddings.cls_token""" ) if "mask_token" in name: SCREAMING_SNAKE_CASE_: Optional[int] =name.replace("""mask_token""" , """decoder.mask_token""" ) if "decoder_pos_embed" in name: SCREAMING_SNAKE_CASE_: int =name.replace("""decoder_pos_embed""" , """decoder.decoder_pos_embed""" ) if "pos_embed" in name and "decoder" not in name: SCREAMING_SNAKE_CASE_: str =name.replace("""pos_embed""" , """vit.embeddings.position_embeddings""" ) if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE_: str =name.replace("""patch_embed.proj""" , """vit.embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: SCREAMING_SNAKE_CASE_: int =name.replace("""patch_embed.norm""" , """vit.embeddings.norm""" ) if "decoder_blocks" in name: SCREAMING_SNAKE_CASE_: List[Any] =name.replace("""decoder_blocks""" , """decoder.decoder_layers""" ) if "blocks" in name: SCREAMING_SNAKE_CASE_: str =name.replace("""blocks""" , """vit.encoder.layer""" ) if "attn.proj" in name: SCREAMING_SNAKE_CASE_: Optional[Any] =name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: SCREAMING_SNAKE_CASE_: Union[str, Any] =name.replace("""attn""" , """attention.self""" ) if "norm1" in name: SCREAMING_SNAKE_CASE_: Optional[Any] =name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: SCREAMING_SNAKE_CASE_: int =name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE_: int =name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE_: Dict =name.replace("""mlp.fc2""" , """output.dense""" ) if "decoder_embed" in name: SCREAMING_SNAKE_CASE_: List[str] =name.replace("""decoder_embed""" , """decoder.decoder_embed""" ) if "decoder_norm" in name: SCREAMING_SNAKE_CASE_: Tuple =name.replace("""decoder_norm""" , """decoder.decoder_norm""" ) if "decoder_pred" in name: SCREAMING_SNAKE_CASE_: Any =name.replace("""decoder_pred""" , """decoder.decoder_pred""" ) if "norm.weight" in name and "decoder" not in name: SCREAMING_SNAKE_CASE_: List[str] =name.replace("""norm.weight""" , """vit.layernorm.weight""" ) if "norm.bias" in name and "decoder" not in name: SCREAMING_SNAKE_CASE_: List[str] =name.replace("""norm.bias""" , """vit.layernorm.bias""" ) return name def __magic_name__ ( lowercase , lowercase ): for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE_: Optional[int] =orig_state_dict.pop(lowercase ) if "qkv" in key: SCREAMING_SNAKE_CASE_: Dict =key.split(""".""" ) SCREAMING_SNAKE_CASE_: Optional[Any] =int(key_split[1] ) if "decoder_blocks" in key: SCREAMING_SNAKE_CASE_: int =config.decoder_hidden_size SCREAMING_SNAKE_CASE_: Optional[int] ="""decoder.decoder_layers.""" if "weight" in key: SCREAMING_SNAKE_CASE_: Dict =val[:dim, :] SCREAMING_SNAKE_CASE_: Tuple =val[dim : dim * 2, :] SCREAMING_SNAKE_CASE_: str =val[-dim:, :] elif "bias" in key: SCREAMING_SNAKE_CASE_: List[Any] =val[:dim] SCREAMING_SNAKE_CASE_: Tuple =val[dim : dim * 2] SCREAMING_SNAKE_CASE_: List[Any] =val[-dim:] else: SCREAMING_SNAKE_CASE_: Any =config.hidden_size SCREAMING_SNAKE_CASE_: Union[str, Any] ="""vit.encoder.layer.""" if "weight" in key: SCREAMING_SNAKE_CASE_: Optional[Any] =val[:dim, :] SCREAMING_SNAKE_CASE_: Optional[Any] =val[dim : dim * 2, :] SCREAMING_SNAKE_CASE_: Dict =val[-dim:, :] elif "bias" in key: SCREAMING_SNAKE_CASE_: Optional[Any] =val[:dim] SCREAMING_SNAKE_CASE_: Any =val[dim : dim * 2] SCREAMING_SNAKE_CASE_: Optional[Any] =val[-dim:] else: SCREAMING_SNAKE_CASE_: Tuple =val return orig_state_dict def __magic_name__ ( lowercase , lowercase ): SCREAMING_SNAKE_CASE_: Dict =ViTMAEConfig() if "large" in checkpoint_url: SCREAMING_SNAKE_CASE_: List[Any] =1024 SCREAMING_SNAKE_CASE_: Dict =4096 SCREAMING_SNAKE_CASE_: Tuple =24 SCREAMING_SNAKE_CASE_: int =16 elif "huge" in checkpoint_url: SCREAMING_SNAKE_CASE_: Union[str, Any] =14 SCREAMING_SNAKE_CASE_: Any =1280 SCREAMING_SNAKE_CASE_: Dict =5120 SCREAMING_SNAKE_CASE_: Optional[int] =32 SCREAMING_SNAKE_CASE_: Optional[Any] =16 SCREAMING_SNAKE_CASE_: Tuple =ViTMAEForPreTraining(lowercase ) SCREAMING_SNAKE_CASE_: Optional[int] =torch.hub.load_state_dict_from_url(lowercase , map_location="""cpu""" )["""model"""] SCREAMING_SNAKE_CASE_: Optional[Any] =ViTMAEImageProcessor(size=config.image_size ) SCREAMING_SNAKE_CASE_: str =convert_state_dict(lowercase , lowercase ) model.load_state_dict(lowercase ) model.eval() SCREAMING_SNAKE_CASE_: Tuple ="""https://user-images.githubusercontent.com/11435359/147738734-196fd92f-9260-48d5-ba7e-bf103d29364d.jpg""" SCREAMING_SNAKE_CASE_: List[Any] =Image.open(requests.get(lowercase , stream=lowercase ).raw ) SCREAMING_SNAKE_CASE_: int =ViTMAEImageProcessor(size=config.image_size ) SCREAMING_SNAKE_CASE_: int =image_processor(images=lowercase , return_tensors="""pt""" ) # forward pass torch.manual_seed(2 ) SCREAMING_SNAKE_CASE_: Optional[Any] =model(**lowercase ) SCREAMING_SNAKE_CASE_: Optional[int] =outputs.logits if "large" in checkpoint_url: SCREAMING_SNAKE_CASE_: Dict =torch.tensor( [[-0.7_309, -0.7_128, -1.0_169], [-1.0_161, -0.9_058, -1.1_878], [-1.0_478, -0.9_411, -1.1_911]] ) elif "huge" in checkpoint_url: SCREAMING_SNAKE_CASE_: Tuple =torch.tensor( [[-1.1_599, -0.9_199, -1.2_221], [-1.1_952, -0.9_269, -1.2_307], [-1.2_143, -0.9_337, -1.2_262]] ) else: SCREAMING_SNAKE_CASE_: Any =torch.tensor( [[-0.9_192, -0.8_481, -1.1_259], [-1.1_349, -1.0_034, -1.2_599], [-1.1_757, -1.0_429, -1.2_726]] ) # verify logits assert torch.allclose(logits[0, :3, :3] , lowercase , atol=1e-4 ) print(f'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowercase ) if __name__ == "__main__": _UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--checkpoint_url""", default="""https://dl.fbaipublicfiles.com/mae/visualize/mae_visualize_vit_base.pth""", type=str, help="""URL of the checkpoint you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) _UpperCAmelCase = parser.parse_args() convert_vit_mae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
36
"""simple docstring""" import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class a : def __init__( self : Union[str, Any] , lowerCAmelCase : List[str]=2 , lowerCAmelCase : int=3 , lowerCAmelCase : Optional[Any]=64 , lowerCAmelCase : Union[str, Any]=None ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Union[str, Any] =np.random.default_rng(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =length SCREAMING_SNAKE_CASE_: Union[str, Any] =rng.normal(size=(length,) ).astype(np.floataa ) SCREAMING_SNAKE_CASE_: Tuple =a * self.x + b + rng.normal(scale=0.1 , size=(length,) ).astype(np.floataa ) def __len__( self : List[Any] ) -> str: '''simple docstring''' return self.length def __getitem__( self : Union[str, Any] , lowerCAmelCase : Any ) -> List[str]: '''simple docstring''' return {"x": self.x[i], "y": self.y[i]} class a ( torch.nn.Module ): def __init__( self : Optional[int] , lowerCAmelCase : str=0 , lowerCAmelCase : List[Any]=0 , lowerCAmelCase : Optional[int]=False ) -> Tuple: '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE_: int =torch.nn.Parameter(torch.tensor([2, 3] ).float() ) SCREAMING_SNAKE_CASE_: int =torch.nn.Parameter(torch.tensor([2, 3] ).float() ) SCREAMING_SNAKE_CASE_: Dict =True def lowerCamelCase__ ( self : str , lowerCAmelCase : Tuple=None ) -> int: '''simple docstring''' if self.first_batch: print(f'''Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}''' ) SCREAMING_SNAKE_CASE_: Union[str, Any] =False return x * self.a[0] + self.b[0] class a ( torch.nn.Module ): def __init__( self : Union[str, Any] , lowerCAmelCase : Any=0 , lowerCAmelCase : List[Any]=0 , lowerCAmelCase : List[Any]=False ) -> str: '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE_: List[str] =torch.nn.Parameter(torch.tensor(lowerCAmelCase ).float() ) SCREAMING_SNAKE_CASE_: Optional[int] =torch.nn.Parameter(torch.tensor(lowerCAmelCase ).float() ) SCREAMING_SNAKE_CASE_: List[Any] =True def lowerCamelCase__ ( self : List[str] , lowerCAmelCase : int=None ) -> Any: '''simple docstring''' if self.first_batch: print(f'''Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}''' ) SCREAMING_SNAKE_CASE_: Optional[int] =False return x * self.a + self.b def __magic_name__ ( lowercase , lowercase = 16 ): from datasets import load_dataset from transformers import AutoTokenizer SCREAMING_SNAKE_CASE_: Optional[Any] =AutoTokenizer.from_pretrained("""bert-base-cased""" ) SCREAMING_SNAKE_CASE_: Optional[int] ={"""train""": """tests/test_samples/MRPC/train.csv""", """validation""": """tests/test_samples/MRPC/dev.csv"""} SCREAMING_SNAKE_CASE_: Any =load_dataset("""csv""" , data_files=lowercase ) SCREAMING_SNAKE_CASE_: Any =datasets["""train"""].unique("""label""" ) SCREAMING_SNAKE_CASE_: List[Any] ={v: i for i, v in enumerate(lowercase )} def tokenize_function(lowercase ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE_: Dict =tokenizer( examples["""sentence1"""] , examples["""sentence2"""] , truncation=lowercase , max_length=lowercase , padding="""max_length""" ) if "label" in examples: SCREAMING_SNAKE_CASE_: Optional[int] =[label_to_id[l] for l in examples["""label"""]] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset SCREAMING_SNAKE_CASE_: List[Any] =datasets.map( lowercase , batched=lowercase , remove_columns=["""sentence1""", """sentence2""", """label"""] , ) def collate_fn(lowercase ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(lowercase , padding="""max_length""" , max_length=128 , return_tensors="""pt""" ) return tokenizer.pad(lowercase , padding="""longest""" , return_tensors="""pt""" ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE_: Optional[int] =DataLoader(tokenized_datasets["""train"""] , shuffle=lowercase , collate_fn=lowercase , batch_size=2 ) SCREAMING_SNAKE_CASE_: Dict =DataLoader(tokenized_datasets["""validation"""] , shuffle=lowercase , collate_fn=lowercase , batch_size=1 ) return train_dataloader, eval_dataloader
36
1
"""simple docstring""" import os import pytest from datasets import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, ) _UpperCAmelCase = pytest.mark.integration @pytest.mark.parametrize("""path""" , ["""paws""", """csv"""] ) def __magic_name__ ( lowercase , lowercase ): inspect_dataset(lowercase , lowercase ) SCREAMING_SNAKE_CASE_: List[str] =path + """.py""" assert script_name in os.listdir(lowercase ) assert "__pycache__" not in os.listdir(lowercase ) @pytest.mark.filterwarnings("""ignore:inspect_metric is deprecated:FutureWarning""" ) @pytest.mark.filterwarnings("""ignore:metric_module_factory is deprecated:FutureWarning""" ) @pytest.mark.parametrize("""path""" , ["""accuracy"""] ) def __magic_name__ ( lowercase , lowercase ): inspect_metric(lowercase , lowercase ) SCREAMING_SNAKE_CASE_: str =path + """.py""" assert script_name in os.listdir(lowercase ) assert "__pycache__" not in os.listdir(lowercase ) @pytest.mark.parametrize( """path, config_name, expected_splits""" , [ ("""squad""", """plain_text""", ["""train""", """validation"""]), ("""dalle-mini/wit""", """dalle-mini--wit""", ["""train"""]), ("""paws""", """labeled_final""", ["""train""", """test""", """validation"""]), ] , ) def __magic_name__ ( lowercase , lowercase , lowercase ): SCREAMING_SNAKE_CASE_: Optional[Any] =get_dataset_config_info(lowercase , config_name=lowercase ) assert info.config_name == config_name assert list(info.splits.keys() ) == expected_splits @pytest.mark.parametrize( """path, config_name, expected_exception""" , [ ("""paws""", None, ValueError), ] , ) def __magic_name__ ( lowercase , lowercase , lowercase ): with pytest.raises(lowercase ): get_dataset_config_info(lowercase , config_name=lowercase ) @pytest.mark.parametrize( """path, expected""" , [ ("""squad""", """plain_text"""), ("""acronym_identification""", """default"""), ("""lhoestq/squad""", """plain_text"""), ("""lhoestq/test""", """default"""), ("""lhoestq/demo1""", """lhoestq--demo1"""), ("""dalle-mini/wit""", """dalle-mini--wit"""), ] , ) def __magic_name__ ( lowercase , lowercase ): SCREAMING_SNAKE_CASE_: Any =get_dataset_config_names(lowercase ) assert expected in config_names @pytest.mark.parametrize( """path, expected_configs, expected_splits_in_first_config""" , [ ("""squad""", ["""plain_text"""], ["""train""", """validation"""]), ("""dalle-mini/wit""", ["""dalle-mini--wit"""], ["""train"""]), ("""paws""", ["""labeled_final""", """labeled_swap""", """unlabeled_final"""], ["""train""", """test""", """validation"""]), ] , ) def __magic_name__ ( lowercase , lowercase , lowercase ): SCREAMING_SNAKE_CASE_: List[Any] =get_dataset_infos(lowercase ) assert list(infos.keys() ) == expected_configs SCREAMING_SNAKE_CASE_: Dict =expected_configs[0] assert expected_config in infos SCREAMING_SNAKE_CASE_: List[str] =infos[expected_config] assert info.config_name == expected_config assert list(info.splits.keys() ) == expected_splits_in_first_config @pytest.mark.parametrize( """path, expected_config, expected_splits""" , [ ("""squad""", """plain_text""", ["""train""", """validation"""]), ("""dalle-mini/wit""", """dalle-mini--wit""", ["""train"""]), ("""paws""", """labeled_final""", ["""train""", """test""", """validation"""]), ] , ) def __magic_name__ ( lowercase , lowercase , lowercase ): SCREAMING_SNAKE_CASE_: Optional[int] =get_dataset_infos(lowercase ) assert expected_config in infos SCREAMING_SNAKE_CASE_: Optional[int] =infos[expected_config] assert info.config_name == expected_config assert list(info.splits.keys() ) == expected_splits @pytest.mark.parametrize( """path, config_name, expected_exception""" , [ ("""paws""", None, ValueError), ] , ) def __magic_name__ ( lowercase , lowercase , lowercase ): with pytest.raises(lowercase ): get_dataset_split_names(lowercase , config_name=lowercase )
36
"""simple docstring""" def __magic_name__ ( lowercase ): if upper_limit < 0: raise ValueError("""Limit for the Catalan sequence must be ≥ 0""" ) SCREAMING_SNAKE_CASE_: Tuple =[0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 SCREAMING_SNAKE_CASE_: Any =1 if upper_limit > 0: SCREAMING_SNAKE_CASE_: List[str] =1 # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i for i in range(2 , upper_limit + 1 ): for j in range(lowercase ): catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1] return catalan_list if __name__ == "__main__": print("""\n********* Catalan Numbers Using Dynamic Programming ************\n""") print("""\n*** Enter -1 at any time to quit ***""") print("""\nEnter the upper limit (≥ 0) for the Catalan number sequence: """, end="""""") try: while True: _UpperCAmelCase = int(input().strip()) if N < 0: print("""\n********* Goodbye!! ************""") break else: print(f"""The Catalan numbers from 0 through {N} are:""") print(catalan_numbers(N)) print("""Try another upper limit for the sequence: """, end="""""") except (NameError, ValueError): print("""\n********* Invalid input, goodbye! ************\n""") import doctest doctest.testmod()
36
1
"""simple docstring""" def __magic_name__ ( lowercase , lowercase , lowercase , lowercase , lowercase , ): SCREAMING_SNAKE_CASE_: Any =[redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError("""All input parameters must be positive""" ) if any(p > 1 for p in parameters[1:4] ): raise ValueError("""Relative densities cannot be greater than one""" ) else: SCREAMING_SNAKE_CASE_: int =1 - (matter_density + radiation_density + dark_energy) SCREAMING_SNAKE_CASE_: str =( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) SCREAMING_SNAKE_CASE_: Union[str, Any] =hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation _UpperCAmelCase = 0.3 print( hubble_parameter( hubble_constant=6_8.3, radiation_density=1e-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
36
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig _UpperCAmelCase = { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/config.json""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/config.json""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/config.json""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/config.json""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/config.json""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/config.json""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json""", } class a ( UpperCAmelCase__ ): UpperCamelCase : Any = 'albert' def __init__( self : Dict , lowerCAmelCase : List[str]=3_0000 , lowerCAmelCase : List[Any]=128 , lowerCAmelCase : List[str]=4096 , lowerCAmelCase : str=12 , lowerCAmelCase : str=1 , lowerCAmelCase : Tuple=64 , lowerCAmelCase : Dict=1_6384 , lowerCAmelCase : int=1 , lowerCAmelCase : str="gelu_new" , lowerCAmelCase : Dict=0 , lowerCAmelCase : Optional[Any]=0 , lowerCAmelCase : str=512 , lowerCAmelCase : Optional[int]=2 , lowerCAmelCase : List[Any]=0.0_2 , lowerCAmelCase : Union[str, Any]=1E-12 , lowerCAmelCase : Tuple=0.1 , lowerCAmelCase : List[Any]="absolute" , lowerCAmelCase : List[Any]=0 , lowerCAmelCase : int=2 , lowerCAmelCase : Optional[int]=3 , **lowerCAmelCase : int , ) -> Tuple: '''simple docstring''' super().__init__(pad_token_id=lowerCAmelCase , bos_token_id=lowerCAmelCase , eos_token_id=lowerCAmelCase , **lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =vocab_size SCREAMING_SNAKE_CASE_: Optional[int] =embedding_size SCREAMING_SNAKE_CASE_: Optional[int] =hidden_size SCREAMING_SNAKE_CASE_: Tuple =num_hidden_layers SCREAMING_SNAKE_CASE_: Any =num_hidden_groups SCREAMING_SNAKE_CASE_: List[Any] =num_attention_heads SCREAMING_SNAKE_CASE_: List[Any] =inner_group_num SCREAMING_SNAKE_CASE_: Optional[int] =hidden_act SCREAMING_SNAKE_CASE_: int =intermediate_size SCREAMING_SNAKE_CASE_: Any =hidden_dropout_prob SCREAMING_SNAKE_CASE_: Union[str, Any] =attention_probs_dropout_prob SCREAMING_SNAKE_CASE_: int =max_position_embeddings SCREAMING_SNAKE_CASE_: Any =type_vocab_size SCREAMING_SNAKE_CASE_: int =initializer_range SCREAMING_SNAKE_CASE_: List[Any] =layer_norm_eps SCREAMING_SNAKE_CASE_: Dict =classifier_dropout_prob SCREAMING_SNAKE_CASE_: int =position_embedding_type class a ( UpperCAmelCase__ ): @property def lowerCamelCase__ ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": SCREAMING_SNAKE_CASE_: str ={0: """batch""", 1: """choice""", 2: """sequence"""} else: SCREAMING_SNAKE_CASE_: Dict ={0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
36
1
"""simple docstring""" import tempfile import numpy as np import torch from transformers import AutoTokenizer, TaEncoderModel from diffusers import DDPMScheduler, UNetaDConditionModel from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.pipelines.deepfloyd_if import IFWatermarker from diffusers.utils.testing_utils import torch_device from ..test_pipelines_common import to_np class a : def lowerCamelCase__ ( self : List[str] ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_: int =TaEncoderModel.from_pretrained("""hf-internal-testing/tiny-random-t5""" ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_: Optional[Any] =AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-t5""" ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_: str =UNetaDConditionModel( sample_size=32 , layers_per_block=1 , block_out_channels=[32, 64] , down_block_types=[ """ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D""", ] , mid_block_type="""UNetMidBlock2DSimpleCrossAttn""" , up_block_types=["""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""] , in_channels=3 , out_channels=6 , cross_attention_dim=32 , encoder_hid_dim=32 , attention_head_dim=8 , addition_embed_type="""text""" , addition_embed_type_num_heads=2 , cross_attention_norm="""group_norm""" , resnet_time_scale_shift="""scale_shift""" , act_fn="""gelu""" , ) unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_: List[str] =DDPMScheduler( num_train_timesteps=1000 , beta_schedule="""squaredcos_cap_v2""" , beta_start=0.0_0_0_1 , beta_end=0.0_2 , thresholding=lowerCAmelCase , dynamic_thresholding_ratio=0.9_5 , sample_max_value=1.0 , prediction_type="""epsilon""" , variance_type="""learned_range""" , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_: Optional[Any] =IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def lowerCamelCase__ ( self : str ) -> Any: '''simple docstring''' torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_: Any =TaEncoderModel.from_pretrained("""hf-internal-testing/tiny-random-t5""" ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_: Dict =AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-t5""" ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_: List[Any] =UNetaDConditionModel( sample_size=32 , layers_per_block=[1, 2] , block_out_channels=[32, 64] , down_block_types=[ """ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D""", ] , mid_block_type="""UNetMidBlock2DSimpleCrossAttn""" , up_block_types=["""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""] , in_channels=6 , out_channels=6 , cross_attention_dim=32 , encoder_hid_dim=32 , attention_head_dim=8 , addition_embed_type="""text""" , addition_embed_type_num_heads=2 , cross_attention_norm="""group_norm""" , resnet_time_scale_shift="""scale_shift""" , act_fn="""gelu""" , class_embed_type="""timestep""" , mid_block_scale_factor=1.4_1_4 , time_embedding_act_fn="""gelu""" , time_embedding_dim=32 , ) unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_: str =DDPMScheduler( num_train_timesteps=1000 , beta_schedule="""squaredcos_cap_v2""" , beta_start=0.0_0_0_1 , beta_end=0.0_2 , thresholding=lowerCAmelCase , dynamic_thresholding_ratio=0.9_5 , sample_max_value=1.0 , prediction_type="""epsilon""" , variance_type="""learned_range""" , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_: List[Any] =DDPMScheduler( num_train_timesteps=1000 , beta_schedule="""squaredcos_cap_v2""" , beta_start=0.0_0_0_1 , beta_end=0.0_2 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_: Tuple =IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "image_noising_scheduler": image_noising_scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def lowerCamelCase__ ( self : int ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =self.get_dummy_components() SCREAMING_SNAKE_CASE_: str =self.pipeline_class(**lowerCAmelCase ) pipe.to(lowerCAmelCase ) pipe.set_progress_bar_config(disable=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Any =self.get_dummy_inputs(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Dict =inputs["""prompt"""] SCREAMING_SNAKE_CASE_: Tuple =inputs["""generator"""] SCREAMING_SNAKE_CASE_: Tuple =inputs["""num_inference_steps"""] SCREAMING_SNAKE_CASE_: Tuple =inputs["""output_type"""] if "image" in inputs: SCREAMING_SNAKE_CASE_: List[str] =inputs["""image"""] else: SCREAMING_SNAKE_CASE_: Union[str, Any] =None if "mask_image" in inputs: SCREAMING_SNAKE_CASE_: Optional[Any] =inputs["""mask_image"""] else: SCREAMING_SNAKE_CASE_: Tuple =None if "original_image" in inputs: SCREAMING_SNAKE_CASE_: List[str] =inputs["""original_image"""] else: SCREAMING_SNAKE_CASE_: Optional[int] =None SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: str =pipe.encode_prompt(lowerCAmelCase ) # inputs with prompt converted to embeddings SCREAMING_SNAKE_CASE_: Union[str, Any] ={ """prompt_embeds""": prompt_embeds, """negative_prompt_embeds""": negative_prompt_embeds, """generator""": generator, """num_inference_steps""": num_inference_steps, """output_type""": output_type, } if image is not None: SCREAMING_SNAKE_CASE_: int =image if mask_image is not None: SCREAMING_SNAKE_CASE_: Optional[Any] =mask_image if original_image is not None: SCREAMING_SNAKE_CASE_: str =original_image # set all optional components to None for optional_component in pipe._optional_components: setattr(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =pipe(**lowerCAmelCase )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Any =self.pipeline_class.from_pretrained(lowerCAmelCase ) pipe_loaded.to(lowerCAmelCase ) pipe_loaded.set_progress_bar_config(disable=lowerCAmelCase ) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests for optional_component in pipe._optional_components: self.assertTrue( getattr(lowerCAmelCase , lowerCAmelCase ) is None , f'''`{optional_component}` did not stay set to None after loading.''' , ) SCREAMING_SNAKE_CASE_: Optional[int] =self.get_dummy_inputs(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =inputs["""generator"""] SCREAMING_SNAKE_CASE_: List[str] =inputs["""num_inference_steps"""] SCREAMING_SNAKE_CASE_: List[str] =inputs["""output_type"""] # inputs with prompt converted to embeddings SCREAMING_SNAKE_CASE_: Dict ={ """prompt_embeds""": prompt_embeds, """negative_prompt_embeds""": negative_prompt_embeds, """generator""": generator, """num_inference_steps""": num_inference_steps, """output_type""": output_type, } if image is not None: SCREAMING_SNAKE_CASE_: Union[str, Any] =image if mask_image is not None: SCREAMING_SNAKE_CASE_: List[str] =mask_image if original_image is not None: SCREAMING_SNAKE_CASE_: int =original_image SCREAMING_SNAKE_CASE_: List[str] =pipe_loaded(**lowerCAmelCase )[0] SCREAMING_SNAKE_CASE_: Optional[int] =np.abs(to_np(lowerCAmelCase ) - to_np(lowerCAmelCase ) ).max() self.assertLess(lowerCAmelCase , 1E-4 ) def lowerCamelCase__ ( self : List[Any] ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[str] =self.get_dummy_components() SCREAMING_SNAKE_CASE_: Any =self.pipeline_class(**lowerCAmelCase ) pipe.to(lowerCAmelCase ) pipe.set_progress_bar_config(disable=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[Any] =self.get_dummy_inputs(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[Any] =pipe(**lowerCAmelCase )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple =self.pipeline_class.from_pretrained(lowerCAmelCase ) pipe_loaded.to(lowerCAmelCase ) pipe_loaded.set_progress_bar_config(disable=lowerCAmelCase ) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests SCREAMING_SNAKE_CASE_: Tuple =self.get_dummy_inputs(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: int =pipe_loaded(**lowerCAmelCase )[0] SCREAMING_SNAKE_CASE_: List[Any] =np.abs(to_np(lowerCAmelCase ) - to_np(lowerCAmelCase ) ).max() self.assertLess(lowerCAmelCase , 1E-4 )
36
"""simple docstring""" from collections import Counter from pathlib import Path from typing import Optional, Tuple import yaml class a ( yaml.SafeLoader ): def lowerCamelCase__ ( self : int , lowerCAmelCase : List[str] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =[self.constructed_objects[key_node] for key_node, _ in node.value] SCREAMING_SNAKE_CASE_: Any =[tuple(lowerCAmelCase ) if isinstance(lowerCAmelCase , lowerCAmelCase ) else key for key in keys] SCREAMING_SNAKE_CASE_: Dict =Counter(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =[key for key in counter if counter[key] > 1] if duplicate_keys: raise TypeError(f'''Got duplicate yaml keys: {duplicate_keys}''' ) def lowerCamelCase__ ( self : Tuple , lowerCAmelCase : str , lowerCAmelCase : Optional[int]=False ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =super().construct_mapping(lowerCAmelCase , deep=lowerCAmelCase ) self._check_no_duplicates_on_constructed_node(lowerCAmelCase ) return mapping def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Dict =list(readme_content.splitlines() ) if full_content and full_content[0] == "---" and "---" in full_content[1:]: SCREAMING_SNAKE_CASE_: Union[str, Any] =full_content[1:].index("""---""" ) + 1 SCREAMING_SNAKE_CASE_: List[str] ="""\n""".join(full_content[1:sep_idx] ) return yamlblock, "\n".join(full_content[sep_idx + 1 :] ) return None, "\n".join(lowercase ) class a ( UpperCAmelCase__ ): # class attributes UpperCamelCase : Tuple = {'train_eval_index'} # train-eval-index in the YAML metadata @classmethod def lowerCamelCase__ ( cls : List[Any] , lowerCAmelCase : Path ) -> "DatasetMetadata": '''simple docstring''' with open(lowerCAmelCase , encoding="""utf-8""" ) as readme_file: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Union[str, Any] =_split_yaml_from_readme(readme_file.read() ) if yaml_string is not None: return cls.from_yaml_string(lowerCAmelCase ) else: return cls() def lowerCamelCase__ ( self : Any , lowerCAmelCase : Path ) -> List[str]: '''simple docstring''' if path.exists(): with open(lowerCAmelCase , encoding="""utf-8""" ) as readme_file: SCREAMING_SNAKE_CASE_: str =readme_file.read() else: SCREAMING_SNAKE_CASE_: str =None SCREAMING_SNAKE_CASE_: Tuple =self._to_readme(lowerCAmelCase ) with open(lowerCAmelCase , """w""" , encoding="""utf-8""" ) as readme_file: readme_file.write(lowerCAmelCase ) def lowerCamelCase__ ( self : Optional[Any] , lowerCAmelCase : Optional[str] = None ) -> str: '''simple docstring''' if readme_content is not None: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[str] =_split_yaml_from_readme(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] ="""---\n""" + self.to_yaml_string() + """---\n""" + content else: SCREAMING_SNAKE_CASE_: List[Any] ="""---\n""" + self.to_yaml_string() + """---\n""" return full_content @classmethod def lowerCamelCase__ ( cls : Optional[int] , lowerCAmelCase : str ) -> "DatasetMetadata": '''simple docstring''' SCREAMING_SNAKE_CASE_: int =yaml.load(lowerCAmelCase , Loader=_NoDuplicateSafeLoader ) or {} # Convert the YAML keys to DatasetMetadata fields SCREAMING_SNAKE_CASE_: List[Any] ={ (key.replace("""-""" , """_""" ) if key.replace("""-""" , """_""" ) in cls._FIELDS_WITH_DASHES else key): value for key, value in metadata_dict.items() } return cls(**lowerCAmelCase ) def lowerCamelCase__ ( self : Dict ) -> str: '''simple docstring''' return yaml.safe_dump( { (key.replace("""_""" , """-""" ) if key in self._FIELDS_WITH_DASHES else key): value for key, value in self.items() } , sort_keys=lowerCAmelCase , allow_unicode=lowerCAmelCase , encoding="""utf-8""" , ).decode("""utf-8""" ) _UpperCAmelCase = { """image-classification""": [], """translation""": [], """image-segmentation""": [], """fill-mask""": [], """automatic-speech-recognition""": [], """token-classification""": [], """sentence-similarity""": [], """audio-classification""": [], """question-answering""": [], """summarization""": [], """zero-shot-classification""": [], """table-to-text""": [], """feature-extraction""": [], """other""": [], """multiple-choice""": [], """text-classification""": [], """text-to-image""": [], """text2text-generation""": [], """zero-shot-image-classification""": [], """tabular-classification""": [], """tabular-regression""": [], """image-to-image""": [], """tabular-to-text""": [], """unconditional-image-generation""": [], """text-retrieval""": [], """text-to-speech""": [], """object-detection""": [], """audio-to-audio""": [], """text-generation""": [], """conversational""": [], """table-question-answering""": [], """visual-question-answering""": [], """image-to-text""": [], """reinforcement-learning""": [], """voice-activity-detection""": [], """time-series-forecasting""": [], """document-question-answering""": [], } if __name__ == "__main__": from argparse import ArgumentParser _UpperCAmelCase = ArgumentParser(usage="""Validate the yaml metadata block of a README.md file.""") ap.add_argument("""readme_filepath""") _UpperCAmelCase = ap.parse_args() _UpperCAmelCase = Path(args.readme_filepath) _UpperCAmelCase = DatasetMetadata.from_readme(readme_filepath) print(dataset_metadata) dataset_metadata.to_readme(readme_filepath)
36
1
"""simple docstring""" # DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from typing import Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import randn_tensor from .scheduling_utils import SchedulerMixin class a ( UpperCAmelCase__ , UpperCAmelCase__ ): UpperCamelCase : Tuple = 1 @register_to_config def __init__( self : Tuple , lowerCAmelCase : List[str]=2000 , lowerCAmelCase : List[Any]=0.1 , lowerCAmelCase : List[str]=20 , lowerCAmelCase : Any=1E-3 ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[str] =None SCREAMING_SNAKE_CASE_: Tuple =None SCREAMING_SNAKE_CASE_: Union[str, Any] =None def lowerCamelCase__ ( self : Dict , lowerCAmelCase : Optional[int] , lowerCAmelCase : Union[str, torch.device] = None ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[str] =torch.linspace(1 , self.config.sampling_eps , lowerCAmelCase , device=lowerCAmelCase ) def lowerCamelCase__ ( self : Optional[Any] , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Dict , lowerCAmelCase : List[str] , lowerCAmelCase : Union[str, Any]=None ) -> int: '''simple docstring''' if self.timesteps is None: raise ValueError( """`self.timesteps` is not set, you need to run 'set_timesteps' after creating the scheduler""" ) # TODO(Patrick) better comments + non-PyTorch # postprocess model score SCREAMING_SNAKE_CASE_: str =( -0.2_5 * t**2 * (self.config.beta_max - self.config.beta_min) - 0.5 * t * self.config.beta_min ) SCREAMING_SNAKE_CASE_: Optional[int] =torch.sqrt(1.0 - torch.exp(2.0 * log_mean_coeff ) ) SCREAMING_SNAKE_CASE_: int =std.flatten() while len(std.shape ) < len(score.shape ): SCREAMING_SNAKE_CASE_: Optional[int] =std.unsqueeze(-1 ) SCREAMING_SNAKE_CASE_: Dict =-score / std # compute SCREAMING_SNAKE_CASE_: Union[str, Any] =-1.0 / len(self.timesteps ) SCREAMING_SNAKE_CASE_: Optional[Any] =self.config.beta_min + t * (self.config.beta_max - self.config.beta_min) SCREAMING_SNAKE_CASE_: Any =beta_t.flatten() while len(beta_t.shape ) < len(x.shape ): SCREAMING_SNAKE_CASE_: List[str] =beta_t.unsqueeze(-1 ) SCREAMING_SNAKE_CASE_: Union[str, Any] =-0.5 * beta_t * x SCREAMING_SNAKE_CASE_: Tuple =torch.sqrt(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: str =drift - diffusion**2 * score SCREAMING_SNAKE_CASE_: Tuple =x + drift * dt # add noise SCREAMING_SNAKE_CASE_: Tuple =randn_tensor(x.shape , layout=x.layout , generator=lowerCAmelCase , device=x.device , dtype=x.dtype ) SCREAMING_SNAKE_CASE_: Tuple =x_mean + diffusion * math.sqrt(-dt ) * noise return x, x_mean def __len__( self : Tuple ) -> str: '''simple docstring''' return self.config.num_train_timesteps
36
"""simple docstring""" import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from xgboost import XGBClassifier def __magic_name__ ( lowercase ): return (data["data"], data["target"]) def __magic_name__ ( lowercase , lowercase ): SCREAMING_SNAKE_CASE_: Dict =XGBClassifier() classifier.fit(lowercase , lowercase ) return classifier def __magic_name__ ( ): SCREAMING_SNAKE_CASE_: Optional[Any] =load_iris() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Tuple =data_handling(lowercase ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[Any] =train_test_split( lowercase , lowercase , test_size=0.25 ) SCREAMING_SNAKE_CASE_: Tuple =iris["""target_names"""] # Create an XGBoost Classifier from the training data SCREAMING_SNAKE_CASE_: Optional[int] =xgboost(lowercase , lowercase ) # Display the confusion matrix of the classifier with both training and test sets ConfusionMatrixDisplay.from_estimator( lowercase , lowercase , lowercase , display_labels=lowercase , cmap="""Blues""" , normalize="""true""" , ) plt.title("""Normalized Confusion Matrix - IRIS Dataset""" ) plt.show() if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
36
1
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_lxmert import LxmertTokenizer _UpperCAmelCase = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} _UpperCAmelCase = { """vocab_file""": { """unc-nlp/lxmert-base-uncased""": """https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/vocab.txt""", }, """tokenizer_file""": { """unc-nlp/lxmert-base-uncased""": ( """https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/tokenizer.json""" ), }, } _UpperCAmelCase = { """unc-nlp/lxmert-base-uncased""": 5_1_2, } _UpperCAmelCase = { """unc-nlp/lxmert-base-uncased""": {"""do_lower_case""": True}, } class a ( UpperCAmelCase__ ): UpperCamelCase : int = VOCAB_FILES_NAMES UpperCamelCase : List[Any] = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : Dict = PRETRAINED_INIT_CONFIGURATION UpperCamelCase : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : str = LxmertTokenizer def __init__( self : int , lowerCAmelCase : List[Any]=None , lowerCAmelCase : List[str]=None , lowerCAmelCase : Dict=True , lowerCAmelCase : Optional[Any]="[UNK]" , lowerCAmelCase : str="[SEP]" , lowerCAmelCase : List[Any]="[PAD]" , lowerCAmelCase : Tuple="[CLS]" , lowerCAmelCase : List[Any]="[MASK]" , lowerCAmelCase : List[str]=True , lowerCAmelCase : Tuple=None , **lowerCAmelCase : Union[str, Any] , ) -> List[str]: '''simple docstring''' super().__init__( lowerCAmelCase , tokenizer_file=lowerCAmelCase , do_lower_case=lowerCAmelCase , unk_token=lowerCAmelCase , sep_token=lowerCAmelCase , pad_token=lowerCAmelCase , cls_token=lowerCAmelCase , mask_token=lowerCAmelCase , tokenize_chinese_chars=lowerCAmelCase , strip_accents=lowerCAmelCase , **lowerCAmelCase , ) SCREAMING_SNAKE_CASE_: Tuple =json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , lowerCAmelCase ) != do_lower_case or normalizer_state.get("""strip_accents""" , lowerCAmelCase ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , lowerCAmelCase ) != tokenize_chinese_chars ): SCREAMING_SNAKE_CASE_: Optional[int] =getattr(lowerCAmelCase , normalizer_state.pop("""type""" ) ) SCREAMING_SNAKE_CASE_: Dict =do_lower_case SCREAMING_SNAKE_CASE_: Union[str, Any] =strip_accents SCREAMING_SNAKE_CASE_: str =tokenize_chinese_chars SCREAMING_SNAKE_CASE_: Optional[int] =normalizer_class(**lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Union[str, Any] =do_lower_case def lowerCamelCase__ ( self : Tuple , lowerCAmelCase : str , lowerCAmelCase : Union[str, Any]=None ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[Any] =[self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def lowerCamelCase__ ( self : Dict , lowerCAmelCase : List[int] , lowerCAmelCase : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =[self.sep_token_id] SCREAMING_SNAKE_CASE_: Any =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def lowerCamelCase__ ( self : Optional[int] , lowerCAmelCase : str , lowerCAmelCase : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: int =self._tokenizer.model.save(lowerCAmelCase , name=lowerCAmelCase ) return tuple(lowerCAmelCase )
36
"""simple docstring""" from typing import Dict import numpy as np import torch from . import residue_constants as rc from .tensor_utils import tensor_tree_map, tree_map def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Optional[Any] =[] SCREAMING_SNAKE_CASE_: List[str] =[] SCREAMING_SNAKE_CASE_: Any =[] for rt in rc.restypes: SCREAMING_SNAKE_CASE_: Optional[int] =rc.restype_name_to_atomaa_names[rc.restype_atoa[rt]] restype_atomaa_to_atomaa_list.append([(rc.atom_order[name] if name else 0) for name in atom_names] ) SCREAMING_SNAKE_CASE_: Any ={name: i for i, name in enumerate(lowercase )} restype_atomaa_to_atomaa_list.append( [(atom_name_to_idxaa[name] if name in atom_name_to_idxaa else 0) for name in rc.atom_types] ) restype_atomaa_mask_list.append([(1.0 if name else 0.0) for name in atom_names] ) # Add dummy mapping for restype 'UNK' restype_atomaa_to_atomaa_list.append([0] * 14 ) restype_atomaa_to_atomaa_list.append([0] * 37 ) restype_atomaa_mask_list.append([0.0] * 14 ) SCREAMING_SNAKE_CASE_: Union[str, Any] =torch.tensor( lowercase , dtype=torch.intaa , device=protein["""aatype"""].device , ) SCREAMING_SNAKE_CASE_: Optional[Any] =torch.tensor( lowercase , dtype=torch.intaa , device=protein["""aatype"""].device , ) SCREAMING_SNAKE_CASE_: List[str] =torch.tensor( lowercase , dtype=torch.floataa , device=protein["""aatype"""].device , ) SCREAMING_SNAKE_CASE_: Optional[Any] =protein["""aatype"""].to(torch.long ) # create the mapping for (residx, atom14) --> atom37, i.e. an array # with shape (num_res, 14) containing the atom37 indices for this protein SCREAMING_SNAKE_CASE_: List[str] =restype_atomaa_to_atomaa[protein_aatype] SCREAMING_SNAKE_CASE_: Any =restype_atomaa_mask[protein_aatype] SCREAMING_SNAKE_CASE_: Tuple =residx_atomaa_mask SCREAMING_SNAKE_CASE_: Dict =residx_atomaa_to_atomaa.long() # create the gather indices for mapping back SCREAMING_SNAKE_CASE_: Dict =restype_atomaa_to_atomaa[protein_aatype] SCREAMING_SNAKE_CASE_: Optional[int] =residx_atomaa_to_atomaa.long() # create the corresponding mask SCREAMING_SNAKE_CASE_: Optional[int] =torch.zeros([21, 37] , dtype=torch.floataa , device=protein["""aatype"""].device ) for restype, restype_letter in enumerate(rc.restypes ): SCREAMING_SNAKE_CASE_: int =rc.restype_atoa[restype_letter] SCREAMING_SNAKE_CASE_: Any =rc.residue_atoms[restype_name] for atom_name in atom_names: SCREAMING_SNAKE_CASE_: Optional[int] =rc.atom_order[atom_name] SCREAMING_SNAKE_CASE_: Dict =1 SCREAMING_SNAKE_CASE_: List[str] =restype_atomaa_mask[protein_aatype] SCREAMING_SNAKE_CASE_: List[Any] =residx_atomaa_mask return protein def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Any =tree_map(lambda lowercase : torch.tensor(lowercase , device=batch["""aatype"""].device ) , lowercase , np.ndarray ) SCREAMING_SNAKE_CASE_: int =tensor_tree_map(lambda lowercase : np.array(lowercase ) , make_atomaa_masks(lowercase ) ) return out
36
1
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class a ( unittest.TestCase ): def __init__( self : int , lowerCAmelCase : Tuple , lowerCAmelCase : Optional[int]=7 , lowerCAmelCase : int=3 , lowerCAmelCase : List[str]=18 , lowerCAmelCase : Dict=30 , lowerCAmelCase : int=400 , lowerCAmelCase : int=True , lowerCAmelCase : str=None , lowerCAmelCase : Optional[Any]=True , ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[Any] =size if size is not None else {"""height""": 18, """width""": 18} SCREAMING_SNAKE_CASE_: Optional[int] =parent SCREAMING_SNAKE_CASE_: List[Any] =batch_size SCREAMING_SNAKE_CASE_: Union[str, Any] =num_channels SCREAMING_SNAKE_CASE_: Tuple =image_size SCREAMING_SNAKE_CASE_: Optional[int] =min_resolution SCREAMING_SNAKE_CASE_: int =max_resolution SCREAMING_SNAKE_CASE_: Optional[Any] =do_resize SCREAMING_SNAKE_CASE_: str =size SCREAMING_SNAKE_CASE_: Any =apply_ocr def lowerCamelCase__ ( self : List[Any] ) -> Any: '''simple docstring''' return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class a ( UpperCAmelCase__ , unittest.TestCase ): UpperCamelCase : str = LayoutLMvaImageProcessor if is_pytesseract_available() else None def lowerCamelCase__ ( self : str ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =LayoutLMvaImageProcessingTester(self ) @property def lowerCamelCase__ ( self : Tuple ) -> Union[str, Any]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def lowerCamelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[Any] =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowerCAmelCase , """do_resize""" ) ) self.assertTrue(hasattr(lowerCAmelCase , """size""" ) ) self.assertTrue(hasattr(lowerCAmelCase , """apply_ocr""" ) ) def lowerCamelCase__ ( self : Optional[int] ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: int =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 18, """width""": 18} ) SCREAMING_SNAKE_CASE_: Union[str, Any] =self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"""height""": 42, """width""": 42} ) def lowerCamelCase__ ( self : Union[str, Any] ) -> str: '''simple docstring''' pass def lowerCamelCase__ ( self : Tuple ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE_: Optional[Any] =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE_: List[str] =image_processing(image_inputs[0] , return_tensors="""pt""" ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) self.assertIsInstance(encoding.words , lowerCAmelCase ) self.assertIsInstance(encoding.boxes , lowerCAmelCase ) # Test batched SCREAMING_SNAKE_CASE_: int =image_processing(lowerCAmelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) def lowerCamelCase__ ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE_: int =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase , numpify=lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE_: Optional[int] =image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) # Test batched SCREAMING_SNAKE_CASE_: List[str] =image_processing(lowerCAmelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) def lowerCamelCase__ ( self : Optional[Any] ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE_: Any =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase , torchify=lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE_: List[str] =image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) # Test batched SCREAMING_SNAKE_CASE_: Any =image_processing(lowerCAmelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) def lowerCamelCase__ ( self : int ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE_: str =LayoutLMvaImageProcessor() from datasets import load_dataset SCREAMING_SNAKE_CASE_: Any =load_dataset("""hf-internal-testing/fixtures_docvqa""" , split="""test""" ) SCREAMING_SNAKE_CASE_: Union[str, Any] =Image.open(ds[0]["""file"""] ).convert("""RGB""" ) SCREAMING_SNAKE_CASE_: Union[str, Any] =image_processing(lowerCAmelCase , return_tensors="""pt""" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 SCREAMING_SNAKE_CASE_: List[str] =[["""11:14""", """to""", """11:39""", """a.m""", """11:39""", """to""", """11:44""", """a.m.""", """11:44""", """a.m.""", """to""", """12:25""", """p.m.""", """12:25""", """to""", """12:58""", """p.m.""", """12:58""", """to""", """4:00""", """p.m.""", """2:00""", """to""", """5:00""", """p.m.""", """Coffee""", """Break""", """Coffee""", """will""", """be""", """served""", """for""", """men""", """and""", """women""", """in""", """the""", """lobby""", """adjacent""", """to""", """exhibit""", """area.""", """Please""", """move""", """into""", """exhibit""", """area.""", """(Exhibits""", """Open)""", """TRRF""", """GENERAL""", """SESSION""", """(PART""", """|)""", """Presiding:""", """Lee""", """A.""", """Waller""", """TRRF""", """Vice""", """President""", """“Introductory""", """Remarks”""", """Lee""", """A.""", """Waller,""", """TRRF""", """Vice""", """Presi-""", """dent""", """Individual""", """Interviews""", """with""", """TRRF""", """Public""", """Board""", """Members""", """and""", """Sci-""", """entific""", """Advisory""", """Council""", """Mem-""", """bers""", """Conducted""", """by""", """TRRF""", """Treasurer""", """Philip""", """G.""", """Kuehn""", """to""", """get""", """answers""", """which""", """the""", """public""", """refrigerated""", """warehousing""", """industry""", """is""", """looking""", """for.""", """Plus""", """questions""", """from""", """the""", """floor.""", """Dr.""", """Emil""", """M.""", """Mrak,""", """University""", """of""", """Cal-""", """ifornia,""", """Chairman,""", """TRRF""", """Board;""", """Sam""", """R.""", """Cecil,""", """University""", """of""", """Georgia""", """College""", """of""", """Agriculture;""", """Dr.""", """Stanley""", """Charm,""", """Tufts""", """University""", """School""", """of""", """Medicine;""", """Dr.""", """Robert""", """H.""", """Cotton,""", """ITT""", """Continental""", """Baking""", """Company;""", """Dr.""", """Owen""", """Fennema,""", """University""", """of""", """Wis-""", """consin;""", """Dr.""", """Robert""", """E.""", """Hardenburg,""", """USDA.""", """Questions""", """and""", """Answers""", """Exhibits""", """Open""", """Capt.""", """Jack""", """Stoney""", """Room""", """TRRF""", """Scientific""", """Advisory""", """Council""", """Meeting""", """Ballroom""", """Foyer"""]] # noqa: E231 SCREAMING_SNAKE_CASE_: Dict =[[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , lowerCAmelCase ) self.assertListEqual(encoding.boxes , lowerCAmelCase ) # with apply_OCR = False SCREAMING_SNAKE_CASE_: Tuple =LayoutLMvaImageProcessor(apply_ocr=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple =image_processing(lowerCAmelCase , return_tensors="""pt""" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
36
"""simple docstring""" from pathlib import Path from typing import List from transformers import is_torch_available, is_vision_available from transformers.testing_utils import get_tests_dir, is_tool_test from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText if is_torch_available(): import torch if is_vision_available(): from PIL import Image _UpperCAmelCase = ["""text""", """image""", """audio"""] def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: str =[] for input_type in input_types: if input_type == "text": inputs.append("""Text input""" ) elif input_type == "image": inputs.append( Image.open(Path(get_tests_dir("""fixtures/tests_samples/COCO""" ) ) / """000000039769.png""" ).resize((512, 512) ) ) elif input_type == "audio": inputs.append(torch.ones(3000 ) ) elif isinstance(lowercase , lowercase ): inputs.append(create_inputs(lowercase ) ) else: raise ValueError(f'''Invalid type requested: {input_type}''' ) return inputs def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: int =[] for output in outputs: if isinstance(lowercase , (str, AgentText) ): output_types.append("""text""" ) elif isinstance(lowercase , (Image.Image, AgentImage) ): output_types.append("""image""" ) elif isinstance(lowercase , (torch.Tensor, AgentAudio) ): output_types.append("""audio""" ) else: raise ValueError(f'''Invalid output: {output}''' ) return output_types @is_tool_test class a : def lowerCamelCase__ ( self : Tuple ) -> List[Any]: '''simple docstring''' self.assertTrue(hasattr(self.tool , """inputs""" ) ) self.assertTrue(hasattr(self.tool , """outputs""" ) ) SCREAMING_SNAKE_CASE_: Optional[int] =self.tool.inputs for _input in inputs: if isinstance(_input , lowerCAmelCase ): for __input in _input: self.assertTrue(__input in authorized_types ) else: self.assertTrue(_input in authorized_types ) SCREAMING_SNAKE_CASE_: Any =self.tool.outputs for _output in outputs: self.assertTrue(_output in authorized_types ) def lowerCamelCase__ ( self : str ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =create_inputs(self.tool.inputs ) SCREAMING_SNAKE_CASE_: List[Any] =self.tool(*lowerCAmelCase ) # There is a single output if len(self.tool.outputs ) == 1: SCREAMING_SNAKE_CASE_: str =[outputs] self.assertListEqual(output_types(lowerCAmelCase ) , self.tool.outputs ) def lowerCamelCase__ ( self : str ) -> Optional[Any]: '''simple docstring''' self.assertTrue(hasattr(self.tool , """description""" ) ) self.assertTrue(hasattr(self.tool , """default_checkpoint""" ) ) self.assertTrue(self.tool.description.startswith("""This is a tool that""" ) ) def lowerCamelCase__ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: str =create_inputs(self.tool.inputs ) SCREAMING_SNAKE_CASE_: Tuple =self.tool(*lowerCAmelCase ) if not isinstance(lowerCAmelCase , lowerCAmelCase ): SCREAMING_SNAKE_CASE_: int =[outputs] self.assertEqual(len(lowerCAmelCase ) , len(self.tool.outputs ) ) for output, output_type in zip(lowerCAmelCase , self.tool.outputs ): SCREAMING_SNAKE_CASE_: int =AGENT_TYPE_MAPPING[output_type] self.assertTrue(isinstance(lowerCAmelCase , lowerCAmelCase ) ) def lowerCamelCase__ ( self : List[Any] ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =create_inputs(self.tool.inputs ) SCREAMING_SNAKE_CASE_: Union[str, Any] =[] for _input, input_type in zip(lowerCAmelCase , self.tool.inputs ): if isinstance(lowerCAmelCase , lowerCAmelCase ): _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input ) for _input_type in input_type] ) else: _inputs.append(AGENT_TYPE_MAPPING[input_type](_input ) ) # Should not raise an error SCREAMING_SNAKE_CASE_: Dict =self.tool(*lowerCAmelCase ) if not isinstance(lowerCAmelCase , lowerCAmelCase ): SCREAMING_SNAKE_CASE_: List[str] =[outputs] self.assertEqual(len(lowerCAmelCase ) , len(self.tool.outputs ) )
36
1
"""simple docstring""" from __future__ import annotations def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: List[Any] =len(lowercase ) # We need to create solution object to save path. SCREAMING_SNAKE_CASE_: Optional[Any] =[[0 for _ in range(lowercase )] for _ in range(lowercase )] SCREAMING_SNAKE_CASE_: List[str] =run_maze(lowercase , 0 , 0 , lowercase ) if solved: print("""\n""".join(str(lowercase ) for row in solutions ) ) else: print("""No solution exists!""" ) return solved def __magic_name__ ( lowercase , lowercase , lowercase , lowercase ): SCREAMING_SNAKE_CASE_: Any =len(lowercase ) # Final check point. if i == j == (size - 1): SCREAMING_SNAKE_CASE_: Optional[int] =1 return True SCREAMING_SNAKE_CASE_: int =(not i < 0) and (not j < 0) # Check lower bounds SCREAMING_SNAKE_CASE_: Union[str, Any] =(i < size) and (j < size) # Check upper bounds if lower_flag and upper_flag: # check for already visited and block points. SCREAMING_SNAKE_CASE_: List[str] =(not solutions[i][j]) and (not maze[i][j]) if block_flag: # check visited SCREAMING_SNAKE_CASE_: str =1 # check for directions if ( run_maze(lowercase , i + 1 , lowercase , lowercase ) or run_maze(lowercase , lowercase , j + 1 , lowercase ) or run_maze(lowercase , i - 1 , lowercase , lowercase ) or run_maze(lowercase , lowercase , j - 1 , lowercase ) ): return True SCREAMING_SNAKE_CASE_: str =0 return False return False if __name__ == "__main__": import doctest doctest.testmod()
36
"""simple docstring""" from __future__ import annotations def __magic_name__ ( lowercase , lowercase ): SCREAMING_SNAKE_CASE_: List[Any] =sorted(numsa + numsa ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Tuple =divmod(len(lowercase ) , 2 ) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() _UpperCAmelCase = [float(x) for x in input("""Enter the elements of first array: """).split()] _UpperCAmelCase = [float(x) for x in input("""Enter the elements of second array: """).split()] print(f"""The median of two arrays is: {median_of_two_arrays(array_a, array_a)}""")
36
1
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class a : @staticmethod def lowerCamelCase__ ( *lowerCAmelCase : List[Any] , **lowerCAmelCase : Any ) -> Union[str, Any]: '''simple docstring''' pass @is_pipeline_test @require_vision @require_timm @require_torch class a ( unittest.TestCase ): UpperCamelCase : int = MODEL_FOR_OBJECT_DETECTION_MAPPING def lowerCamelCase__ ( self : Optional[Any] , lowerCAmelCase : Any , lowerCAmelCase : Tuple , lowerCAmelCase : List[str] ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: int =ObjectDetectionPipeline(model=lowerCAmelCase , image_processor=lowerCAmelCase ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def lowerCamelCase__ ( self : List[str] , lowerCAmelCase : Tuple , lowerCAmelCase : Optional[Any] ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: int =object_detector("""./tests/fixtures/tests_samples/COCO/000000039769.png""" , threshold=0.0 ) self.assertGreater(len(lowerCAmelCase ) , 0 ) for detected_object in outputs: self.assertEqual( lowerCAmelCase , { """score""": ANY(lowerCAmelCase ), """label""": ANY(lowerCAmelCase ), """box""": {"""xmin""": ANY(lowerCAmelCase ), """ymin""": ANY(lowerCAmelCase ), """xmax""": ANY(lowerCAmelCase ), """ymax""": ANY(lowerCAmelCase )}, } , ) import datasets SCREAMING_SNAKE_CASE_: Any =datasets.load_dataset("""hf-internal-testing/fixtures_image_utils""" , """image""" , split="""test""" ) SCREAMING_SNAKE_CASE_: str =[ Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ), """http://images.cocodataset.org/val2017/000000039769.jpg""", # RGBA dataset[0]["""file"""], # LA dataset[1]["""file"""], # L dataset[2]["""file"""], ] SCREAMING_SNAKE_CASE_: Any =object_detector(lowerCAmelCase , threshold=0.0 ) self.assertEqual(len(lowerCAmelCase ) , len(lowerCAmelCase ) ) for outputs in batch_outputs: self.assertGreater(len(lowerCAmelCase ) , 0 ) for detected_object in outputs: self.assertEqual( lowerCAmelCase , { """score""": ANY(lowerCAmelCase ), """label""": ANY(lowerCAmelCase ), """box""": {"""xmin""": ANY(lowerCAmelCase ), """ymin""": ANY(lowerCAmelCase ), """xmax""": ANY(lowerCAmelCase ), """ymax""": ANY(lowerCAmelCase )}, } , ) @require_tf @unittest.skip("""Object detection not implemented in TF""" ) def lowerCamelCase__ ( self : Optional[int] ) -> Optional[Any]: '''simple docstring''' pass @require_torch def lowerCamelCase__ ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple ="""hf-internal-testing/tiny-detr-mobilenetsv3""" SCREAMING_SNAKE_CASE_: Union[str, Any] =AutoModelForObjectDetection.from_pretrained(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Any =AutoFeatureExtractor.from_pretrained(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: int =ObjectDetectionPipeline(model=lowerCAmelCase , feature_extractor=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: int =object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=0.0 ) self.assertEqual( nested_simplify(lowerCAmelCase , decimals=4 ) , [ {"""score""": 0.3_3_7_6, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3_3_7_6, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ] , ) SCREAMING_SNAKE_CASE_: str =object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] , threshold=0.0 , ) self.assertEqual( nested_simplify(lowerCAmelCase , decimals=4 ) , [ [ {"""score""": 0.3_3_7_6, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3_3_7_6, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], [ {"""score""": 0.3_3_7_6, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3_3_7_6, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], ] , ) @require_torch @slow def lowerCamelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Union[str, Any] ="""facebook/detr-resnet-50""" SCREAMING_SNAKE_CASE_: Dict =AutoModelForObjectDetection.from_pretrained(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Any =AutoFeatureExtractor.from_pretrained(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple =ObjectDetectionPipeline(model=lowerCAmelCase , feature_extractor=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[Any] =object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(lowerCAmelCase , decimals=4 ) , [ {"""score""": 0.9_9_8_2, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9_9_6_0, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9_9_5_5, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9_9_8_8, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9_9_8_7, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) SCREAMING_SNAKE_CASE_: str =object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(lowerCAmelCase , decimals=4 ) , [ [ {"""score""": 0.9_9_8_2, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9_9_6_0, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9_9_5_5, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9_9_8_8, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9_9_8_7, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9_9_8_2, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9_9_6_0, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9_9_5_5, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9_9_8_8, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9_9_8_7, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def lowerCamelCase__ ( self : int ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any ="""facebook/detr-resnet-50""" SCREAMING_SNAKE_CASE_: int =pipeline("""object-detection""" , model=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(lowerCAmelCase , decimals=4 ) , [ {"""score""": 0.9_9_8_2, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9_9_6_0, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9_9_5_5, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9_9_8_8, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9_9_8_7, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) SCREAMING_SNAKE_CASE_: Any =object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(lowerCAmelCase , decimals=4 ) , [ [ {"""score""": 0.9_9_8_2, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9_9_6_0, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9_9_5_5, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9_9_8_8, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9_9_8_7, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9_9_8_2, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9_9_6_0, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9_9_5_5, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9_9_8_8, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9_9_8_7, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def lowerCamelCase__ ( self : int ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[Any] =0.9_9_8_5 SCREAMING_SNAKE_CASE_: Tuple ="""facebook/detr-resnet-50""" SCREAMING_SNAKE_CASE_: str =pipeline("""object-detection""" , model=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=lowerCAmelCase ) self.assertEqual( nested_simplify(lowerCAmelCase , decimals=4 ) , [ {"""score""": 0.9_9_8_8, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9_9_8_7, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) @require_torch @require_pytesseract @slow def lowerCamelCase__ ( self : Dict ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Union[str, Any] ="""Narsil/layoutlmv3-finetuned-funsd""" SCREAMING_SNAKE_CASE_: Union[str, Any] =0.9_9_9_3 SCREAMING_SNAKE_CASE_: Any =pipeline("""object-detection""" , model=lowerCAmelCase , threshold=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =object_detector( """https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png""" ) self.assertEqual( nested_simplify(lowerCAmelCase , decimals=4 ) , [ {"""score""": 0.9_9_9_3, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, {"""score""": 0.9_9_9_3, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, ] , )
36
"""simple docstring""" import copy import inspect import unittest from transformers import PretrainedConfig, SwiftFormerConfig from transformers.testing_utils import ( require_torch, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwiftFormerForImageClassification, SwiftFormerModel from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class a : def __init__( self : Any , lowerCAmelCase : Any , lowerCAmelCase : List[str]=13 , lowerCAmelCase : Dict=3 , lowerCAmelCase : Optional[Any]=True , lowerCAmelCase : Dict=True , lowerCAmelCase : Dict=0.1 , lowerCAmelCase : str=0.1 , lowerCAmelCase : List[str]=224 , lowerCAmelCase : List[str]=1000 , lowerCAmelCase : Optional[Any]=[3, 3, 6, 4] , lowerCAmelCase : int=[48, 56, 112, 220] , ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[int] =parent SCREAMING_SNAKE_CASE_: Any =batch_size SCREAMING_SNAKE_CASE_: Tuple =num_channels SCREAMING_SNAKE_CASE_: Union[str, Any] =is_training SCREAMING_SNAKE_CASE_: Tuple =use_labels SCREAMING_SNAKE_CASE_: Optional[int] =hidden_dropout_prob SCREAMING_SNAKE_CASE_: Tuple =attention_probs_dropout_prob SCREAMING_SNAKE_CASE_: List[Any] =num_labels SCREAMING_SNAKE_CASE_: int =image_size SCREAMING_SNAKE_CASE_: Optional[Any] =layer_depths SCREAMING_SNAKE_CASE_: List[Any] =embed_dims def lowerCamelCase__ ( self : List[Any] ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[str] =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_: List[Any] =None if self.use_labels: SCREAMING_SNAKE_CASE_: List[str] =ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE_: Tuple =self.get_config() return config, pixel_values, labels def lowerCamelCase__ ( self : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' return SwiftFormerConfig( depths=self.layer_depths , embed_dims=self.embed_dims , mlp_ratio=4 , downsamples=[True, True, True, True] , hidden_act="""gelu""" , num_labels=self.num_labels , down_patch_size=3 , down_stride=2 , down_pad=1 , drop_rate=0.0 , drop_path_rate=0.0 , use_layer_scale=lowerCAmelCase , layer_scale_init_value=1E-5 , ) def lowerCamelCase__ ( self : Any , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Optional[Any] , lowerCAmelCase : Optional[int] ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[str] =SwiftFormerModel(config=lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() SCREAMING_SNAKE_CASE_: Any =model(lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dims[-1], 7, 7) ) def lowerCamelCase__ ( self : Union[str, Any] , lowerCAmelCase : List[Any] , lowerCAmelCase : Optional[int] , lowerCAmelCase : Union[str, Any] ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[Any] =self.num_labels SCREAMING_SNAKE_CASE_: Dict =SwiftFormerForImageClassification(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() SCREAMING_SNAKE_CASE_: Dict =model(lowerCAmelCase , labels=lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) SCREAMING_SNAKE_CASE_: int =SwiftFormerForImageClassification(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() SCREAMING_SNAKE_CASE_: Tuple =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_: Dict =model(lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase__ ( self : int ) -> Optional[Any]: '''simple docstring''' ((SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_)): str =self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_: Tuple ={"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class a ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): UpperCamelCase : Optional[int] = (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else () UpperCamelCase : Tuple = ( {'feature-extraction': SwiftFormerModel, 'image-classification': SwiftFormerForImageClassification} if is_torch_available() else {} ) UpperCamelCase : Any = False UpperCamelCase : Optional[int] = False UpperCamelCase : Optional[Any] = False UpperCamelCase : Dict = False UpperCamelCase : List[str] = False def lowerCamelCase__ ( self : Dict ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =SwiftFormerModelTester(self ) SCREAMING_SNAKE_CASE_: Union[str, Any] =ConfigTester( self , config_class=lowerCAmelCase , has_text_modality=lowerCAmelCase , hidden_size=37 , num_attention_heads=12 , num_hidden_layers=12 , ) def lowerCamelCase__ ( self : Tuple ) -> int: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="""SwiftFormer does not use inputs_embeds""" ) def lowerCamelCase__ ( self : Tuple ) -> List[str]: '''simple docstring''' pass def lowerCamelCase__ ( self : Optional[int] ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[str] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_: Any =model_class(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[Any] =model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCAmelCase , nn.Linear ) ) def lowerCamelCase__ ( self : str ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[Any] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_: int =model_class(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[Any] =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE_: Any =[*signature.parameters.keys()] SCREAMING_SNAKE_CASE_: Tuple =["""pixel_values"""] self.assertListEqual(arg_names[:1] , lowerCAmelCase ) def lowerCamelCase__ ( self : int ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase ) def lowerCamelCase__ ( self : Any ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: int =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase ) @slow def lowerCamelCase__ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_: Optional[Any] =SwiftFormerModel.from_pretrained(lowerCAmelCase ) self.assertIsNotNone(lowerCAmelCase ) @unittest.skip(reason="""SwiftFormer does not output attentions""" ) def lowerCamelCase__ ( self : Optional[int] ) -> str: '''simple docstring''' pass def lowerCamelCase__ ( self : List[Any] ) -> List[str]: '''simple docstring''' def check_hidden_states_output(lowerCAmelCase : Optional[int] , lowerCAmelCase : str , lowerCAmelCase : Optional[int] ): SCREAMING_SNAKE_CASE_: Optional[Any] =model_class(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_: List[str] =model(**self._prepare_for_class(lowerCAmelCase , lowerCAmelCase ) ) SCREAMING_SNAKE_CASE_: Dict =outputs.hidden_states SCREAMING_SNAKE_CASE_: List[Any] =8 self.assertEqual(len(lowerCAmelCase ) , lowerCAmelCase ) # TODO # SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width) # with the width and height being successively divided by 2, after every 2 blocks for i in range(len(lowerCAmelCase ) ): self.assertEqual( hidden_states[i].shape , torch.Size( [ self.model_tester.batch_size, self.model_tester.embed_dims[i // 2], (self.model_tester.image_size // 4) // 2 ** (i // 2), (self.model_tester.image_size // 4) // 2 ** (i // 2), ] ) , ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: int =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_: Dict =True check_hidden_states_output(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE_: Any =True check_hidden_states_output(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) def lowerCamelCase__ ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' def _config_zero_init(lowerCAmelCase : str ): SCREAMING_SNAKE_CASE_: Dict =copy.deepcopy(lowerCAmelCase ) for key in configs_no_init.__dict__.keys(): if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key: setattr(lowerCAmelCase , lowerCAmelCase , 1E-10 ) if isinstance(getattr(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) , lowerCAmelCase ): SCREAMING_SNAKE_CASE_: Tuple =_config_zero_init(getattr(lowerCAmelCase , lowerCAmelCase ) ) setattr(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) return configs_no_init SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[Any] =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_: List[Any] =_config_zero_init(lowerCAmelCase ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_: Any =model_class(config=lowerCAmelCase ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1E9) / 1E9).round().item() , [0.0, 1.0] , msg=f'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def lowerCamelCase__ ( self : List[str] ) -> List[str]: '''simple docstring''' pass def __magic_name__ ( ): SCREAMING_SNAKE_CASE_: List[Any] =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class a ( unittest.TestCase ): @cached_property def lowerCamelCase__ ( self : str ) -> str: '''simple docstring''' return ViTImageProcessor.from_pretrained("""MBZUAI/swiftformer-xs""" ) if is_vision_available() else None @slow def lowerCamelCase__ ( self : Union[str, Any] ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: str =SwiftFormerForImageClassification.from_pretrained("""MBZUAI/swiftformer-xs""" ).to(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: str =self.default_image_processor SCREAMING_SNAKE_CASE_: int =prepare_img() SCREAMING_SNAKE_CASE_: Union[str, Any] =image_processor(images=lowerCAmelCase , return_tensors="""pt""" ).to(lowerCAmelCase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_: Dict =model(**lowerCAmelCase ) # verify the logits SCREAMING_SNAKE_CASE_: Optional[Any] =torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =torch.tensor([[-2.1_703E00, 2.1_107E00, -2.0_811E00]] ).to(lowerCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCAmelCase , atol=1E-4 ) )
36
1
"""simple docstring""" from collections import defaultdict def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: str =1 SCREAMING_SNAKE_CASE_: int =True for v in tree[start]: if v not in visited: ret += dfs(lowercase ) if ret % 2 == 0: cuts.append(lowercase ) return ret def __magic_name__ ( ): dfs(1 ) if __name__ == "__main__": _UpperCAmelCase, _UpperCAmelCase = 1_0, 9 _UpperCAmelCase = defaultdict(list) _UpperCAmelCase = {} _UpperCAmelCase = [] _UpperCAmelCase = 0 _UpperCAmelCase = [(2, 1), (3, 1), (4, 3), (5, 2), (6, 1), (7, 2), (8, 6), (9, 8), (1_0, 8)] for u, v in edges: tree[u].append(v) tree[v].append(u) even_tree() print(len(cuts) - 1)
36
"""simple docstring""" from math import pi def __magic_name__ ( lowercase , lowercase ): return 2 * pi * radius * (angle / 360) if __name__ == "__main__": print(arc_length(9_0, 1_0))
36
1
"""simple docstring""" from __future__ import annotations _UpperCAmelCase = 1.6021e-19 # units = C def __magic_name__ ( lowercase , lowercase , lowercase , ): if (conductivity, electron_conc, mobility).count(0 ) != 1: raise ValueError("""You cannot supply more or less than 2 values""" ) elif conductivity < 0: raise ValueError("""Conductivity cannot be negative""" ) elif electron_conc < 0: raise ValueError("""Electron concentration cannot be negative""" ) elif mobility < 0: raise ValueError("""mobility cannot be negative""" ) elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
36
"""simple docstring""" 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 a ( unittest.TestCase ): def lowerCamelCase__ ( self : Dict ) -> str: '''simple docstring''' super().tearDown() gc.collect() def lowerCamelCase__ ( self : Optional[Any] ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Dict =FlaxStableDiffusionPipeline.from_pretrained( """stabilityai/stable-diffusion-2""" , revision="""bf16""" , dtype=jnp.bfloataa , ) SCREAMING_SNAKE_CASE_: Union[str, Any] ="""A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE_: Any =jax.device_count() SCREAMING_SNAKE_CASE_: Dict =num_samples * [prompt] SCREAMING_SNAKE_CASE_: List[Any] =sd_pipe.prepare_inputs(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Union[str, Any] =replicate(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =shard(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Dict =jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE_: Union[str, Any] =jax.random.split(lowerCAmelCase , jax.device_count() ) SCREAMING_SNAKE_CASE_: Tuple =sd_pipe(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , num_inference_steps=25 , jit=lowerCAmelCase )[0] assert images.shape == (jax.device_count(), 1, 768, 768, 3) SCREAMING_SNAKE_CASE_: Dict =images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) SCREAMING_SNAKE_CASE_: Dict =images[0, 253:256, 253:256, -1] SCREAMING_SNAKE_CASE_: Optional[int] =jnp.asarray(jax.device_get(image_slice.flatten() ) ) SCREAMING_SNAKE_CASE_: Optional[int] =jnp.array([0.4_2_3_8, 0.4_4_1_4, 0.4_3_9_5, 0.4_4_5_3, 0.4_6_2_9, 0.4_5_9_0, 0.4_5_3_1, 0.4_5_5_0_8, 0.4_5_1_2] ) print(f'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2 def lowerCamelCase__ ( self : List[str] ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE_: int ="""stabilityai/stable-diffusion-2""" SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[int] =FlaxDPMSolverMultistepScheduler.from_pretrained(lowerCAmelCase , subfolder="""scheduler""" ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[int] =FlaxStableDiffusionPipeline.from_pretrained( lowerCAmelCase , scheduler=lowerCAmelCase , revision="""bf16""" , dtype=jnp.bfloataa , ) SCREAMING_SNAKE_CASE_: Optional[int] =scheduler_params SCREAMING_SNAKE_CASE_: Tuple ="""A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE_: Union[str, Any] =jax.device_count() SCREAMING_SNAKE_CASE_: Optional[Any] =num_samples * [prompt] SCREAMING_SNAKE_CASE_: List[Any] =sd_pipe.prepare_inputs(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple =replicate(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =shard(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Any =jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE_: Any =jax.random.split(lowerCAmelCase , jax.device_count() ) SCREAMING_SNAKE_CASE_: Tuple =sd_pipe(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , num_inference_steps=25 , jit=lowerCAmelCase )[0] assert images.shape == (jax.device_count(), 1, 768, 768, 3) SCREAMING_SNAKE_CASE_: str =images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) SCREAMING_SNAKE_CASE_: Any =images[0, 253:256, 253:256, -1] SCREAMING_SNAKE_CASE_: Optional[Any] =jnp.asarray(jax.device_get(image_slice.flatten() ) ) SCREAMING_SNAKE_CASE_: Optional[int] =jnp.array([0.4_3_3_6, 0.4_2_9_6_9, 0.4_4_5_3, 0.4_1_9_9, 0.4_2_9_7, 0.4_5_3_1, 0.4_4_3_4, 0.4_4_3_4, 0.4_2_9_7] ) print(f'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2
36
1
"""simple docstring""" def __magic_name__ ( lowercase = 10 ): if not isinstance(lowercase , lowercase ) or n < 0: raise ValueError("""Invalid input""" ) SCREAMING_SNAKE_CASE_: List[Any] =10**n SCREAMING_SNAKE_CASE_: str =2_8433 * (pow(2 , 783_0457 , lowercase )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(f"""{solution(1_0) = }""")
36
"""simple docstring""" def __magic_name__ ( lowercase = 200_0000 ): SCREAMING_SNAKE_CASE_: List[Any] =[0 for i in range(n + 1 )] SCREAMING_SNAKE_CASE_: Union[str, Any] =1 SCREAMING_SNAKE_CASE_: Optional[Any] =1 for i in range(2 , int(n**0.5 ) + 1 ): if primality_list[i] == 0: for j in range(i * i , n + 1 , lowercase ): SCREAMING_SNAKE_CASE_: Optional[int] =1 SCREAMING_SNAKE_CASE_: Dict =0 for i in range(lowercase ): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(f"""{solution() = }""")
36
1
"""simple docstring""" import os import numpy import onnx def __magic_name__ ( lowercase , lowercase ): SCREAMING_SNAKE_CASE_: Union[str, Any] =a.name SCREAMING_SNAKE_CASE_: Dict =b.name SCREAMING_SNAKE_CASE_: Dict ="""""" SCREAMING_SNAKE_CASE_: List[str] ="""""" SCREAMING_SNAKE_CASE_: Optional[int] =a == b SCREAMING_SNAKE_CASE_: int =name_a SCREAMING_SNAKE_CASE_: Optional[int] =name_b return res def __magic_name__ ( lowercase , lowercase , lowercase ): for i, input_name in enumerate(node_proto.input ): if input_name == name: node_proto.input.insert(lowercase , lowercase ) node_proto.input.pop(i + 1 ) if node_proto.op_type == "If": _graph_replace_input_with(node_proto.attribute[0].g , lowercase , lowercase ) _graph_replace_input_with(node_proto.attribute[1].g , lowercase , lowercase ) if node_proto.op_type == "Loop": _graph_replace_input_with(node_proto.attribute[0].g , lowercase , lowercase ) def __magic_name__ ( lowercase , lowercase , lowercase ): for n in graph_proto.node: _node_replace_input_with(lowercase , lowercase , lowercase ) def __magic_name__ ( lowercase , lowercase , lowercase ): SCREAMING_SNAKE_CASE_: Optional[int] =list(model.graph.initializer ) SCREAMING_SNAKE_CASE_: Dict =list(model_without_ext.graph.initializer ) for i, ref_i in ind_to_replace: assert inits_with_data[i].name == inits[i].name assert inits_with_data[ref_i].name == inits[ref_i].name assert i > ref_i SCREAMING_SNAKE_CASE_: List[Any] =inits[i].name SCREAMING_SNAKE_CASE_: List[Any] =inits[ref_i].name model_without_ext.graph.initializer.remove(inits[i] ) # for n in model.graph.node: _graph_replace_input_with(model_without_ext.graph , lowercase , lowercase ) def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Dict =os.path.dirname(lowercase ) SCREAMING_SNAKE_CASE_: List[str] =os.path.basename(lowercase ) SCREAMING_SNAKE_CASE_: List[str] =onnx.load(os.path.join(lowercase , lowercase ) ) SCREAMING_SNAKE_CASE_: Dict =list(model.graph.initializer ) SCREAMING_SNAKE_CASE_: str =set() SCREAMING_SNAKE_CASE_: Tuple ={} SCREAMING_SNAKE_CASE_: Optional[Any] =[] SCREAMING_SNAKE_CASE_: List[str] =0 for i in range(len(lowercase ) ): if i in dup_set: continue for j in range(i + 1 , len(lowercase ) ): if j in dup_set: continue if _is_equal_tensor_proto(inits[i] , inits[j] ): dup_set.add(lowercase ) dup_set.add(lowercase ) SCREAMING_SNAKE_CASE_: Any =inits[j].data_type SCREAMING_SNAKE_CASE_: Any =numpy.prod(inits[j].dims ) if dtype == 1: mem_size *= 4 elif dtype == 6: mem_size *= 4 elif dtype == 7 or dtype == 11: mem_size *= 8 else: print("""unexpected data type: """ , lowercase ) total_reduced_size += mem_size SCREAMING_SNAKE_CASE_: Tuple =inits[i].name SCREAMING_SNAKE_CASE_: Dict =inits[j].name if name_i in dup_map: dup_map[name_i].append(lowercase ) else: SCREAMING_SNAKE_CASE_: int =[name_j] ind_to_replace.append((j, i) ) print("""total reduced size: """ , total_reduced_size / 1024 / 1024 / 1024 , """GB""" ) SCREAMING_SNAKE_CASE_: Optional[Any] =sorted(lowercase ) _remove_dup_initializers_from_model(lowercase , lowercase , lowercase ) SCREAMING_SNAKE_CASE_: Union[str, Any] ="""optimized_""" + model_file_name SCREAMING_SNAKE_CASE_: str =os.path.join(lowercase , lowercase ) onnx.save(lowercase , lowercase ) return new_model
36
"""simple docstring""" import argparse import torch from transformers import BertForMaskedLM if __name__ == "__main__": _UpperCAmelCase = argparse.ArgumentParser( description=( """Extraction some layers of the full BertForMaskedLM or RObertaForMaskedLM for Transfer Learned""" """ Distillation""" ) ) parser.add_argument("""--model_type""", default="""bert""", choices=["""bert"""]) parser.add_argument("""--model_name""", default="""bert-base-uncased""", type=str) parser.add_argument("""--dump_checkpoint""", default="""serialization_dir/tf_bert-base-uncased_0247911.pth""", type=str) parser.add_argument("""--vocab_transform""", action="""store_true""") _UpperCAmelCase = parser.parse_args() if args.model_type == "bert": _UpperCAmelCase = BertForMaskedLM.from_pretrained(args.model_name) _UpperCAmelCase = """bert""" else: raise ValueError("""args.model_type should be \"bert\".""") _UpperCAmelCase = model.state_dict() _UpperCAmelCase = {} for w in ["word_embeddings", "position_embeddings"]: _UpperCAmelCase = state_dict[f"""{prefix}.embeddings.{w}.weight"""] for w in ["weight", "bias"]: _UpperCAmelCase = state_dict[f"""{prefix}.embeddings.LayerNorm.{w}"""] _UpperCAmelCase = 0 for teacher_idx in [0, 2, 4, 7, 9, 1_1]: for w in ["weight", "bias"]: _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.query.{w}""" ] _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.key.{w}""" ] _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.value.{w}""" ] _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.output.dense.{w}""" ] _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.output.LayerNorm.{w}""" ] _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.intermediate.dense.{w}""" ] _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.output.dense.{w}""" ] _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.output.LayerNorm.{w}""" ] std_idx += 1 _UpperCAmelCase = state_dict["""cls.predictions.decoder.weight"""] _UpperCAmelCase = state_dict["""cls.predictions.bias"""] if args.vocab_transform: for w in ["weight", "bias"]: _UpperCAmelCase = state_dict[f"""cls.predictions.transform.dense.{w}"""] _UpperCAmelCase = state_dict[f"""cls.predictions.transform.LayerNorm.{w}"""] print(f"""N layers selected for distillation: {std_idx}""") print(f"""Number of params transferred for distillation: {len(compressed_sd.keys())}""") print(f"""Save transferred checkpoint to {args.dump_checkpoint}.""") torch.save(compressed_sd, args.dump_checkpoint)
36
1
"""simple docstring""" def __magic_name__ ( lowercase = 100 ): SCREAMING_SNAKE_CASE_: str =set() SCREAMING_SNAKE_CASE_: int =0 SCREAMING_SNAKE_CASE_: Optional[Any] =n + 1 # maximum limit for a in range(2 , lowercase ): for b in range(2 , lowercase ): SCREAMING_SNAKE_CASE_: List[Any] =a**b # calculates the current power collect_powers.add(lowercase ) # adds the result to the set return len(lowercase ) if __name__ == "__main__": print("""Number of terms """, solution(int(str(input()).strip())))
36
"""simple docstring""" def __magic_name__ ( lowercase , lowercase ): return int((input_a, input_a).count(0 ) == 0 ) def __magic_name__ ( ): assert and_gate(0 , 0 ) == 0 assert and_gate(0 , 1 ) == 0 assert and_gate(1 , 0 ) == 0 assert and_gate(1 , 1 ) == 1 if __name__ == "__main__": test_and_gate() print(and_gate(1, 0)) print(and_gate(0, 0)) print(and_gate(0, 1)) print(and_gate(1, 1))
36
1
"""simple docstring""" _UpperCAmelCase = [ 9_9_9, 8_0_0, 7_9_9, 6_0_0, 5_9_9, 5_0_0, 4_0_0, 3_9_9, 3_7_7, 3_5_5, 3_3_3, 3_1_1, 2_8_8, 2_6_6, 2_4_4, 2_2_2, 2_0_0, 1_9_9, 1_7_7, 1_5_5, 1_3_3, 1_1_1, 8_8, 6_6, 4_4, 2_2, 0, ] _UpperCAmelCase = [ 9_9_9, 9_7_6, 9_5_2, 9_2_8, 9_0_5, 8_8_2, 8_5_8, 8_5_7, 8_1_0, 7_6_2, 7_1_5, 7_1_4, 5_7_2, 4_2_9, 4_2_8, 2_8_6, 2_8_5, 2_3_8, 1_9_0, 1_4_3, 1_4_2, 1_1_8, 9_5, 7_1, 4_7, 2_4, 0, ] _UpperCAmelCase = [ 9_9_9, 9_8_8, 9_7_7, 9_6_6, 9_5_5, 9_4_4, 9_3_3, 9_2_2, 9_1_1, 9_0_0, 8_9_9, 8_7_9, 8_5_9, 8_4_0, 8_2_0, 8_0_0, 7_9_9, 7_6_6, 7_3_3, 7_0_0, 6_9_9, 6_5_0, 6_0_0, 5_9_9, 5_0_0, 4_9_9, 4_0_0, 3_9_9, 3_5_0, 3_0_0, 2_9_9, 2_6_6, 2_3_3, 2_0_0, 1_9_9, 1_7_9, 1_5_9, 1_4_0, 1_2_0, 1_0_0, 9_9, 8_8, 7_7, 6_6, 5_5, 4_4, 3_3, 2_2, 1_1, 0, ] _UpperCAmelCase = [ 9_9_9, 9_9_5, 9_9_2, 9_8_9, 9_8_5, 9_8_1, 9_7_8, 9_7_5, 9_7_1, 9_6_7, 9_6_4, 9_6_1, 9_5_7, 9_5_6, 9_5_1, 9_4_7, 9_4_2, 9_3_7, 9_3_3, 9_2_8, 9_2_3, 9_1_9, 9_1_4, 9_1_3, 9_0_8, 9_0_3, 8_9_7, 8_9_2, 8_8_7, 8_8_1, 8_7_6, 8_7_1, 8_7_0, 8_6_4, 8_5_8, 8_5_2, 8_4_6, 8_4_0, 8_3_4, 8_2_8, 8_2_7, 8_2_0, 8_1_3, 8_0_6, 7_9_9, 7_9_2, 7_8_5, 7_8_4, 7_7_7, 7_7_0, 7_6_3, 7_5_6, 7_4_9, 7_4_2, 7_4_1, 7_3_3, 7_2_4, 7_1_6, 7_0_7, 6_9_9, 6_9_8, 6_8_8, 6_7_7, 6_6_6, 6_5_6, 6_5_5, 6_4_5, 6_3_4, 6_2_3, 6_1_3, 6_1_2, 5_9_8, 5_8_4, 5_7_0, 5_6_9, 5_5_5, 5_4_1, 5_2_7, 5_2_6, 5_0_5, 4_8_4, 4_8_3, 4_6_2, 4_4_0, 4_3_9, 3_9_6, 3_9_5, 3_5_2, 3_5_1, 3_0_8, 3_0_7, 2_6_4, 2_6_3, 2_2_0, 2_1_9, 1_7_6, 1_3_2, 8_8, 4_4, 0, ] _UpperCAmelCase = [ 9_9_9, 9_9_7, 9_9_5, 9_9_2, 9_9_0, 9_8_8, 9_8_6, 9_8_4, 9_8_1, 9_7_9, 9_7_7, 9_7_5, 9_7_2, 9_7_0, 9_6_8, 9_6_6, 9_6_4, 9_6_1, 9_5_9, 9_5_7, 9_5_6, 9_5_4, 9_5_1, 9_4_9, 9_4_6, 9_4_4, 9_4_1, 9_3_9, 9_3_6, 9_3_4, 9_3_1, 9_2_9, 9_2_6, 9_2_4, 9_2_1, 9_1_9, 9_1_6, 9_1_4, 9_1_3, 9_1_0, 9_0_7, 9_0_5, 9_0_2, 8_9_9, 8_9_6, 8_9_3, 8_9_1, 8_8_8, 8_8_5, 8_8_2, 8_7_9, 8_7_7, 8_7_4, 8_7_1, 8_7_0, 8_6_7, 8_6_4, 8_6_1, 8_5_8, 8_5_5, 8_5_2, 8_4_9, 8_4_6, 8_4_3, 8_4_0, 8_3_7, 8_3_4, 8_3_1, 8_2_8, 8_2_7, 8_2_4, 8_2_1, 8_1_7, 8_1_4, 8_1_1, 8_0_8, 8_0_4, 8_0_1, 7_9_8, 7_9_5, 7_9_1, 7_8_8, 7_8_5, 7_8_4, 7_8_0, 7_7_7, 7_7_4, 7_7_0, 7_6_6, 7_6_3, 7_6_0, 7_5_6, 7_5_2, 7_4_9, 7_4_6, 7_4_2, 7_4_1, 7_3_7, 7_3_3, 7_3_0, 7_2_6, 7_2_2, 7_1_8, 7_1_4, 7_1_0, 7_0_7, 7_0_3, 6_9_9, 6_9_8, 6_9_4, 6_9_0, 6_8_5, 6_8_1, 6_7_7, 6_7_3, 6_6_9, 6_6_4, 6_6_0, 6_5_6, 6_5_5, 6_5_0, 6_4_6, 6_4_1, 6_3_6, 6_3_2, 6_2_7, 6_2_2, 6_1_8, 6_1_3, 6_1_2, 6_0_7, 6_0_2, 5_9_6, 5_9_1, 5_8_6, 5_8_0, 5_7_5, 5_7_0, 5_6_9, 5_6_3, 5_5_7, 5_5_1, 5_4_5, 5_3_9, 5_3_3, 5_2_7, 5_2_6, 5_1_9, 5_1_2, 5_0_5, 4_9_8, 4_9_1, 4_8_4, 4_8_3, 4_7_4, 4_6_6, 4_5_7, 4_4_9, 4_4_0, 4_3_9, 4_2_8, 4_1_8, 4_0_7, 3_9_6, 3_9_5, 3_8_1, 3_6_6, 3_5_2, 3_5_1, 3_3_0, 3_0_8, 3_0_7, 2_8_6, 2_6_4, 2_6_3, 2_4_2, 2_2_0, 2_1_9, 1_7_6, 1_7_5, 1_3_2, 1_3_1, 8_8, 4_4, 0, ] _UpperCAmelCase = [ 9_9_9, 9_9_1, 9_8_2, 9_7_4, 9_6_6, 9_5_8, 9_5_0, 9_4_1, 9_3_3, 9_2_5, 9_1_6, 9_0_8, 9_0_0, 8_9_9, 8_7_4, 8_5_0, 8_2_5, 8_0_0, 7_9_9, 7_0_0, 6_0_0, 5_0_0, 4_0_0, 3_0_0, 2_0_0, 1_0_0, 0, ] _UpperCAmelCase = [ 9_9_9, 9_9_2, 9_8_5, 9_7_8, 9_7_1, 9_6_4, 9_5_7, 9_4_9, 9_4_2, 9_3_5, 9_2_8, 9_2_1, 9_1_4, 9_0_7, 9_0_0, 8_9_9, 8_7_9, 8_5_9, 8_4_0, 8_2_0, 8_0_0, 7_9_9, 7_6_6, 7_3_3, 7_0_0, 6_9_9, 6_5_0, 6_0_0, 5_9_9, 5_0_0, 4_9_9, 4_0_0, 3_9_9, 3_0_0, 2_9_9, 2_0_0, 1_9_9, 1_0_0, 9_9, 0, ] _UpperCAmelCase = [ 9_9_9, 9_9_6, 9_9_2, 9_8_9, 9_8_5, 9_8_2, 9_7_9, 9_7_5, 9_7_2, 9_6_8, 9_6_5, 9_6_1, 9_5_8, 9_5_5, 9_5_1, 9_4_8, 9_4_4, 9_4_1, 9_3_8, 9_3_4, 9_3_1, 9_2_7, 9_2_4, 9_2_0, 9_1_7, 9_1_4, 9_1_0, 9_0_7, 9_0_3, 9_0_0, 8_9_9, 8_9_1, 8_8_4, 8_7_6, 8_6_9, 8_6_1, 8_5_3, 8_4_6, 8_3_8, 8_3_0, 8_2_3, 8_1_5, 8_0_8, 8_0_0, 7_9_9, 7_8_8, 7_7_7, 7_6_6, 7_5_5, 7_4_4, 7_3_3, 7_2_2, 7_1_1, 7_0_0, 6_9_9, 6_8_8, 6_7_7, 6_6_6, 6_5_5, 6_4_4, 6_3_3, 6_2_2, 6_1_1, 6_0_0, 5_9_9, 5_8_5, 5_7_1, 5_5_7, 5_4_2, 5_2_8, 5_1_4, 5_0_0, 4_9_9, 4_8_5, 4_7_1, 4_5_7, 4_4_2, 4_2_8, 4_1_4, 4_0_0, 3_9_9, 3_7_9, 3_5_9, 3_4_0, 3_2_0, 3_0_0, 2_9_9, 2_7_9, 2_5_9, 2_4_0, 2_2_0, 2_0_0, 1_9_9, 1_6_6, 1_3_3, 1_0_0, 9_9, 6_6, 3_3, 0, ]
36
"""simple docstring""" import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() _UpperCAmelCase = logging.get_logger("""transformers.models.speecht5""") def __magic_name__ ( lowercase , lowercase , lowercase ): hf_model.apply_weight_norm() SCREAMING_SNAKE_CASE_: Tuple =checkpoint["""input_conv.weight_g"""] SCREAMING_SNAKE_CASE_: Optional[int] =checkpoint["""input_conv.weight_v"""] SCREAMING_SNAKE_CASE_: Optional[int] =checkpoint["""input_conv.bias"""] for i in range(len(config.upsample_rates ) ): SCREAMING_SNAKE_CASE_: Any =checkpoint[f'''upsamples.{i}.1.weight_g'''] SCREAMING_SNAKE_CASE_: Any =checkpoint[f'''upsamples.{i}.1.weight_v'''] SCREAMING_SNAKE_CASE_: List[str] =checkpoint[f'''upsamples.{i}.1.bias'''] for i in range(len(config.upsample_rates ) * len(config.resblock_kernel_sizes ) ): for j in range(len(config.resblock_dilation_sizes ) ): SCREAMING_SNAKE_CASE_: Dict =checkpoint[f'''blocks.{i}.convs1.{j}.1.weight_g'''] SCREAMING_SNAKE_CASE_: Any =checkpoint[f'''blocks.{i}.convs1.{j}.1.weight_v'''] SCREAMING_SNAKE_CASE_: Union[str, Any] =checkpoint[f'''blocks.{i}.convs1.{j}.1.bias'''] SCREAMING_SNAKE_CASE_: Dict =checkpoint[f'''blocks.{i}.convs2.{j}.1.weight_g'''] SCREAMING_SNAKE_CASE_: Any =checkpoint[f'''blocks.{i}.convs2.{j}.1.weight_v'''] SCREAMING_SNAKE_CASE_: List[Any] =checkpoint[f'''blocks.{i}.convs2.{j}.1.bias'''] SCREAMING_SNAKE_CASE_: Tuple =checkpoint["""output_conv.1.weight_g"""] SCREAMING_SNAKE_CASE_: List[str] =checkpoint["""output_conv.1.weight_v"""] SCREAMING_SNAKE_CASE_: Optional[int] =checkpoint["""output_conv.1.bias"""] hf_model.remove_weight_norm() @torch.no_grad() def __magic_name__ ( lowercase , lowercase , lowercase , lowercase=None , lowercase=None , ): if config_path is not None: SCREAMING_SNAKE_CASE_: List[Any] =SpeechTaHifiGanConfig.from_pretrained(lowercase ) else: SCREAMING_SNAKE_CASE_: Optional[Any] =SpeechTaHifiGanConfig() SCREAMING_SNAKE_CASE_: Union[str, Any] =SpeechTaHifiGan(lowercase ) SCREAMING_SNAKE_CASE_: Any =torch.load(lowercase ) load_weights(orig_checkpoint["""model"""]["""generator"""] , lowercase , lowercase ) SCREAMING_SNAKE_CASE_: List[Any] =np.load(lowercase ) SCREAMING_SNAKE_CASE_: Any =stats[0].reshape(-1 ) SCREAMING_SNAKE_CASE_: str =stats[1].reshape(-1 ) SCREAMING_SNAKE_CASE_: Dict =torch.from_numpy(lowercase ).float() SCREAMING_SNAKE_CASE_: Dict =torch.from_numpy(lowercase ).float() model.save_pretrained(lowercase ) if repo_id: print("""Pushing to the hub...""" ) model.push_to_hub(lowercase ) if __name__ == "__main__": _UpperCAmelCase = argparse.ArgumentParser() parser.add_argument("""--checkpoint_path""", required=True, default=None, type=str, help="""Path to original checkpoint""") parser.add_argument("""--stats_path""", required=True, default=None, type=str, help="""Path to stats.npy file""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--pytorch_dump_folder_path""", required=True, default=None, type=str, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--push_to_hub""", default=None, type=str, help="""Where to upload the converted model on the 🤗 hub.""" ) _UpperCAmelCase = parser.parse_args() convert_hifigan_checkpoint( args.checkpoint_path, args.stats_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
36
1
"""simple docstring""" import numpy as np def __magic_name__ ( lowercase ): return (2 / (1 + np.exp(-2 * vector ))) - 1 if __name__ == "__main__": import doctest doctest.testmod()
36
"""simple docstring""" import argparse import requests import torch from PIL import Image from transformers import ViTMAEConfig, ViTMAEForPreTraining, ViTMAEImageProcessor def __magic_name__ ( lowercase ): if "cls_token" in name: SCREAMING_SNAKE_CASE_: Optional[int] =name.replace("""cls_token""" , """vit.embeddings.cls_token""" ) if "mask_token" in name: SCREAMING_SNAKE_CASE_: Optional[int] =name.replace("""mask_token""" , """decoder.mask_token""" ) if "decoder_pos_embed" in name: SCREAMING_SNAKE_CASE_: int =name.replace("""decoder_pos_embed""" , """decoder.decoder_pos_embed""" ) if "pos_embed" in name and "decoder" not in name: SCREAMING_SNAKE_CASE_: str =name.replace("""pos_embed""" , """vit.embeddings.position_embeddings""" ) if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE_: str =name.replace("""patch_embed.proj""" , """vit.embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: SCREAMING_SNAKE_CASE_: int =name.replace("""patch_embed.norm""" , """vit.embeddings.norm""" ) if "decoder_blocks" in name: SCREAMING_SNAKE_CASE_: List[Any] =name.replace("""decoder_blocks""" , """decoder.decoder_layers""" ) if "blocks" in name: SCREAMING_SNAKE_CASE_: str =name.replace("""blocks""" , """vit.encoder.layer""" ) if "attn.proj" in name: SCREAMING_SNAKE_CASE_: Optional[Any] =name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: SCREAMING_SNAKE_CASE_: Union[str, Any] =name.replace("""attn""" , """attention.self""" ) if "norm1" in name: SCREAMING_SNAKE_CASE_: Optional[Any] =name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: SCREAMING_SNAKE_CASE_: int =name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE_: int =name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE_: Dict =name.replace("""mlp.fc2""" , """output.dense""" ) if "decoder_embed" in name: SCREAMING_SNAKE_CASE_: List[str] =name.replace("""decoder_embed""" , """decoder.decoder_embed""" ) if "decoder_norm" in name: SCREAMING_SNAKE_CASE_: Tuple =name.replace("""decoder_norm""" , """decoder.decoder_norm""" ) if "decoder_pred" in name: SCREAMING_SNAKE_CASE_: Any =name.replace("""decoder_pred""" , """decoder.decoder_pred""" ) if "norm.weight" in name and "decoder" not in name: SCREAMING_SNAKE_CASE_: List[str] =name.replace("""norm.weight""" , """vit.layernorm.weight""" ) if "norm.bias" in name and "decoder" not in name: SCREAMING_SNAKE_CASE_: List[str] =name.replace("""norm.bias""" , """vit.layernorm.bias""" ) return name def __magic_name__ ( lowercase , lowercase ): for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE_: Optional[int] =orig_state_dict.pop(lowercase ) if "qkv" in key: SCREAMING_SNAKE_CASE_: Dict =key.split(""".""" ) SCREAMING_SNAKE_CASE_: Optional[Any] =int(key_split[1] ) if "decoder_blocks" in key: SCREAMING_SNAKE_CASE_: int =config.decoder_hidden_size SCREAMING_SNAKE_CASE_: Optional[int] ="""decoder.decoder_layers.""" if "weight" in key: SCREAMING_SNAKE_CASE_: Dict =val[:dim, :] SCREAMING_SNAKE_CASE_: Tuple =val[dim : dim * 2, :] SCREAMING_SNAKE_CASE_: str =val[-dim:, :] elif "bias" in key: SCREAMING_SNAKE_CASE_: List[Any] =val[:dim] SCREAMING_SNAKE_CASE_: Tuple =val[dim : dim * 2] SCREAMING_SNAKE_CASE_: List[Any] =val[-dim:] else: SCREAMING_SNAKE_CASE_: Any =config.hidden_size SCREAMING_SNAKE_CASE_: Union[str, Any] ="""vit.encoder.layer.""" if "weight" in key: SCREAMING_SNAKE_CASE_: Optional[Any] =val[:dim, :] SCREAMING_SNAKE_CASE_: Optional[Any] =val[dim : dim * 2, :] SCREAMING_SNAKE_CASE_: Dict =val[-dim:, :] elif "bias" in key: SCREAMING_SNAKE_CASE_: Optional[Any] =val[:dim] SCREAMING_SNAKE_CASE_: Any =val[dim : dim * 2] SCREAMING_SNAKE_CASE_: Optional[Any] =val[-dim:] else: SCREAMING_SNAKE_CASE_: Tuple =val return orig_state_dict def __magic_name__ ( lowercase , lowercase ): SCREAMING_SNAKE_CASE_: Dict =ViTMAEConfig() if "large" in checkpoint_url: SCREAMING_SNAKE_CASE_: List[Any] =1024 SCREAMING_SNAKE_CASE_: Dict =4096 SCREAMING_SNAKE_CASE_: Tuple =24 SCREAMING_SNAKE_CASE_: int =16 elif "huge" in checkpoint_url: SCREAMING_SNAKE_CASE_: Union[str, Any] =14 SCREAMING_SNAKE_CASE_: Any =1280 SCREAMING_SNAKE_CASE_: Dict =5120 SCREAMING_SNAKE_CASE_: Optional[int] =32 SCREAMING_SNAKE_CASE_: Optional[Any] =16 SCREAMING_SNAKE_CASE_: Tuple =ViTMAEForPreTraining(lowercase ) SCREAMING_SNAKE_CASE_: Optional[int] =torch.hub.load_state_dict_from_url(lowercase , map_location="""cpu""" )["""model"""] SCREAMING_SNAKE_CASE_: Optional[Any] =ViTMAEImageProcessor(size=config.image_size ) SCREAMING_SNAKE_CASE_: str =convert_state_dict(lowercase , lowercase ) model.load_state_dict(lowercase ) model.eval() SCREAMING_SNAKE_CASE_: Tuple ="""https://user-images.githubusercontent.com/11435359/147738734-196fd92f-9260-48d5-ba7e-bf103d29364d.jpg""" SCREAMING_SNAKE_CASE_: List[Any] =Image.open(requests.get(lowercase , stream=lowercase ).raw ) SCREAMING_SNAKE_CASE_: int =ViTMAEImageProcessor(size=config.image_size ) SCREAMING_SNAKE_CASE_: int =image_processor(images=lowercase , return_tensors="""pt""" ) # forward pass torch.manual_seed(2 ) SCREAMING_SNAKE_CASE_: Optional[Any] =model(**lowercase ) SCREAMING_SNAKE_CASE_: Optional[int] =outputs.logits if "large" in checkpoint_url: SCREAMING_SNAKE_CASE_: Dict =torch.tensor( [[-0.7_309, -0.7_128, -1.0_169], [-1.0_161, -0.9_058, -1.1_878], [-1.0_478, -0.9_411, -1.1_911]] ) elif "huge" in checkpoint_url: SCREAMING_SNAKE_CASE_: Tuple =torch.tensor( [[-1.1_599, -0.9_199, -1.2_221], [-1.1_952, -0.9_269, -1.2_307], [-1.2_143, -0.9_337, -1.2_262]] ) else: SCREAMING_SNAKE_CASE_: Any =torch.tensor( [[-0.9_192, -0.8_481, -1.1_259], [-1.1_349, -1.0_034, -1.2_599], [-1.1_757, -1.0_429, -1.2_726]] ) # verify logits assert torch.allclose(logits[0, :3, :3] , lowercase , atol=1e-4 ) print(f'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowercase ) if __name__ == "__main__": _UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--checkpoint_url""", default="""https://dl.fbaipublicfiles.com/mae/visualize/mae_visualize_vit_base.pth""", type=str, help="""URL of the checkpoint you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) _UpperCAmelCase = parser.parse_args() convert_vit_mae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
36
1
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL _UpperCAmelCase = logging.get_logger(__name__) def __magic_name__ ( lowercase ): if isinstance(lowercase , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(lowercase , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(lowercase ): return [[videos]] raise ValueError(f'''Could not make batched video from {videos}''' ) class a ( UpperCAmelCase__ ): UpperCamelCase : str = ['pixel_values'] def __init__( self : List[str] , lowerCAmelCase : bool = True , lowerCAmelCase : Dict[str, int] = None , lowerCAmelCase : PILImageResampling = PILImageResampling.BILINEAR , lowerCAmelCase : bool = True , lowerCAmelCase : Dict[str, int] = None , lowerCAmelCase : bool = True , lowerCAmelCase : Union[int, float] = 1 / 255 , lowerCAmelCase : bool = True , lowerCAmelCase : Optional[Union[float, List[float]]] = None , lowerCAmelCase : Optional[Union[float, List[float]]] = None , **lowerCAmelCase : List[Any] , ) -> None: '''simple docstring''' super().__init__(**lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Dict =size if size is not None else {"""shortest_edge""": 224} SCREAMING_SNAKE_CASE_: Tuple =get_size_dict(lowerCAmelCase , default_to_square=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Union[str, Any] =crop_size if crop_size is not None else {"""height""": 224, """width""": 224} SCREAMING_SNAKE_CASE_: Optional[Any] =get_size_dict(lowerCAmelCase , param_name="""crop_size""" ) SCREAMING_SNAKE_CASE_: Optional[int] =do_resize SCREAMING_SNAKE_CASE_: List[Any] =size SCREAMING_SNAKE_CASE_: List[str] =do_center_crop SCREAMING_SNAKE_CASE_: Tuple =crop_size SCREAMING_SNAKE_CASE_: List[Any] =resample SCREAMING_SNAKE_CASE_: List[str] =do_rescale SCREAMING_SNAKE_CASE_: Tuple =rescale_factor SCREAMING_SNAKE_CASE_: Optional[Any] =do_normalize SCREAMING_SNAKE_CASE_: int =image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE_: Tuple =image_std if image_std is not None else IMAGENET_STANDARD_STD def lowerCamelCase__ ( self : Dict , lowerCAmelCase : np.ndarray , lowerCAmelCase : Dict[str, int] , lowerCAmelCase : PILImageResampling = PILImageResampling.BILINEAR , lowerCAmelCase : Optional[Union[str, ChannelDimension]] = None , **lowerCAmelCase : Union[str, Any] , ) -> np.ndarray: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =get_size_dict(lowerCAmelCase , default_to_square=lowerCAmelCase ) if "shortest_edge" in size: SCREAMING_SNAKE_CASE_: str =get_resize_output_image_size(lowerCAmelCase , size["""shortest_edge"""] , default_to_square=lowerCAmelCase ) elif "height" in size and "width" in size: SCREAMING_SNAKE_CASE_: Optional[int] =(size["""height"""], size["""width"""]) else: raise ValueError(f'''Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}''' ) return resize(lowerCAmelCase , size=lowerCAmelCase , resample=lowerCAmelCase , data_format=lowerCAmelCase , **lowerCAmelCase ) def lowerCamelCase__ ( self : str , lowerCAmelCase : np.ndarray , lowerCAmelCase : Dict[str, int] , lowerCAmelCase : Optional[Union[str, ChannelDimension]] = None , **lowerCAmelCase : Optional[int] , ) -> np.ndarray: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[Any] =get_size_dict(lowerCAmelCase ) if "height" not in size or "width" not in size: raise ValueError(f'''Size must have \'height\' and \'width\' as keys. Got {size.keys()}''' ) return center_crop(lowerCAmelCase , size=(size["""height"""], size["""width"""]) , data_format=lowerCAmelCase , **lowerCAmelCase ) def lowerCamelCase__ ( self : str , lowerCAmelCase : np.ndarray , lowerCAmelCase : Union[int, float] , lowerCAmelCase : Optional[Union[str, ChannelDimension]] = None , **lowerCAmelCase : int , ) -> List[str]: '''simple docstring''' return rescale(lowerCAmelCase , scale=lowerCAmelCase , data_format=lowerCAmelCase , **lowerCAmelCase ) def lowerCamelCase__ ( self : Any , lowerCAmelCase : np.ndarray , lowerCAmelCase : Union[float, List[float]] , lowerCAmelCase : Union[float, List[float]] , lowerCAmelCase : Optional[Union[str, ChannelDimension]] = None , **lowerCAmelCase : int , ) -> np.ndarray: '''simple docstring''' return normalize(lowerCAmelCase , mean=lowerCAmelCase , std=lowerCAmelCase , data_format=lowerCAmelCase , **lowerCAmelCase ) def lowerCamelCase__ ( self : Optional[Any] , lowerCAmelCase : ImageInput , lowerCAmelCase : bool = None , lowerCAmelCase : Dict[str, int] = None , lowerCAmelCase : PILImageResampling = None , lowerCAmelCase : bool = None , lowerCAmelCase : Dict[str, int] = None , lowerCAmelCase : bool = None , lowerCAmelCase : float = None , lowerCAmelCase : bool = None , lowerCAmelCase : Optional[Union[float, List[float]]] = None , lowerCAmelCase : Optional[Union[float, List[float]]] = None , lowerCAmelCase : Optional[ChannelDimension] = ChannelDimension.FIRST , ) -> np.ndarray: '''simple docstring''' if do_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE_: Any =to_numpy_array(lowerCAmelCase ) if do_resize: SCREAMING_SNAKE_CASE_: Optional[Any] =self.resize(image=lowerCAmelCase , size=lowerCAmelCase , resample=lowerCAmelCase ) if do_center_crop: SCREAMING_SNAKE_CASE_: Tuple =self.center_crop(lowerCAmelCase , size=lowerCAmelCase ) if do_rescale: SCREAMING_SNAKE_CASE_: Tuple =self.rescale(image=lowerCAmelCase , scale=lowerCAmelCase ) if do_normalize: SCREAMING_SNAKE_CASE_: Optional[Any] =self.normalize(image=lowerCAmelCase , mean=lowerCAmelCase , std=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: str =to_channel_dimension_format(lowerCAmelCase , lowerCAmelCase ) return image def lowerCamelCase__ ( self : List[str] , lowerCAmelCase : ImageInput , lowerCAmelCase : bool = None , lowerCAmelCase : Dict[str, int] = None , lowerCAmelCase : PILImageResampling = None , lowerCAmelCase : bool = None , lowerCAmelCase : Dict[str, int] = None , lowerCAmelCase : bool = None , lowerCAmelCase : float = None , lowerCAmelCase : bool = None , lowerCAmelCase : Optional[Union[float, List[float]]] = None , lowerCAmelCase : Optional[Union[float, List[float]]] = None , lowerCAmelCase : Optional[Union[str, TensorType]] = None , lowerCAmelCase : ChannelDimension = ChannelDimension.FIRST , **lowerCAmelCase : List[str] , ) -> PIL.Image.Image: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[Any] =do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE_: Dict =resample if resample is not None else self.resample SCREAMING_SNAKE_CASE_: List[str] =do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE_: Tuple =do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE_: List[str] =rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE_: List[str] =do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE_: str =image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE_: List[Any] =image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE_: Optional[int] =size if size is not None else self.size SCREAMING_SNAKE_CASE_: Dict =get_size_dict(lowerCAmelCase , default_to_square=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: int =crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE_: List[str] =get_size_dict(lowerCAmelCase , param_name="""crop_size""" ) if not valid_images(lowerCAmelCase ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) SCREAMING_SNAKE_CASE_: Tuple =make_batched(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =[ [ self._preprocess_image( image=lowerCAmelCase , do_resize=lowerCAmelCase , size=lowerCAmelCase , resample=lowerCAmelCase , do_center_crop=lowerCAmelCase , crop_size=lowerCAmelCase , do_rescale=lowerCAmelCase , rescale_factor=lowerCAmelCase , do_normalize=lowerCAmelCase , image_mean=lowerCAmelCase , image_std=lowerCAmelCase , data_format=lowerCAmelCase , ) for img in video ] for video in videos ] SCREAMING_SNAKE_CASE_: Union[str, Any] ={"""pixel_values""": videos} return BatchFeature(data=lowerCAmelCase , tensor_type=lowerCAmelCase )
36
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _UpperCAmelCase = { """configuration_xlm""": ["""XLM_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XLMConfig""", """XLMOnnxConfig"""], """tokenization_xlm""": ["""XLMTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ """XLM_PRETRAINED_MODEL_ARCHIVE_LIST""", """XLMForMultipleChoice""", """XLMForQuestionAnswering""", """XLMForQuestionAnsweringSimple""", """XLMForSequenceClassification""", """XLMForTokenClassification""", """XLMModel""", """XLMPreTrainedModel""", """XLMWithLMHeadModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ """TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFXLMForMultipleChoice""", """TFXLMForQuestionAnsweringSimple""", """TFXLMForSequenceClassification""", """TFXLMForTokenClassification""", """TFXLMMainLayer""", """TFXLMModel""", """TFXLMPreTrainedModel""", """TFXLMWithLMHeadModel""", ] if TYPE_CHECKING: from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig from .tokenization_xlm import XLMTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm import ( XLM_PRETRAINED_MODEL_ARCHIVE_LIST, XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMPreTrainedModel, XLMWithLMHeadModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm import ( TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMForMultipleChoice, TFXLMForQuestionAnsweringSimple, TFXLMForSequenceClassification, TFXLMForTokenClassification, TFXLMMainLayer, TFXLMModel, TFXLMPreTrainedModel, TFXLMWithLMHeadModel, ) else: import sys _UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
36
1
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_url from PIL import Image from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor from transformers.utils import logging logging.set_verbosity_info() _UpperCAmelCase = logging.get_logger(__name__) def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Union[str, Any] =DPTConfig() if "large" in checkpoint_url: SCREAMING_SNAKE_CASE_: int =1024 SCREAMING_SNAKE_CASE_: Dict =4096 SCREAMING_SNAKE_CASE_: Optional[int] =24 SCREAMING_SNAKE_CASE_: Optional[Any] =16 SCREAMING_SNAKE_CASE_: Dict =[5, 11, 17, 23] SCREAMING_SNAKE_CASE_: Union[str, Any] =[256, 512, 1024, 1024] SCREAMING_SNAKE_CASE_: Union[str, Any] =(1, 384, 384) if "ade" in checkpoint_url: SCREAMING_SNAKE_CASE_: Tuple =True SCREAMING_SNAKE_CASE_: int =150 SCREAMING_SNAKE_CASE_: Union[str, Any] ="""huggingface/label-files""" SCREAMING_SNAKE_CASE_: List[str] ="""ade20k-id2label.json""" SCREAMING_SNAKE_CASE_: Tuple =json.load(open(cached_download(hf_hub_url(lowercase , lowercase , repo_type="""dataset""" ) ) , """r""" ) ) SCREAMING_SNAKE_CASE_: int ={int(lowercase ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_: Optional[Any] =idalabel SCREAMING_SNAKE_CASE_: Dict ={v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_: Dict =[1, 150, 480, 480] return config, expected_shape def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Optional[Any] =["""pretrained.model.head.weight""", """pretrained.model.head.bias"""] for k in ignore_keys: state_dict.pop(lowercase , lowercase ) def __magic_name__ ( lowercase ): if ( "pretrained.model" in name and "cls_token" not in name and "pos_embed" not in name and "patch_embed" not in name ): SCREAMING_SNAKE_CASE_: Dict =name.replace("""pretrained.model""" , """dpt.encoder""" ) if "pretrained.model" in name: SCREAMING_SNAKE_CASE_: List[Any] =name.replace("""pretrained.model""" , """dpt.embeddings""" ) if "patch_embed" in name: SCREAMING_SNAKE_CASE_: List[Any] =name.replace("""patch_embed""" , """patch_embeddings""" ) if "pos_embed" in name: SCREAMING_SNAKE_CASE_: Union[str, Any] =name.replace("""pos_embed""" , """position_embeddings""" ) if "attn.proj" in name: SCREAMING_SNAKE_CASE_: Optional[Any] =name.replace("""attn.proj""" , """attention.output.dense""" ) if "proj" in name and "project" not in name: SCREAMING_SNAKE_CASE_: Any =name.replace("""proj""" , """projection""" ) if "blocks" in name: SCREAMING_SNAKE_CASE_: Optional[int] =name.replace("""blocks""" , """layer""" ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE_: Tuple =name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE_: Optional[int] =name.replace("""mlp.fc2""" , """output.dense""" ) if "norm1" in name: SCREAMING_SNAKE_CASE_: Dict =name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: SCREAMING_SNAKE_CASE_: Any =name.replace("""norm2""" , """layernorm_after""" ) if "scratch.output_conv" in name: SCREAMING_SNAKE_CASE_: List[Any] =name.replace("""scratch.output_conv""" , """head""" ) if "scratch" in name: SCREAMING_SNAKE_CASE_: int =name.replace("""scratch""" , """neck""" ) if "layer1_rn" in name: SCREAMING_SNAKE_CASE_: Union[str, Any] =name.replace("""layer1_rn""" , """convs.0""" ) if "layer2_rn" in name: SCREAMING_SNAKE_CASE_: str =name.replace("""layer2_rn""" , """convs.1""" ) if "layer3_rn" in name: SCREAMING_SNAKE_CASE_: Dict =name.replace("""layer3_rn""" , """convs.2""" ) if "layer4_rn" in name: SCREAMING_SNAKE_CASE_: Any =name.replace("""layer4_rn""" , """convs.3""" ) if "refinenet" in name: SCREAMING_SNAKE_CASE_: int =int(name[len("""neck.refinenet""" ) : len("""neck.refinenet""" ) + 1] ) # tricky here: we need to map 4 to 0, 3 to 1, 2 to 2 and 1 to 3 SCREAMING_SNAKE_CASE_: Union[str, Any] =name.replace(f'''refinenet{layer_idx}''' , f'''fusion_stage.layers.{abs(layer_idx-4 )}''' ) if "out_conv" in name: SCREAMING_SNAKE_CASE_: int =name.replace("""out_conv""" , """projection""" ) if "resConfUnit1" in name: SCREAMING_SNAKE_CASE_: Optional[Any] =name.replace("""resConfUnit1""" , """residual_layer1""" ) if "resConfUnit2" in name: SCREAMING_SNAKE_CASE_: Optional[int] =name.replace("""resConfUnit2""" , """residual_layer2""" ) if "conv1" in name: SCREAMING_SNAKE_CASE_: Dict =name.replace("""conv1""" , """convolution1""" ) if "conv2" in name: SCREAMING_SNAKE_CASE_: Union[str, Any] =name.replace("""conv2""" , """convolution2""" ) # readout blocks if "pretrained.act_postprocess1.0.project.0" in name: SCREAMING_SNAKE_CASE_: Dict =name.replace("""pretrained.act_postprocess1.0.project.0""" , """neck.reassemble_stage.readout_projects.0.0""" ) if "pretrained.act_postprocess2.0.project.0" in name: SCREAMING_SNAKE_CASE_: List[str] =name.replace("""pretrained.act_postprocess2.0.project.0""" , """neck.reassemble_stage.readout_projects.1.0""" ) if "pretrained.act_postprocess3.0.project.0" in name: SCREAMING_SNAKE_CASE_: List[str] =name.replace("""pretrained.act_postprocess3.0.project.0""" , """neck.reassemble_stage.readout_projects.2.0""" ) if "pretrained.act_postprocess4.0.project.0" in name: SCREAMING_SNAKE_CASE_: Optional[Any] =name.replace("""pretrained.act_postprocess4.0.project.0""" , """neck.reassemble_stage.readout_projects.3.0""" ) # resize blocks if "pretrained.act_postprocess1.3" in name: SCREAMING_SNAKE_CASE_: List[str] =name.replace("""pretrained.act_postprocess1.3""" , """neck.reassemble_stage.layers.0.projection""" ) if "pretrained.act_postprocess1.4" in name: SCREAMING_SNAKE_CASE_: str =name.replace("""pretrained.act_postprocess1.4""" , """neck.reassemble_stage.layers.0.resize""" ) if "pretrained.act_postprocess2.3" in name: SCREAMING_SNAKE_CASE_: List[Any] =name.replace("""pretrained.act_postprocess2.3""" , """neck.reassemble_stage.layers.1.projection""" ) if "pretrained.act_postprocess2.4" in name: SCREAMING_SNAKE_CASE_: List[Any] =name.replace("""pretrained.act_postprocess2.4""" , """neck.reassemble_stage.layers.1.resize""" ) if "pretrained.act_postprocess3.3" in name: SCREAMING_SNAKE_CASE_: List[Any] =name.replace("""pretrained.act_postprocess3.3""" , """neck.reassemble_stage.layers.2.projection""" ) if "pretrained.act_postprocess4.3" in name: SCREAMING_SNAKE_CASE_: Union[str, Any] =name.replace("""pretrained.act_postprocess4.3""" , """neck.reassemble_stage.layers.3.projection""" ) if "pretrained.act_postprocess4.4" in name: SCREAMING_SNAKE_CASE_: Any =name.replace("""pretrained.act_postprocess4.4""" , """neck.reassemble_stage.layers.3.resize""" ) if "pretrained" in name: SCREAMING_SNAKE_CASE_: int =name.replace("""pretrained""" , """dpt""" ) if "bn" in name: SCREAMING_SNAKE_CASE_: Dict =name.replace("""bn""" , """batch_norm""" ) if "head" in name: SCREAMING_SNAKE_CASE_: Optional[int] =name.replace("""head""" , """head.head""" ) if "encoder.norm" in name: SCREAMING_SNAKE_CASE_: List[str] =name.replace("""encoder.norm""" , """layernorm""" ) if "auxlayer" in name: SCREAMING_SNAKE_CASE_: Dict =name.replace("""auxlayer""" , """auxiliary_head.head""" ) return name def __magic_name__ ( lowercase , lowercase ): for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE_: Any =state_dict.pop(f'''dpt.encoder.layer.{i}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE_: int =state_dict.pop(f'''dpt.encoder.layer.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE_: Optional[int] =in_proj_weight[: config.hidden_size, :] SCREAMING_SNAKE_CASE_: Optional[Any] =in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE_: Union[str, Any] =in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE_: List[str] =in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE_: Any =in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE_: Tuple =in_proj_bias[-config.hidden_size :] def __magic_name__ ( ): SCREAMING_SNAKE_CASE_: str ="""http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE_: Optional[int] =Image.open(requests.get(lowercase , stream=lowercase ).raw ) return im @torch.no_grad() def __magic_name__ ( lowercase , lowercase , lowercase , lowercase ): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Any =get_dpt_config(lowercase ) # load original state_dict from URL SCREAMING_SNAKE_CASE_: Dict =torch.hub.load_state_dict_from_url(lowercase , map_location="""cpu""" ) # remove certain keys remove_ignore_keys_(lowercase ) # rename keys for key in state_dict.copy().keys(): SCREAMING_SNAKE_CASE_: Optional[int] =state_dict.pop(lowercase ) SCREAMING_SNAKE_CASE_: Any =val # read in qkv matrices read_in_q_k_v(lowercase , lowercase ) # load HuggingFace model SCREAMING_SNAKE_CASE_: List[Any] =DPTForSemanticSegmentation(lowercase ) if """ade""" in checkpoint_url else DPTForDepthEstimation(lowercase ) model.load_state_dict(lowercase ) model.eval() # Check outputs on an image SCREAMING_SNAKE_CASE_: Dict =480 if """ade""" in checkpoint_url else 384 SCREAMING_SNAKE_CASE_: List[str] =DPTImageProcessor(size=lowercase ) SCREAMING_SNAKE_CASE_: int =prepare_img() SCREAMING_SNAKE_CASE_: Union[str, Any] =image_processor(lowercase , return_tensors="""pt""" ) # forward pass SCREAMING_SNAKE_CASE_: List[str] =model(**lowercase ).logits if """ade""" in checkpoint_url else model(**lowercase ).predicted_depth # Assert logits SCREAMING_SNAKE_CASE_: Optional[Any] =torch.tensor([[6.3_199, 6.3_629, 6.4_148], [6.3_850, 6.3_615, 6.4_166], [6.3_519, 6.3_176, 6.3_575]] ) if "ade" in checkpoint_url: SCREAMING_SNAKE_CASE_: int =torch.tensor([[4.0_480, 4.2_420, 4.4_360], [4.3_124, 4.5_693, 4.8_261], [4.5_768, 4.8_965, 5.2_163]] ) assert outputs.shape == torch.Size(lowercase ) assert ( torch.allclose(outputs[0, 0, :3, :3] , lowercase , atol=1e-4 ) if "ade" in checkpoint_url else torch.allclose(outputs[0, :3, :3] , lowercase ) ) Path(lowercase ).mkdir(exist_ok=lowercase ) print(f'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowercase ) if push_to_hub: print("""Pushing model to hub...""" ) model.push_to_hub( repo_path_or_name=Path(lowercase , lowercase ) , organization="""nielsr""" , commit_message="""Add model""" , use_temp_dir=lowercase , ) image_processor.push_to_hub( repo_path_or_name=Path(lowercase , lowercase ) , organization="""nielsr""" , commit_message="""Add image processor""" , use_temp_dir=lowercase , ) if __name__ == "__main__": _UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--checkpoint_url""", default="""https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt""", type=str, help="""URL of the original DPT checkpoint you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model directory.""", ) parser.add_argument( """--push_to_hub""", action="""store_true""", ) parser.add_argument( """--model_name""", default="""dpt-large""", type=str, help="""Name of the model, in case you're pushing to the hub.""", ) _UpperCAmelCase = parser.parse_args() convert_dpt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name)
36
"""simple docstring""" def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: int =False while is_sorted is False: # Until all the indices are traversed keep looping SCREAMING_SNAKE_CASE_: Tuple =True for i in range(0 , len(lowercase ) - 1 , 2 ): # iterating over all even indices if input_list[i] > input_list[i + 1]: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[int] =input_list[i + 1], input_list[i] # swapping if elements not in order SCREAMING_SNAKE_CASE_: Tuple =False for i in range(1 , len(lowercase ) - 1 , 2 ): # iterating over all odd indices if input_list[i] > input_list[i + 1]: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: str =input_list[i + 1], input_list[i] # swapping if elements not in order SCREAMING_SNAKE_CASE_: str =False return input_list if __name__ == "__main__": print("""Enter list to be sorted""") _UpperCAmelCase = [int(x) for x in input().split()] # inputing elements of the list in one line _UpperCAmelCase = odd_even_sort(input_list) print("""The sorted list is""") print(sorted_list)
36
1
"""simple docstring""" from typing import Dict, List, Optional from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { """nielsr/canine-s""": 2_0_4_8, } # Unicode defines 1,114,112 total “codepoints” _UpperCAmelCase = 1_1_1_4_1_1_2 # Below: Constants defining canonical codepoints for special, pseudo-characters. # Copied from https://github.com/google-research/language/blob/master/language/canine/special_codepoints.py _UpperCAmelCase = 0 _UpperCAmelCase = 0xE_000 _UpperCAmelCase = 0xE_001 _UpperCAmelCase = 0xE_002 _UpperCAmelCase = 0xE_003 _UpperCAmelCase = 0xE_004 # Maps special codepoints to human-readable names. _UpperCAmelCase = { # Special symbols are represented using codepoints values that are valid, # but designated as "Private Use", meaning that they will never be assigned # characters by the Unicode Consortium, and are thus safe for use here. # # NOTE: Do *NOT* add any sort of [UNK_CHAR] here. They are explicitly # excluded and should fail with a hard error. CLS: "[CLS]", SEP: "[SEP]", BOS: "[BOS]", MASK: "[MASK]", PAD: "[PAD]", RESERVED: "[RESERVED]", } # Maps special codepoint human-readable names to their codepoint values. _UpperCAmelCase = {name: codepoint for codepoint, name in SPECIAL_CODEPOINTS.items()} class a ( UpperCAmelCase__ ): UpperCamelCase : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : Union[str, Any] , lowerCAmelCase : Any=chr(lowerCAmelCase ) , lowerCAmelCase : List[str]=chr(lowerCAmelCase ) , lowerCAmelCase : List[str]=chr(lowerCAmelCase ) , lowerCAmelCase : Dict=chr(lowerCAmelCase ) , lowerCAmelCase : Tuple=chr(lowerCAmelCase ) , lowerCAmelCase : Any=chr(lowerCAmelCase ) , lowerCAmelCase : Optional[Any]=False , lowerCAmelCase : Any=2048 , **lowerCAmelCase : Any , ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =AddedToken(lowerCAmelCase , lstrip=lowerCAmelCase , rstrip=lowerCAmelCase ) if isinstance(lowerCAmelCase , lowerCAmelCase ) else bos_token SCREAMING_SNAKE_CASE_: str =AddedToken(lowerCAmelCase , lstrip=lowerCAmelCase , rstrip=lowerCAmelCase ) if isinstance(lowerCAmelCase , lowerCAmelCase ) else eos_token SCREAMING_SNAKE_CASE_: Tuple =AddedToken(lowerCAmelCase , lstrip=lowerCAmelCase , rstrip=lowerCAmelCase ) if isinstance(lowerCAmelCase , lowerCAmelCase ) else sep_token SCREAMING_SNAKE_CASE_: List[Any] =AddedToken(lowerCAmelCase , lstrip=lowerCAmelCase , rstrip=lowerCAmelCase ) if isinstance(lowerCAmelCase , lowerCAmelCase ) else cls_token SCREAMING_SNAKE_CASE_: List[str] =AddedToken(lowerCAmelCase , lstrip=lowerCAmelCase , rstrip=lowerCAmelCase ) if isinstance(lowerCAmelCase , lowerCAmelCase ) else pad_token # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE_: Dict =AddedToken(lowerCAmelCase , lstrip=lowerCAmelCase , rstrip=lowerCAmelCase ) if isinstance(lowerCAmelCase , lowerCAmelCase ) else mask_token super().__init__( bos_token=lowerCAmelCase , eos_token=lowerCAmelCase , sep_token=lowerCAmelCase , cls_token=lowerCAmelCase , pad_token=lowerCAmelCase , mask_token=lowerCAmelCase , add_prefix_space=lowerCAmelCase , model_max_length=lowerCAmelCase , **lowerCAmelCase , ) # Creates a mapping for looking up the IDs of special symbols. SCREAMING_SNAKE_CASE_: Dict[str, int] ={} for codepoint, name in SPECIAL_CODEPOINTS.items(): SCREAMING_SNAKE_CASE_: Any =codepoint # Creates a mapping for looking up the string forms of special symbol IDs. SCREAMING_SNAKE_CASE_: Dict[int, str] ={ codepoint: name for name, codepoint in self._special_codepoints.items() } SCREAMING_SNAKE_CASE_: Dict =UNICODE_VOCAB_SIZE SCREAMING_SNAKE_CASE_: str =len(self._special_codepoints ) @property def lowerCamelCase__ ( self : List[str] ) -> int: '''simple docstring''' return self._unicode_vocab_size def lowerCamelCase__ ( self : Dict , lowerCAmelCase : str ) -> List[str]: '''simple docstring''' return list(lowerCAmelCase ) def lowerCamelCase__ ( self : Tuple , lowerCAmelCase : str ) -> int: '''simple docstring''' try: return ord(lowerCAmelCase ) except TypeError: raise ValueError(f'''invalid token: \'{token}\'''' ) def lowerCamelCase__ ( self : List[Any] , lowerCAmelCase : int ) -> str: '''simple docstring''' try: if index in SPECIAL_CODEPOINTS: return SPECIAL_CODEPOINTS[index] return chr(lowerCAmelCase ) except TypeError: raise ValueError(f'''invalid id: {index}''' ) def lowerCamelCase__ ( self : List[str] , lowerCAmelCase : Optional[int] ) -> Optional[int]: '''simple docstring''' return "".join(lowerCAmelCase ) def lowerCamelCase__ ( self : Dict , lowerCAmelCase : List[int] , lowerCAmelCase : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Union[str, Any] =[self.sep_token_id] SCREAMING_SNAKE_CASE_: Optional[int] =[self.cls_token_id] SCREAMING_SNAKE_CASE_: Dict =cls + token_ids_a + sep if token_ids_a is not None: result += token_ids_a + sep return result def lowerCamelCase__ ( self : Any , lowerCAmelCase : List[int] , lowerCAmelCase : Optional[List[int]] = None , lowerCAmelCase : bool = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowerCAmelCase , token_ids_a=lowerCAmelCase , already_has_special_tokens=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: int =[1] + ([0] * len(lowerCAmelCase )) + [1] if token_ids_a is not None: result += ([0] * len(lowerCAmelCase )) + [1] return result def lowerCamelCase__ ( self : Dict , lowerCAmelCase : List[int] , lowerCAmelCase : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[int] =[self.sep_token_id] SCREAMING_SNAKE_CASE_: List[str] =[self.cls_token_id] SCREAMING_SNAKE_CASE_: Dict =len(cls + token_ids_a + sep ) * [0] if token_ids_a is not None: result += len(token_ids_a + sep ) * [1] return result def lowerCamelCase__ ( self : Tuple , lowerCAmelCase : str , lowerCAmelCase : Optional[str] = None ) -> List[str]: '''simple docstring''' return ()
36
"""simple docstring""" def __magic_name__ ( lowercase ): return str(lowercase ) == str(lowercase )[::-1] def __magic_name__ ( lowercase ): return int(lowercase ) + int(str(lowercase )[::-1] ) def __magic_name__ ( lowercase = 1_0000 ): SCREAMING_SNAKE_CASE_: List[str] =[] for num in range(1 , lowercase ): SCREAMING_SNAKE_CASE_: List[Any] =0 SCREAMING_SNAKE_CASE_: int =num while iterations < 50: SCREAMING_SNAKE_CASE_: Optional[Any] =sum_reverse(lowercase ) iterations += 1 if is_palindrome(lowercase ): break else: lychrel_nums.append(lowercase ) return len(lowercase ) if __name__ == "__main__": print(f"""{solution() = }""")
36
1
"""simple docstring""" def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: List[str] =0 # if input_string is "aba" than new_input_string become "a|b|a" SCREAMING_SNAKE_CASE_: Optional[Any] ="""""" SCREAMING_SNAKE_CASE_: Optional[Any] ="""""" # append each character + "|" in new_string for range(0, length-1) for i in input_string[: len(lowercase ) - 1]: new_input_string += i + "|" # append last character new_input_string += input_string[-1] # we will store the starting and ending of previous furthest ending palindromic # substring SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[Any] =0, 0 # length[i] shows the length of palindromic substring with center i SCREAMING_SNAKE_CASE_: Optional[Any] =[1 for i in range(len(lowercase ) )] # for each character in new_string find corresponding palindromic string SCREAMING_SNAKE_CASE_: Optional[int] =0 for j in range(len(lowercase ) ): SCREAMING_SNAKE_CASE_: Union[str, Any] =1 if j > r else min(length[l + r - j] // 2 , r - j + 1 ) while ( j - k >= 0 and j + k < len(lowercase ) and new_input_string[k + j] == new_input_string[j - k] ): k += 1 SCREAMING_SNAKE_CASE_: Dict =2 * k - 1 # does this string is ending after the previously explored end (that is r) ? # if yes the update the new r to the last index of this if j + k - 1 > r: SCREAMING_SNAKE_CASE_: Optional[int] =j - k + 1 # noqa: E741 SCREAMING_SNAKE_CASE_: List[str] =j + k - 1 # update max_length and start position if max_length < length[j]: SCREAMING_SNAKE_CASE_: int =length[j] SCREAMING_SNAKE_CASE_: Optional[int] =j # create that string SCREAMING_SNAKE_CASE_: Dict =new_input_string[start - max_length // 2 : start + max_length // 2 + 1] for i in s: if i != "|": output_string += i return output_string if __name__ == "__main__": import doctest doctest.testmod()
36
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available from ...utils import OptionalDependencyNotAvailable _UpperCAmelCase = {"""configuration_dpt""": ["""DPT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """DPTConfig"""]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = ["""DPTFeatureExtractor"""] _UpperCAmelCase = ["""DPTImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ """DPT_PRETRAINED_MODEL_ARCHIVE_LIST""", """DPTForDepthEstimation""", """DPTForSemanticSegmentation""", """DPTModel""", """DPTPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_dpt import DPTFeatureExtractor from .image_processing_dpt import DPTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dpt import ( DPT_PRETRAINED_MODEL_ARCHIVE_LIST, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel, DPTPreTrainedModel, ) else: import sys _UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
36
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { """google/mobilenet_v1_1.0_224""": """https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json""", """google/mobilenet_v1_0.75_192""": """https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json""", # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 } class a ( UpperCAmelCase__ ): UpperCamelCase : Optional[Any] = 'mobilenet_v1' def __init__( self : int , lowerCAmelCase : List[str]=3 , lowerCAmelCase : Dict=224 , lowerCAmelCase : Tuple=1.0 , lowerCAmelCase : int=8 , lowerCAmelCase : Any="relu6" , lowerCAmelCase : Any=True , lowerCAmelCase : List[str]=0.9_9_9 , lowerCAmelCase : Union[str, Any]=0.0_2 , lowerCAmelCase : Tuple=0.0_0_1 , **lowerCAmelCase : List[Any] , ) -> Union[str, Any]: '''simple docstring''' super().__init__(**lowerCAmelCase ) if depth_multiplier <= 0: raise ValueError("""depth_multiplier must be greater than zero.""" ) SCREAMING_SNAKE_CASE_: List[str] =num_channels SCREAMING_SNAKE_CASE_: List[Any] =image_size SCREAMING_SNAKE_CASE_: List[str] =depth_multiplier SCREAMING_SNAKE_CASE_: Union[str, Any] =min_depth SCREAMING_SNAKE_CASE_: Tuple =hidden_act SCREAMING_SNAKE_CASE_: List[str] =tf_padding SCREAMING_SNAKE_CASE_: int =classifier_dropout_prob SCREAMING_SNAKE_CASE_: Any =initializer_range SCREAMING_SNAKE_CASE_: Dict =layer_norm_eps class a ( UpperCAmelCase__ ): UpperCamelCase : int = version.parse('1.11' ) @property def lowerCamelCase__ ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict([("""pixel_values""", {0: """batch"""})] ) @property def lowerCamelCase__ ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "image-classification": return OrderedDict([("""logits""", {0: """batch"""})] ) else: return OrderedDict([("""last_hidden_state""", {0: """batch"""}), ("""pooler_output""", {0: """batch"""})] ) @property def lowerCamelCase__ ( self : Tuple ) -> float: '''simple docstring''' return 1E-4
36
"""simple docstring""" from __future__ import annotations import math import random from typing import Any class a : def __init__( self : str ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: list[Any] =[] SCREAMING_SNAKE_CASE_: int =0 SCREAMING_SNAKE_CASE_: int =0 def lowerCamelCase__ ( self : Optional[Any] ) -> bool: '''simple docstring''' return self.head == self.tail def lowerCamelCase__ ( self : Tuple , lowerCAmelCase : Any ) -> None: '''simple docstring''' self.data.append(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =self.tail + 1 def lowerCamelCase__ ( self : int ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: int =self.data[self.head] SCREAMING_SNAKE_CASE_: Optional[int] =self.head + 1 return ret def lowerCamelCase__ ( self : Optional[Any] ) -> int: '''simple docstring''' return self.tail - self.head def lowerCamelCase__ ( self : str ) -> None: '''simple docstring''' print(self.data ) print("""**************""" ) print(self.data[self.head : self.tail] ) class a : def __init__( self : Union[str, Any] , lowerCAmelCase : Any ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =data SCREAMING_SNAKE_CASE_: MyNode | None =None SCREAMING_SNAKE_CASE_: MyNode | None =None SCREAMING_SNAKE_CASE_: int =1 def lowerCamelCase__ ( self : Optional[Any] ) -> Any: '''simple docstring''' return self.data def lowerCamelCase__ ( self : List[Any] ) -> MyNode | None: '''simple docstring''' return self.left def lowerCamelCase__ ( self : Dict ) -> MyNode | None: '''simple docstring''' return self.right def lowerCamelCase__ ( self : Any ) -> int: '''simple docstring''' return self.height def lowerCamelCase__ ( self : Any , lowerCAmelCase : Any ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[Any] =data def lowerCamelCase__ ( self : Dict , lowerCAmelCase : MyNode | None ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =node def lowerCamelCase__ ( self : List[Any] , lowerCAmelCase : MyNode | None ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: str =node def lowerCamelCase__ ( self : int , lowerCAmelCase : int ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =height def __magic_name__ ( lowercase ): if node is None: return 0 return node.get_height() def __magic_name__ ( lowercase , lowercase ): if a > b: return a return b def __magic_name__ ( lowercase ): print("""left rotation node:""" , node.get_data() ) SCREAMING_SNAKE_CASE_: List[Any] =node.get_left() assert ret is not None node.set_left(ret.get_right() ) ret.set_right(lowercase ) SCREAMING_SNAKE_CASE_: Tuple =my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowercase ) SCREAMING_SNAKE_CASE_: int =my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(lowercase ) return ret def __magic_name__ ( lowercase ): print("""right rotation node:""" , node.get_data() ) SCREAMING_SNAKE_CASE_: List[Any] =node.get_right() assert ret is not None node.set_right(ret.get_left() ) ret.set_left(lowercase ) SCREAMING_SNAKE_CASE_: List[Any] =my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowercase ) SCREAMING_SNAKE_CASE_: Optional[int] =my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(lowercase ) return ret def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Any =node.get_left() assert left_child is not None node.set_left(left_rotation(lowercase ) ) return right_rotation(lowercase ) def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Dict =node.get_right() assert right_child is not None node.set_right(right_rotation(lowercase ) ) return left_rotation(lowercase ) def __magic_name__ ( lowercase , lowercase ): if node is None: return MyNode(lowercase ) if data < node.get_data(): node.set_left(insert_node(node.get_left() , lowercase ) ) if ( get_height(node.get_left() ) - get_height(node.get_right() ) == 2 ): # an unbalance detected SCREAMING_SNAKE_CASE_: Union[str, Any] =node.get_left() assert left_child is not None if ( data < left_child.get_data() ): # new node is the left child of the left child SCREAMING_SNAKE_CASE_: Any =right_rotation(lowercase ) else: SCREAMING_SNAKE_CASE_: List[Any] =lr_rotation(lowercase ) else: node.set_right(insert_node(node.get_right() , lowercase ) ) if get_height(node.get_right() ) - get_height(node.get_left() ) == 2: SCREAMING_SNAKE_CASE_: Tuple =node.get_right() assert right_child is not None if data < right_child.get_data(): SCREAMING_SNAKE_CASE_: Optional[Any] =rl_rotation(lowercase ) else: SCREAMING_SNAKE_CASE_: Optional[int] =left_rotation(lowercase ) SCREAMING_SNAKE_CASE_: Tuple =my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowercase ) return node def __magic_name__ ( lowercase ): while True: SCREAMING_SNAKE_CASE_: Dict =root.get_right() if right_child is None: break SCREAMING_SNAKE_CASE_: str =right_child return root.get_data() def __magic_name__ ( lowercase ): while True: SCREAMING_SNAKE_CASE_: str =root.get_left() if left_child is None: break SCREAMING_SNAKE_CASE_: Dict =left_child return root.get_data() def __magic_name__ ( lowercase , lowercase ): SCREAMING_SNAKE_CASE_: str =root.get_left() SCREAMING_SNAKE_CASE_: List[Any] =root.get_right() if root.get_data() == data: if left_child is not None and right_child is not None: SCREAMING_SNAKE_CASE_: Union[str, Any] =get_left_most(lowercase ) root.set_data(lowercase ) root.set_right(del_node(lowercase , lowercase ) ) elif left_child is not None: SCREAMING_SNAKE_CASE_: Optional[int] =left_child elif right_child is not None: SCREAMING_SNAKE_CASE_: Any =right_child else: return None elif root.get_data() > data: if left_child is None: print("""No such data""" ) return root else: root.set_left(del_node(lowercase , lowercase ) ) else: # root.get_data() < data if right_child is None: return root else: root.set_right(del_node(lowercase , lowercase ) ) if get_height(lowercase ) - get_height(lowercase ) == 2: assert right_child is not None if get_height(right_child.get_right() ) > get_height(right_child.get_left() ): SCREAMING_SNAKE_CASE_: Tuple =left_rotation(lowercase ) else: SCREAMING_SNAKE_CASE_: Optional[Any] =rl_rotation(lowercase ) elif get_height(lowercase ) - get_height(lowercase ) == -2: assert left_child is not None if get_height(left_child.get_left() ) > get_height(left_child.get_right() ): SCREAMING_SNAKE_CASE_: Optional[Any] =right_rotation(lowercase ) else: SCREAMING_SNAKE_CASE_: str =lr_rotation(lowercase ) SCREAMING_SNAKE_CASE_: str =my_max(get_height(root.get_right() ) , get_height(root.get_left() ) ) + 1 root.set_height(lowercase ) return root class a : def __init__( self : int ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: MyNode | None =None def lowerCamelCase__ ( self : List[Any] ) -> int: '''simple docstring''' return get_height(self.root ) def lowerCamelCase__ ( self : Optional[int] , lowerCAmelCase : Any ) -> None: '''simple docstring''' print("""insert:""" + str(lowerCAmelCase ) ) SCREAMING_SNAKE_CASE_: Tuple =insert_node(self.root , lowerCAmelCase ) def lowerCamelCase__ ( self : List[Any] , lowerCAmelCase : Any ) -> None: '''simple docstring''' print("""delete:""" + str(lowerCAmelCase ) ) if self.root is None: print("""Tree is empty!""" ) return SCREAMING_SNAKE_CASE_: Union[str, Any] =del_node(self.root , lowerCAmelCase ) def __str__( self : List[str] , ) -> str: # a level traversale, gives a more intuitive look on the tree '''simple docstring''' SCREAMING_SNAKE_CASE_: List[Any] ="""""" SCREAMING_SNAKE_CASE_: str =MyQueue() q.push(self.root ) SCREAMING_SNAKE_CASE_: List[str] =self.get_height() if layer == 0: return output SCREAMING_SNAKE_CASE_: int =0 while not q.is_empty(): SCREAMING_SNAKE_CASE_: int =q.pop() SCREAMING_SNAKE_CASE_: List[Any] =""" """ * int(math.pow(2 , layer - 1 ) ) output += space if node is None: output += "*" q.push(lowerCAmelCase ) q.push(lowerCAmelCase ) else: output += str(node.get_data() ) q.push(node.get_left() ) q.push(node.get_right() ) output += space SCREAMING_SNAKE_CASE_: List[Any] =cnt + 1 for i in range(100 ): if cnt == math.pow(2 , lowerCAmelCase ) - 1: SCREAMING_SNAKE_CASE_: int =layer - 1 if layer == 0: output += "\n*************************************" return output output += "\n" break output += "\n*************************************" return output def __magic_name__ ( ): import doctest doctest.testmod() if __name__ == "__main__": _test() _UpperCAmelCase = AVLtree() _UpperCAmelCase = list(range(1_0)) random.shuffle(lst) for i in lst: t.insert(i) print(str(t)) random.shuffle(lst) for i in lst: t.del_node(i) print(str(t))
36
1
"""simple docstring""" import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler _UpperCAmelCase = 1_6 _UpperCAmelCase = 3_2 def __magic_name__ ( lowercase , lowercase = 16 , lowercase = "bert-base-cased" ): SCREAMING_SNAKE_CASE_: Union[str, Any] =AutoTokenizer.from_pretrained(lowercase ) SCREAMING_SNAKE_CASE_: Any =load_dataset("""glue""" , """mrpc""" ) def tokenize_function(lowercase ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE_: Tuple =tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=lowercase , max_length=lowercase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset SCREAMING_SNAKE_CASE_: List[str] =datasets.map( lowercase , batched=lowercase , remove_columns=["""idx""", """sentence1""", """sentence2"""] , load_from_cache_file=lowercase ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE_: Dict =tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(lowercase ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(lowercase , padding="""max_length""" , max_length=128 , return_tensors="""pt""" ) return tokenizer.pad(lowercase , padding="""longest""" , return_tensors="""pt""" ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE_: Dict =DataLoader( tokenized_datasets["""train"""] , shuffle=lowercase , collate_fn=lowercase , batch_size=lowercase ) SCREAMING_SNAKE_CASE_: Tuple =DataLoader( tokenized_datasets["""validation"""] , shuffle=lowercase , collate_fn=lowercase , batch_size=lowercase ) return train_dataloader, eval_dataloader def __magic_name__ ( lowercase , lowercase , lowercase , lowercase ): model.eval() SCREAMING_SNAKE_CASE_: str =0 for step, batch in enumerate(lowercase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE_: int =model(**lowercase ) SCREAMING_SNAKE_CASE_: List[Any] =outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: int =accelerator.gather( (predictions, batch["""labels"""]) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(lowercase ) - 1: SCREAMING_SNAKE_CASE_: Optional[int] =predictions[: len(eval_dataloader.dataset ) - samples_seen] SCREAMING_SNAKE_CASE_: str =references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=lowercase , references=lowercase , ) SCREAMING_SNAKE_CASE_: str =metric.compute() return eval_metric["accuracy"] def __magic_name__ ( lowercase , lowercase ): # Initialize accelerator SCREAMING_SNAKE_CASE_: Union[str, Any] =Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE_: Optional[int] =config["""lr"""] SCREAMING_SNAKE_CASE_: Tuple =int(config["""num_epochs"""] ) SCREAMING_SNAKE_CASE_: Any =int(config["""seed"""] ) SCREAMING_SNAKE_CASE_: Tuple =int(config["""batch_size"""] ) SCREAMING_SNAKE_CASE_: int =args.model_name_or_path set_seed(lowercase ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[int] =get_dataloaders(lowercase , lowercase , lowercase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE_: List[Any] =AutoModelForSequenceClassification.from_pretrained(lowercase , return_dict=lowercase ) # Instantiate optimizer SCREAMING_SNAKE_CASE_: Dict =( AdamW if accelerator.state.deepspeed_plugin is None or """optimizer""" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) SCREAMING_SNAKE_CASE_: Tuple =optimizer_cls(params=model.parameters() , lr=lowercase ) if accelerator.state.deepspeed_plugin is not None: SCREAMING_SNAKE_CASE_: Dict =accelerator.state.deepspeed_plugin.deepspeed_config[ """gradient_accumulation_steps""" ] else: SCREAMING_SNAKE_CASE_: Optional[Any] =1 SCREAMING_SNAKE_CASE_: str =(len(lowercase ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): SCREAMING_SNAKE_CASE_: Any =get_linear_schedule_with_warmup( optimizer=lowercase , num_warmup_steps=0 , num_training_steps=lowercase , ) else: SCREAMING_SNAKE_CASE_: Any =DummyScheduler(lowercase , total_num_steps=lowercase , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: str =accelerator.prepare( lowercase , lowercase , lowercase , lowercase , lowercase ) # We need to keep track of how many total steps we have iterated over SCREAMING_SNAKE_CASE_: str =0 # We also need to keep track of the stating epoch so files are named properly SCREAMING_SNAKE_CASE_: int =0 SCREAMING_SNAKE_CASE_: int =evaluate.load("""glue""" , """mrpc""" ) SCREAMING_SNAKE_CASE_: List[Any] =num_epochs if args.partial_train_epoch is not None: SCREAMING_SNAKE_CASE_: int =args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) SCREAMING_SNAKE_CASE_: int =args.resume_from_checkpoint.split("""epoch_""" )[1] SCREAMING_SNAKE_CASE_: Optional[int] ="""""" for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break SCREAMING_SNAKE_CASE_: int =int(lowercase ) + 1 SCREAMING_SNAKE_CASE_: Dict =evaluation_loop(lowercase , lowercase , lowercase , lowercase ) accelerator.print("""resumed checkpoint performance:""" , lowercase ) accelerator.print("""resumed checkpoint's scheduler's lr:""" , lr_scheduler.get_lr()[0] ) accelerator.print("""resumed optimizers's lr:""" , optimizer.param_groups[0]["""lr"""] ) with open(os.path.join(args.output_dir , f'''state_{starting_epoch-1}.json''' ) , """r""" ) as f: SCREAMING_SNAKE_CASE_: List[Any] =json.load(lowercase ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model SCREAMING_SNAKE_CASE_: Dict ={} for epoch in range(lowercase , lowercase ): model.train() for step, batch in enumerate(lowercase ): SCREAMING_SNAKE_CASE_: Union[str, Any] =model(**lowercase ) SCREAMING_SNAKE_CASE_: str =outputs.loss SCREAMING_SNAKE_CASE_: List[str] =loss / gradient_accumulation_steps accelerator.backward(lowercase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 SCREAMING_SNAKE_CASE_: int =f'''epoch_{epoch}''' SCREAMING_SNAKE_CASE_: Optional[int] =os.path.join(args.output_dir , lowercase ) accelerator.save_state(lowercase ) SCREAMING_SNAKE_CASE_: Optional[int] =evaluation_loop(lowercase , lowercase , lowercase , lowercase ) SCREAMING_SNAKE_CASE_: Optional[Any] =accuracy SCREAMING_SNAKE_CASE_: str =lr_scheduler.get_lr()[0] SCREAMING_SNAKE_CASE_: List[str] =optimizer.param_groups[0]["""lr"""] SCREAMING_SNAKE_CASE_: Union[str, Any] =epoch SCREAMING_SNAKE_CASE_: str =overall_step accelerator.print(f'''epoch {epoch}:''' , lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , f'''state_{epoch}.json''' ) , """w""" ) as f: json.dump(lowercase , lowercase ) def __magic_name__ ( ): SCREAMING_SNAKE_CASE_: Tuple =argparse.ArgumentParser(description="""Simple example of training script tracking peak GPU memory usage.""" ) parser.add_argument( """--model_name_or_path""" , type=lowercase , default="""bert-base-cased""" , help="""Path to pretrained model or model identifier from huggingface.co/models.""" , required=lowercase , ) parser.add_argument( """--output_dir""" , type=lowercase , default=""".""" , help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory.""" , ) parser.add_argument( """--resume_from_checkpoint""" , type=lowercase , default=lowercase , help="""If the training should continue from a checkpoint folder.""" , ) parser.add_argument( """--partial_train_epoch""" , type=lowercase , default=lowercase , help="""If passed, the training will stop after this number of epochs.""" , ) parser.add_argument( """--num_epochs""" , type=lowercase , default=2 , help="""Number of train epochs.""" , ) SCREAMING_SNAKE_CASE_: List[str] =parser.parse_args() SCREAMING_SNAKE_CASE_: List[str] ={"""lr""": 2e-5, """num_epochs""": args.num_epochs, """seed""": 42, """batch_size""": 16} training_function(lowercase , lowercase ) if __name__ == "__main__": main()
36
"""simple docstring""" import string def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: List[Any] ="""""" for i in sequence: SCREAMING_SNAKE_CASE_: List[Any] =ord(lowercase ) if 65 <= extract <= 90: output += chr(155 - extract ) elif 97 <= extract <= 122: output += chr(219 - extract ) else: output += i return output def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Any =string.ascii_letters SCREAMING_SNAKE_CASE_: Tuple =string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1] return "".join( letters_reversed[letters.index(lowercase )] if c in letters else c for c in sequence ) def __magic_name__ ( ): from timeit import timeit print("""Running performance benchmarks...""" ) SCREAMING_SNAKE_CASE_: int ="""from string import printable ; from __main__ import atbash, atbash_slow""" print(f'''> atbash_slow(): {timeit("atbash_slow(printable)" , setup=lowercase )} seconds''' ) print(f'''> atbash(): {timeit("atbash(printable)" , setup=lowercase )} seconds''' ) if __name__ == "__main__": for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"): print(f"""{example} encrypted in atbash: {atbash(example)}""") benchmark()
36
1
"""simple docstring""" from collections import Counter from pathlib import Path from typing import Optional, Tuple import yaml class a ( yaml.SafeLoader ): def lowerCamelCase__ ( self : int , lowerCAmelCase : List[str] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =[self.constructed_objects[key_node] for key_node, _ in node.value] SCREAMING_SNAKE_CASE_: Any =[tuple(lowerCAmelCase ) if isinstance(lowerCAmelCase , lowerCAmelCase ) else key for key in keys] SCREAMING_SNAKE_CASE_: Dict =Counter(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =[key for key in counter if counter[key] > 1] if duplicate_keys: raise TypeError(f'''Got duplicate yaml keys: {duplicate_keys}''' ) def lowerCamelCase__ ( self : Tuple , lowerCAmelCase : str , lowerCAmelCase : Optional[int]=False ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =super().construct_mapping(lowerCAmelCase , deep=lowerCAmelCase ) self._check_no_duplicates_on_constructed_node(lowerCAmelCase ) return mapping def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Dict =list(readme_content.splitlines() ) if full_content and full_content[0] == "---" and "---" in full_content[1:]: SCREAMING_SNAKE_CASE_: Union[str, Any] =full_content[1:].index("""---""" ) + 1 SCREAMING_SNAKE_CASE_: List[str] ="""\n""".join(full_content[1:sep_idx] ) return yamlblock, "\n".join(full_content[sep_idx + 1 :] ) return None, "\n".join(lowercase ) class a ( UpperCAmelCase__ ): # class attributes UpperCamelCase : Tuple = {'train_eval_index'} # train-eval-index in the YAML metadata @classmethod def lowerCamelCase__ ( cls : List[Any] , lowerCAmelCase : Path ) -> "DatasetMetadata": '''simple docstring''' with open(lowerCAmelCase , encoding="""utf-8""" ) as readme_file: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Union[str, Any] =_split_yaml_from_readme(readme_file.read() ) if yaml_string is not None: return cls.from_yaml_string(lowerCAmelCase ) else: return cls() def lowerCamelCase__ ( self : Any , lowerCAmelCase : Path ) -> List[str]: '''simple docstring''' if path.exists(): with open(lowerCAmelCase , encoding="""utf-8""" ) as readme_file: SCREAMING_SNAKE_CASE_: str =readme_file.read() else: SCREAMING_SNAKE_CASE_: str =None SCREAMING_SNAKE_CASE_: Tuple =self._to_readme(lowerCAmelCase ) with open(lowerCAmelCase , """w""" , encoding="""utf-8""" ) as readme_file: readme_file.write(lowerCAmelCase ) def lowerCamelCase__ ( self : Optional[Any] , lowerCAmelCase : Optional[str] = None ) -> str: '''simple docstring''' if readme_content is not None: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[str] =_split_yaml_from_readme(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] ="""---\n""" + self.to_yaml_string() + """---\n""" + content else: SCREAMING_SNAKE_CASE_: List[Any] ="""---\n""" + self.to_yaml_string() + """---\n""" return full_content @classmethod def lowerCamelCase__ ( cls : Optional[int] , lowerCAmelCase : str ) -> "DatasetMetadata": '''simple docstring''' SCREAMING_SNAKE_CASE_: int =yaml.load(lowerCAmelCase , Loader=_NoDuplicateSafeLoader ) or {} # Convert the YAML keys to DatasetMetadata fields SCREAMING_SNAKE_CASE_: List[Any] ={ (key.replace("""-""" , """_""" ) if key.replace("""-""" , """_""" ) in cls._FIELDS_WITH_DASHES else key): value for key, value in metadata_dict.items() } return cls(**lowerCAmelCase ) def lowerCamelCase__ ( self : Dict ) -> str: '''simple docstring''' return yaml.safe_dump( { (key.replace("""_""" , """-""" ) if key in self._FIELDS_WITH_DASHES else key): value for key, value in self.items() } , sort_keys=lowerCAmelCase , allow_unicode=lowerCAmelCase , encoding="""utf-8""" , ).decode("""utf-8""" ) _UpperCAmelCase = { """image-classification""": [], """translation""": [], """image-segmentation""": [], """fill-mask""": [], """automatic-speech-recognition""": [], """token-classification""": [], """sentence-similarity""": [], """audio-classification""": [], """question-answering""": [], """summarization""": [], """zero-shot-classification""": [], """table-to-text""": [], """feature-extraction""": [], """other""": [], """multiple-choice""": [], """text-classification""": [], """text-to-image""": [], """text2text-generation""": [], """zero-shot-image-classification""": [], """tabular-classification""": [], """tabular-regression""": [], """image-to-image""": [], """tabular-to-text""": [], """unconditional-image-generation""": [], """text-retrieval""": [], """text-to-speech""": [], """object-detection""": [], """audio-to-audio""": [], """text-generation""": [], """conversational""": [], """table-question-answering""": [], """visual-question-answering""": [], """image-to-text""": [], """reinforcement-learning""": [], """voice-activity-detection""": [], """time-series-forecasting""": [], """document-question-answering""": [], } if __name__ == "__main__": from argparse import ArgumentParser _UpperCAmelCase = ArgumentParser(usage="""Validate the yaml metadata block of a README.md file.""") ap.add_argument("""readme_filepath""") _UpperCAmelCase = ap.parse_args() _UpperCAmelCase = Path(args.readme_filepath) _UpperCAmelCase = DatasetMetadata.from_readme(readme_filepath) print(dataset_metadata) dataset_metadata.to_readme(readme_filepath)
36
"""simple docstring""" import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class a : def __init__( self : Union[str, Any] , lowerCAmelCase : List[str]=2 , lowerCAmelCase : int=3 , lowerCAmelCase : Optional[Any]=64 , lowerCAmelCase : Union[str, Any]=None ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Union[str, Any] =np.random.default_rng(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =length SCREAMING_SNAKE_CASE_: Union[str, Any] =rng.normal(size=(length,) ).astype(np.floataa ) SCREAMING_SNAKE_CASE_: Tuple =a * self.x + b + rng.normal(scale=0.1 , size=(length,) ).astype(np.floataa ) def __len__( self : List[Any] ) -> str: '''simple docstring''' return self.length def __getitem__( self : Union[str, Any] , lowerCAmelCase : Any ) -> List[str]: '''simple docstring''' return {"x": self.x[i], "y": self.y[i]} class a ( torch.nn.Module ): def __init__( self : Optional[int] , lowerCAmelCase : str=0 , lowerCAmelCase : List[Any]=0 , lowerCAmelCase : Optional[int]=False ) -> Tuple: '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE_: int =torch.nn.Parameter(torch.tensor([2, 3] ).float() ) SCREAMING_SNAKE_CASE_: int =torch.nn.Parameter(torch.tensor([2, 3] ).float() ) SCREAMING_SNAKE_CASE_: Dict =True def lowerCamelCase__ ( self : str , lowerCAmelCase : Tuple=None ) -> int: '''simple docstring''' if self.first_batch: print(f'''Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}''' ) SCREAMING_SNAKE_CASE_: Union[str, Any] =False return x * self.a[0] + self.b[0] class a ( torch.nn.Module ): def __init__( self : Union[str, Any] , lowerCAmelCase : Any=0 , lowerCAmelCase : List[Any]=0 , lowerCAmelCase : List[Any]=False ) -> str: '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE_: List[str] =torch.nn.Parameter(torch.tensor(lowerCAmelCase ).float() ) SCREAMING_SNAKE_CASE_: Optional[int] =torch.nn.Parameter(torch.tensor(lowerCAmelCase ).float() ) SCREAMING_SNAKE_CASE_: List[Any] =True def lowerCamelCase__ ( self : List[str] , lowerCAmelCase : int=None ) -> Any: '''simple docstring''' if self.first_batch: print(f'''Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}''' ) SCREAMING_SNAKE_CASE_: Optional[int] =False return x * self.a + self.b def __magic_name__ ( lowercase , lowercase = 16 ): from datasets import load_dataset from transformers import AutoTokenizer SCREAMING_SNAKE_CASE_: Optional[Any] =AutoTokenizer.from_pretrained("""bert-base-cased""" ) SCREAMING_SNAKE_CASE_: Optional[int] ={"""train""": """tests/test_samples/MRPC/train.csv""", """validation""": """tests/test_samples/MRPC/dev.csv"""} SCREAMING_SNAKE_CASE_: Any =load_dataset("""csv""" , data_files=lowercase ) SCREAMING_SNAKE_CASE_: Any =datasets["""train"""].unique("""label""" ) SCREAMING_SNAKE_CASE_: List[Any] ={v: i for i, v in enumerate(lowercase )} def tokenize_function(lowercase ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE_: Dict =tokenizer( examples["""sentence1"""] , examples["""sentence2"""] , truncation=lowercase , max_length=lowercase , padding="""max_length""" ) if "label" in examples: SCREAMING_SNAKE_CASE_: Optional[int] =[label_to_id[l] for l in examples["""label"""]] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset SCREAMING_SNAKE_CASE_: List[Any] =datasets.map( lowercase , batched=lowercase , remove_columns=["""sentence1""", """sentence2""", """label"""] , ) def collate_fn(lowercase ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(lowercase , padding="""max_length""" , max_length=128 , return_tensors="""pt""" ) return tokenizer.pad(lowercase , padding="""longest""" , return_tensors="""pt""" ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE_: Optional[int] =DataLoader(tokenized_datasets["""train"""] , shuffle=lowercase , collate_fn=lowercase , batch_size=2 ) SCREAMING_SNAKE_CASE_: Dict =DataLoader(tokenized_datasets["""validation"""] , shuffle=lowercase , collate_fn=lowercase , batch_size=1 ) return train_dataloader, eval_dataloader
36
1
"""simple docstring""" from __future__ import annotations def __magic_name__ ( lowercase , lowercase = None ): SCREAMING_SNAKE_CASE_: Optional[int] =word_bank or [] # create a table SCREAMING_SNAKE_CASE_: int =len(lowercase ) + 1 SCREAMING_SNAKE_CASE_: list[list[list[str]]] =[] for _ in range(lowercase ): table.append([] ) # seed value SCREAMING_SNAKE_CASE_: Dict =[[]] # because empty string has empty combination # iterate through the indices for i in range(lowercase ): # condition if table[i] != []: for word in word_bank: # slice condition if target[i : i + len(lowercase )] == word: SCREAMING_SNAKE_CASE_: list[list[str]] =[ [word, *way] for way in table[i] ] # adds the word to every combination the current position holds # now,push that combination to the table[i+len(word)] table[i + len(lowercase )] += new_combinations # combinations are in reverse order so reverse for better output for combination in table[len(lowercase )]: combination.reverse() return table[len(lowercase )] if __name__ == "__main__": print(all_construct("""jwajalapa""", ["""jwa""", """j""", """w""", """a""", """la""", """lapa"""])) print(all_construct("""rajamati""", ["""s""", """raj""", """amat""", """raja""", """ma""", """i""", """t"""])) print( all_construct( """hexagonosaurus""", ["""h""", """ex""", """hex""", """ag""", """ago""", """ru""", """auru""", """rus""", """go""", """no""", """o""", """s"""], ) )
36
"""simple docstring""" def __magic_name__ ( lowercase ): if upper_limit < 0: raise ValueError("""Limit for the Catalan sequence must be ≥ 0""" ) SCREAMING_SNAKE_CASE_: Tuple =[0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 SCREAMING_SNAKE_CASE_: Any =1 if upper_limit > 0: SCREAMING_SNAKE_CASE_: List[str] =1 # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i for i in range(2 , upper_limit + 1 ): for j in range(lowercase ): catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1] return catalan_list if __name__ == "__main__": print("""\n********* Catalan Numbers Using Dynamic Programming ************\n""") print("""\n*** Enter -1 at any time to quit ***""") print("""\nEnter the upper limit (≥ 0) for the Catalan number sequence: """, end="""""") try: while True: _UpperCAmelCase = int(input().strip()) if N < 0: print("""\n********* Goodbye!! ************""") break else: print(f"""The Catalan numbers from 0 through {N} are:""") print(catalan_numbers(N)) print("""Try another upper limit for the sequence: """, end="""""") except (NameError, ValueError): print("""\n********* Invalid input, goodbye! ************\n""") import doctest doctest.testmod()
36
1
"""simple docstring""" def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: int =False while is_sorted is False: # Until all the indices are traversed keep looping SCREAMING_SNAKE_CASE_: Tuple =True for i in range(0 , len(lowercase ) - 1 , 2 ): # iterating over all even indices if input_list[i] > input_list[i + 1]: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[int] =input_list[i + 1], input_list[i] # swapping if elements not in order SCREAMING_SNAKE_CASE_: Tuple =False for i in range(1 , len(lowercase ) - 1 , 2 ): # iterating over all odd indices if input_list[i] > input_list[i + 1]: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: str =input_list[i + 1], input_list[i] # swapping if elements not in order SCREAMING_SNAKE_CASE_: str =False return input_list if __name__ == "__main__": print("""Enter list to be sorted""") _UpperCAmelCase = [int(x) for x in input().split()] # inputing elements of the list in one line _UpperCAmelCase = odd_even_sort(input_list) print("""The sorted list is""") print(sorted_list)
36
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig _UpperCAmelCase = { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/config.json""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/config.json""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/config.json""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/config.json""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/config.json""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/config.json""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json""", } class a ( UpperCAmelCase__ ): UpperCamelCase : Any = 'albert' def __init__( self : Dict , lowerCAmelCase : List[str]=3_0000 , lowerCAmelCase : List[Any]=128 , lowerCAmelCase : List[str]=4096 , lowerCAmelCase : str=12 , lowerCAmelCase : str=1 , lowerCAmelCase : Tuple=64 , lowerCAmelCase : Dict=1_6384 , lowerCAmelCase : int=1 , lowerCAmelCase : str="gelu_new" , lowerCAmelCase : Dict=0 , lowerCAmelCase : Optional[Any]=0 , lowerCAmelCase : str=512 , lowerCAmelCase : Optional[int]=2 , lowerCAmelCase : List[Any]=0.0_2 , lowerCAmelCase : Union[str, Any]=1E-12 , lowerCAmelCase : Tuple=0.1 , lowerCAmelCase : List[Any]="absolute" , lowerCAmelCase : List[Any]=0 , lowerCAmelCase : int=2 , lowerCAmelCase : Optional[int]=3 , **lowerCAmelCase : int , ) -> Tuple: '''simple docstring''' super().__init__(pad_token_id=lowerCAmelCase , bos_token_id=lowerCAmelCase , eos_token_id=lowerCAmelCase , **lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =vocab_size SCREAMING_SNAKE_CASE_: Optional[int] =embedding_size SCREAMING_SNAKE_CASE_: Optional[int] =hidden_size SCREAMING_SNAKE_CASE_: Tuple =num_hidden_layers SCREAMING_SNAKE_CASE_: Any =num_hidden_groups SCREAMING_SNAKE_CASE_: List[Any] =num_attention_heads SCREAMING_SNAKE_CASE_: List[Any] =inner_group_num SCREAMING_SNAKE_CASE_: Optional[int] =hidden_act SCREAMING_SNAKE_CASE_: int =intermediate_size SCREAMING_SNAKE_CASE_: Any =hidden_dropout_prob SCREAMING_SNAKE_CASE_: Union[str, Any] =attention_probs_dropout_prob SCREAMING_SNAKE_CASE_: int =max_position_embeddings SCREAMING_SNAKE_CASE_: Any =type_vocab_size SCREAMING_SNAKE_CASE_: int =initializer_range SCREAMING_SNAKE_CASE_: List[Any] =layer_norm_eps SCREAMING_SNAKE_CASE_: Dict =classifier_dropout_prob SCREAMING_SNAKE_CASE_: int =position_embedding_type class a ( UpperCAmelCase__ ): @property def lowerCamelCase__ ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": SCREAMING_SNAKE_CASE_: str ={0: """batch""", 1: """choice""", 2: """sequence"""} else: SCREAMING_SNAKE_CASE_: Dict ={0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
36
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionInstructPixaPixPipeline, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.utils import floats_tensor, load_image, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class a ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): UpperCamelCase : Optional[Any] = StableDiffusionInstructPixaPixPipeline UpperCamelCase : Union[str, Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width', 'cross_attention_kwargs'} UpperCamelCase : List[str] = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS UpperCamelCase : List[str] = IMAGE_TO_IMAGE_IMAGE_PARAMS UpperCamelCase : Tuple = IMAGE_TO_IMAGE_IMAGE_PARAMS def lowerCamelCase__ ( self : Tuple ) -> List[Any]: '''simple docstring''' torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_: List[str] =UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=8 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) SCREAMING_SNAKE_CASE_: Any =PNDMScheduler(skip_prk_steps=lowerCAmelCase ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_: Optional[Any] =AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_: Any =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=1000 , ) SCREAMING_SNAKE_CASE_: int =CLIPTextModel(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: int =CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) SCREAMING_SNAKE_CASE_: List[str] ={ """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def lowerCamelCase__ ( self : Optional[int] , lowerCAmelCase : int , lowerCAmelCase : List[Any]=0 ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: Union[str, Any] =floats_tensor((1, 3, 32, 32) , rng=random.Random(lowerCAmelCase ) ).to(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Dict =image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE_: str =Image.fromarray(np.uinta(lowerCAmelCase ) ).convert("""RGB""" ) if str(lowerCAmelCase ).startswith("""mps""" ): SCREAMING_SNAKE_CASE_: List[str] =torch.manual_seed(lowerCAmelCase ) else: SCREAMING_SNAKE_CASE_: List[str] =torch.Generator(device=lowerCAmelCase ).manual_seed(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[Any] ={ """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """image_guidance_scale""": 1, """output_type""": """numpy""", } return inputs def lowerCamelCase__ ( self : List[Any] ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[Any] ="""cpu""" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE_: Any =self.get_dummy_components() SCREAMING_SNAKE_CASE_: List[Any] =StableDiffusionInstructPixaPixPipeline(**lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =sd_pipe.to(lowerCAmelCase ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: str =self.get_dummy_inputs(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =sd_pipe(**lowerCAmelCase ).images SCREAMING_SNAKE_CASE_: int =image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE_: int =np.array([0.7_5_2_6, 0.3_7_5_0, 0.4_5_4_7, 0.6_1_1_7, 0.5_8_6_6, 0.5_0_1_6, 0.4_3_2_7, 0.5_6_4_2, 0.4_8_1_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def lowerCamelCase__ ( self : List[Any] ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict ="""cpu""" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE_: Optional[Any] =self.get_dummy_components() SCREAMING_SNAKE_CASE_: List[Any] =StableDiffusionInstructPixaPixPipeline(**lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =sd_pipe.to(lowerCAmelCase ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =self.get_dummy_inputs(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[Any] ="""french fries""" SCREAMING_SNAKE_CASE_: List[Any] =sd_pipe(**lowerCAmelCase , negative_prompt=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: str =output.images SCREAMING_SNAKE_CASE_: int =image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE_: List[Any] =np.array([0.7_5_1_1, 0.3_6_4_2, 0.4_5_5_3, 0.6_2_3_6, 0.5_7_9_7, 0.5_0_1_3, 0.4_3_4_3, 0.5_6_1_1, 0.4_8_3_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def lowerCamelCase__ ( self : int ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple ="""cpu""" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE_: int =self.get_dummy_components() SCREAMING_SNAKE_CASE_: Optional[int] =StableDiffusionInstructPixaPixPipeline(**lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =sd_pipe.to(lowerCAmelCase ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[Any] =self.get_dummy_inputs(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Union[str, Any] =[inputs["""prompt"""]] * 2 SCREAMING_SNAKE_CASE_: str =np.array(inputs["""image"""] ).astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE_: Dict =torch.from_numpy(lowerCAmelCase ).unsqueeze(0 ).to(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =image / 2 + 0.5 SCREAMING_SNAKE_CASE_: List[str] =image.permute(0 , 3 , 1 , 2 ) SCREAMING_SNAKE_CASE_: Optional[int] =image.repeat(2 , 1 , 1 , 1 ) SCREAMING_SNAKE_CASE_: int =sd_pipe(**lowerCAmelCase ).images SCREAMING_SNAKE_CASE_: Any =image[-1, -3:, -3:, -1] assert image.shape == (2, 32, 32, 3) SCREAMING_SNAKE_CASE_: Tuple =np.array([0.5_8_1_2, 0.5_7_4_8, 0.5_2_2_2, 0.5_9_0_8, 0.5_6_9_5, 0.7_1_7_4, 0.6_8_0_4, 0.5_5_2_3, 0.5_5_7_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def lowerCamelCase__ ( self : List[Any] ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict ="""cpu""" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE_: List[str] =self.get_dummy_components() SCREAMING_SNAKE_CASE_: List[str] =EulerAncestralDiscreteScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule="""scaled_linear""" ) SCREAMING_SNAKE_CASE_: int =StableDiffusionInstructPixaPixPipeline(**lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple =sd_pipe.to(lowerCAmelCase ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Dict =self.get_dummy_inputs(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =sd_pipe(**lowerCAmelCase ).images SCREAMING_SNAKE_CASE_: str =image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE_: List[Any] =[round(lowerCAmelCase , 4 ) for x in image_slice.flatten().tolist()] print(""",""".join([str(lowerCAmelCase ) for x in slice] ) ) assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE_: Tuple =np.array([0.7_4_1_7, 0.3_8_4_2, 0.4_7_3_2, 0.5_7_7_6, 0.5_8_9_1, 0.5_1_3_9, 0.4_0_5_2, 0.5_6_7_3, 0.4_9_8_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def lowerCamelCase__ ( self : str ) -> Tuple: '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def lowerCamelCase__ ( self : Tuple ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[Any] =self.get_dummy_components() SCREAMING_SNAKE_CASE_: Union[str, Any] =StableDiffusionInstructPixaPixPipeline(**lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Union[str, Any] =VaeImageProcessor(do_resize=lowerCAmelCase , do_normalize=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Any =pipe.to(lowerCAmelCase ) pipe.set_progress_bar_config(disable=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =pipe(**self.get_dummy_inputs_by_type(lowerCAmelCase , input_image_type="""pt""" ) )[0] SCREAMING_SNAKE_CASE_: Optional[int] =components["""vae"""] SCREAMING_SNAKE_CASE_: Optional[Any] =self.get_dummy_inputs_by_type(lowerCAmelCase , input_image_type="""pt""" ) for image_param in self.image_latents_params: if image_param in inputs.keys(): SCREAMING_SNAKE_CASE_: Any =vae.encode(inputs[image_param] ).latent_dist.mode() SCREAMING_SNAKE_CASE_: Optional[Any] =pipe(**lowerCAmelCase )[0] SCREAMING_SNAKE_CASE_: int =np.abs(out - out_latents_inputs ).max() self.assertLess(lowerCAmelCase , 1E-4 , """passing latents as image input generate different result from passing image""" ) @slow @require_torch_gpu class a ( unittest.TestCase ): def lowerCamelCase__ ( self : Any ) -> Union[str, Any]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase__ ( self : Optional[int] , lowerCAmelCase : List[Any]=0 ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =torch.manual_seed(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =load_image( """https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg""" ) SCREAMING_SNAKE_CASE_: int ={ """prompt""": """turn him into a cyborg""", """image""": image, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 7.5, """image_guidance_scale""": 1.0, """output_type""": """numpy""", } return inputs def lowerCamelCase__ ( self : Tuple ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Union[str, Any] =StableDiffusionInstructPixaPixPipeline.from_pretrained( """timbrooks/instruct-pix2pix""" , safety_checker=lowerCAmelCase ) pipe.to(lowerCAmelCase ) pipe.set_progress_bar_config(disable=lowerCAmelCase ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE_: Dict =self.get_inputs() SCREAMING_SNAKE_CASE_: str =pipe(**lowerCAmelCase ).images SCREAMING_SNAKE_CASE_: Optional[Any] =image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_: str =np.array([0.5_9_0_2, 0.6_0_1_5, 0.6_0_2_7, 0.5_9_8_3, 0.6_0_9_2, 0.6_0_6_1, 0.5_7_6_5, 0.5_7_8_5, 0.5_5_5_5] ) assert np.abs(expected_slice - image_slice ).max() < 1E-3 def lowerCamelCase__ ( self : Any ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[Any] =StableDiffusionInstructPixaPixPipeline.from_pretrained( """timbrooks/instruct-pix2pix""" , safety_checker=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[Any] =LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(lowerCAmelCase ) pipe.set_progress_bar_config(disable=lowerCAmelCase ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE_: List[Any] =self.get_inputs() SCREAMING_SNAKE_CASE_: Tuple =pipe(**lowerCAmelCase ).images SCREAMING_SNAKE_CASE_: Union[str, Any] =image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_: str =np.array([0.6_5_7_8, 0.6_8_1_7, 0.6_9_7_2, 0.6_7_6_1, 0.6_8_5_6, 0.6_9_1_6, 0.6_4_2_8, 0.6_5_1_6, 0.6_3_0_1] ) assert np.abs(expected_slice - image_slice ).max() < 1E-3 def lowerCamelCase__ ( self : Optional[int] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =StableDiffusionInstructPixaPixPipeline.from_pretrained( """timbrooks/instruct-pix2pix""" , safety_checker=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple =DDIMScheduler.from_config(pipe.scheduler.config ) pipe.to(lowerCAmelCase ) pipe.set_progress_bar_config(disable=lowerCAmelCase ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE_: Dict =self.get_inputs() SCREAMING_SNAKE_CASE_: Any =pipe(**lowerCAmelCase ).images SCREAMING_SNAKE_CASE_: int =image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_: Any =np.array([0.3_8_2_8, 0.3_8_3_4, 0.3_8_1_8, 0.3_7_9_2, 0.3_8_6_5, 0.3_7_5_2, 0.3_7_9_2, 0.3_8_4_7, 0.3_7_5_3] ) assert np.abs(expected_slice - image_slice ).max() < 1E-3 def lowerCamelCase__ ( self : int ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: int =0 def callback_fn(lowerCAmelCase : int , lowerCAmelCase : int , lowerCAmelCase : torch.FloatTensor ) -> None: SCREAMING_SNAKE_CASE_: str =True nonlocal number_of_steps number_of_steps += 1 if step == 1: SCREAMING_SNAKE_CASE_: List[str] =latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) SCREAMING_SNAKE_CASE_: str =latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE_: Tuple =np.array([-0.2_4_6_3, -0.4_6_4_4, -0.9_7_5_6, 1.5_1_7_6, 1.4_4_1_4, 0.7_8_6_6, 0.9_8_9_7, 0.8_5_2_1, 0.7_9_8_3] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2 elif step == 2: SCREAMING_SNAKE_CASE_: int =latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) SCREAMING_SNAKE_CASE_: Union[str, Any] =latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE_: List[str] =np.array([-0.2_6_4_4, -0.4_6_2_6, -0.9_6_5_3, 1.5_1_7_6, 1.4_5_5_1, 0.7_6_8_6, 0.9_8_0_5, 0.8_4_5_2, 0.8_1_1_5] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2 SCREAMING_SNAKE_CASE_: Any =False SCREAMING_SNAKE_CASE_: int =StableDiffusionInstructPixaPixPipeline.from_pretrained( """timbrooks/instruct-pix2pix""" , safety_checker=lowerCAmelCase , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE_: List[str] =pipe.to(lowerCAmelCase ) pipe.set_progress_bar_config(disable=lowerCAmelCase ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE_: int =self.get_inputs() pipe(**lowerCAmelCase , callback=lowerCAmelCase , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def lowerCamelCase__ ( self : Optional[Any] ) -> Dict: '''simple docstring''' torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE_: List[Any] =StableDiffusionInstructPixaPixPipeline.from_pretrained( """timbrooks/instruct-pix2pix""" , safety_checker=lowerCAmelCase , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE_: Union[str, Any] =pipe.to(lowerCAmelCase ) pipe.set_progress_bar_config(disable=lowerCAmelCase ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE_: Any =self.get_inputs() SCREAMING_SNAKE_CASE_: Dict =pipe(**lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =torch.cuda.max_memory_allocated() # make sure that less than 2.2 GB is allocated assert mem_bytes < 2.2 * 10**9 def lowerCamelCase__ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[int] =self.get_inputs() # resize to resolution that is divisible by 8 but not 16 or 32 SCREAMING_SNAKE_CASE_: Optional[Any] =inputs["""image"""].resize((504, 504) ) SCREAMING_SNAKE_CASE_: List[str] ="""timbrooks/instruct-pix2pix""" SCREAMING_SNAKE_CASE_: str =StableDiffusionInstructPixaPixPipeline.from_pretrained( lowerCAmelCase , safety_checker=lowerCAmelCase , ) pipe.to(lowerCAmelCase ) pipe.set_progress_bar_config(disable=lowerCAmelCase ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE_: int =pipe(**lowerCAmelCase ) SCREAMING_SNAKE_CASE_: int =output.images[0] SCREAMING_SNAKE_CASE_: Optional[int] =image[255:258, 383:386, -1] assert image.shape == (504, 504, 3) SCREAMING_SNAKE_CASE_: List[str] =np.array([0.2_7_2_6, 0.2_5_2_9, 0.2_6_6_4, 0.2_6_5_5, 0.2_6_4_1, 0.2_6_4_2, 0.2_5_9_1, 0.2_6_4_9, 0.2_5_9_0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-3
36
"""simple docstring""" from collections import Counter from pathlib import Path from typing import Optional, Tuple import yaml class a ( yaml.SafeLoader ): def lowerCamelCase__ ( self : int , lowerCAmelCase : List[str] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =[self.constructed_objects[key_node] for key_node, _ in node.value] SCREAMING_SNAKE_CASE_: Any =[tuple(lowerCAmelCase ) if isinstance(lowerCAmelCase , lowerCAmelCase ) else key for key in keys] SCREAMING_SNAKE_CASE_: Dict =Counter(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =[key for key in counter if counter[key] > 1] if duplicate_keys: raise TypeError(f'''Got duplicate yaml keys: {duplicate_keys}''' ) def lowerCamelCase__ ( self : Tuple , lowerCAmelCase : str , lowerCAmelCase : Optional[int]=False ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =super().construct_mapping(lowerCAmelCase , deep=lowerCAmelCase ) self._check_no_duplicates_on_constructed_node(lowerCAmelCase ) return mapping def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Dict =list(readme_content.splitlines() ) if full_content and full_content[0] == "---" and "---" in full_content[1:]: SCREAMING_SNAKE_CASE_: Union[str, Any] =full_content[1:].index("""---""" ) + 1 SCREAMING_SNAKE_CASE_: List[str] ="""\n""".join(full_content[1:sep_idx] ) return yamlblock, "\n".join(full_content[sep_idx + 1 :] ) return None, "\n".join(lowercase ) class a ( UpperCAmelCase__ ): # class attributes UpperCamelCase : Tuple = {'train_eval_index'} # train-eval-index in the YAML metadata @classmethod def lowerCamelCase__ ( cls : List[Any] , lowerCAmelCase : Path ) -> "DatasetMetadata": '''simple docstring''' with open(lowerCAmelCase , encoding="""utf-8""" ) as readme_file: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Union[str, Any] =_split_yaml_from_readme(readme_file.read() ) if yaml_string is not None: return cls.from_yaml_string(lowerCAmelCase ) else: return cls() def lowerCamelCase__ ( self : Any , lowerCAmelCase : Path ) -> List[str]: '''simple docstring''' if path.exists(): with open(lowerCAmelCase , encoding="""utf-8""" ) as readme_file: SCREAMING_SNAKE_CASE_: str =readme_file.read() else: SCREAMING_SNAKE_CASE_: str =None SCREAMING_SNAKE_CASE_: Tuple =self._to_readme(lowerCAmelCase ) with open(lowerCAmelCase , """w""" , encoding="""utf-8""" ) as readme_file: readme_file.write(lowerCAmelCase ) def lowerCamelCase__ ( self : Optional[Any] , lowerCAmelCase : Optional[str] = None ) -> str: '''simple docstring''' if readme_content is not None: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[str] =_split_yaml_from_readme(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] ="""---\n""" + self.to_yaml_string() + """---\n""" + content else: SCREAMING_SNAKE_CASE_: List[Any] ="""---\n""" + self.to_yaml_string() + """---\n""" return full_content @classmethod def lowerCamelCase__ ( cls : Optional[int] , lowerCAmelCase : str ) -> "DatasetMetadata": '''simple docstring''' SCREAMING_SNAKE_CASE_: int =yaml.load(lowerCAmelCase , Loader=_NoDuplicateSafeLoader ) or {} # Convert the YAML keys to DatasetMetadata fields SCREAMING_SNAKE_CASE_: List[Any] ={ (key.replace("""-""" , """_""" ) if key.replace("""-""" , """_""" ) in cls._FIELDS_WITH_DASHES else key): value for key, value in metadata_dict.items() } return cls(**lowerCAmelCase ) def lowerCamelCase__ ( self : Dict ) -> str: '''simple docstring''' return yaml.safe_dump( { (key.replace("""_""" , """-""" ) if key in self._FIELDS_WITH_DASHES else key): value for key, value in self.items() } , sort_keys=lowerCAmelCase , allow_unicode=lowerCAmelCase , encoding="""utf-8""" , ).decode("""utf-8""" ) _UpperCAmelCase = { """image-classification""": [], """translation""": [], """image-segmentation""": [], """fill-mask""": [], """automatic-speech-recognition""": [], """token-classification""": [], """sentence-similarity""": [], """audio-classification""": [], """question-answering""": [], """summarization""": [], """zero-shot-classification""": [], """table-to-text""": [], """feature-extraction""": [], """other""": [], """multiple-choice""": [], """text-classification""": [], """text-to-image""": [], """text2text-generation""": [], """zero-shot-image-classification""": [], """tabular-classification""": [], """tabular-regression""": [], """image-to-image""": [], """tabular-to-text""": [], """unconditional-image-generation""": [], """text-retrieval""": [], """text-to-speech""": [], """object-detection""": [], """audio-to-audio""": [], """text-generation""": [], """conversational""": [], """table-question-answering""": [], """visual-question-answering""": [], """image-to-text""": [], """reinforcement-learning""": [], """voice-activity-detection""": [], """time-series-forecasting""": [], """document-question-answering""": [], } if __name__ == "__main__": from argparse import ArgumentParser _UpperCAmelCase = ArgumentParser(usage="""Validate the yaml metadata block of a README.md file.""") ap.add_argument("""readme_filepath""") _UpperCAmelCase = ap.parse_args() _UpperCAmelCase = Path(args.readme_filepath) _UpperCAmelCase = DatasetMetadata.from_readme(readme_filepath) print(dataset_metadata) dataset_metadata.to_readme(readme_filepath)
36
1
"""simple docstring""" 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 a ( UpperCAmelCase__ ): UpperCamelCase : Any = '' UpperCamelCase : Dict = 'hf-legacy' # "hf://"" is reserved for hffs def __init__( self : Any , lowerCAmelCase : Optional[DatasetInfo] = None , lowerCAmelCase : Optional[str] = None , **lowerCAmelCase : Union[str, Any] , ) -> Dict: '''simple docstring''' super().__init__(self , **lowerCAmelCase ) SCREAMING_SNAKE_CASE_: str =repo_info SCREAMING_SNAKE_CASE_: Union[str, Any] =token SCREAMING_SNAKE_CASE_: int =None def lowerCamelCase__ ( self : Optional[int] ) -> Dict: '''simple docstring''' if self.dir_cache is None: SCREAMING_SNAKE_CASE_: List[str] ={} for hf_file in self.repo_info.siblings: # TODO(QL): add sizes SCREAMING_SNAKE_CASE_: Tuple ={ """name""": hf_file.rfilename, """size""": None, """type""": """file""", } self.dir_cache.update( { str(lowerCAmelCase ): {"""name""": str(lowerCAmelCase ), """size""": None, """type""": """directory"""} for d in list(PurePosixPath(hf_file.rfilename ).parents )[:-1] } ) def lowerCamelCase__ ( self : List[Any] , lowerCAmelCase : str , lowerCAmelCase : str = "rb" , **lowerCAmelCase : str , ) -> List[str]: '''simple docstring''' if not isinstance(self.repo_info , lowerCAmelCase ): raise NotImplementedError(f'''Open is only implemented for dataset repositories, but got {self.repo_info}''' ) SCREAMING_SNAKE_CASE_: Optional[Any] =hf_hub_url(self.repo_info.id , lowerCAmelCase , revision=self.repo_info.sha ) return fsspec.open( lowerCAmelCase , mode=lowerCAmelCase , headers=get_authentication_headers_for_url(lowerCAmelCase , use_auth_token=self.token ) , client_kwargs={"""trust_env""": True} , ).open() def lowerCamelCase__ ( self : Any , lowerCAmelCase : Tuple , **lowerCAmelCase : int ) -> Optional[Any]: '''simple docstring''' self._get_dirs() SCREAMING_SNAKE_CASE_: str =self._strip_protocol(lowerCAmelCase ) if path in self.dir_cache: return self.dir_cache[path] else: raise FileNotFoundError(lowerCAmelCase ) def lowerCamelCase__ ( self : List[str] , lowerCAmelCase : Tuple , lowerCAmelCase : Tuple=False , **lowerCAmelCase : Optional[Any] ) -> Tuple: '''simple docstring''' self._get_dirs() SCREAMING_SNAKE_CASE_: int =PurePosixPath(path.strip("""/""" ) ) SCREAMING_SNAKE_CASE_: Optional[Any] ={} for p, f in self.dir_cache.items(): SCREAMING_SNAKE_CASE_: int =PurePosixPath(p.strip("""/""" ) ) SCREAMING_SNAKE_CASE_: Any =p.parent if root == path: SCREAMING_SNAKE_CASE_: Optional[Any] =f SCREAMING_SNAKE_CASE_: str =list(paths.values() ) if detail: return out else: return sorted(f["""name"""] for f in out )
36
"""simple docstring""" import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from xgboost import XGBClassifier def __magic_name__ ( lowercase ): return (data["data"], data["target"]) def __magic_name__ ( lowercase , lowercase ): SCREAMING_SNAKE_CASE_: Dict =XGBClassifier() classifier.fit(lowercase , lowercase ) return classifier def __magic_name__ ( ): SCREAMING_SNAKE_CASE_: Optional[Any] =load_iris() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Tuple =data_handling(lowercase ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[Any] =train_test_split( lowercase , lowercase , test_size=0.25 ) SCREAMING_SNAKE_CASE_: Tuple =iris["""target_names"""] # Create an XGBoost Classifier from the training data SCREAMING_SNAKE_CASE_: Optional[int] =xgboost(lowercase , lowercase ) # Display the confusion matrix of the classifier with both training and test sets ConfusionMatrixDisplay.from_estimator( lowercase , lowercase , lowercase , display_labels=lowercase , cmap="""Blues""" , normalize="""true""" , ) plt.title("""Normalized Confusion Matrix - IRIS Dataset""" ) plt.show() if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
36
1
"""simple docstring""" import unittest from transformers import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING, is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class a : @staticmethod def lowerCamelCase__ ( *lowerCAmelCase : Union[str, Any] , **lowerCAmelCase : str ) -> int: '''simple docstring''' pass @is_pipeline_test @require_torch @require_vision class a ( unittest.TestCase ): UpperCamelCase : Tuple = MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING def lowerCamelCase__ ( self : Any , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Tuple , lowerCAmelCase : Tuple ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[Any] =pipeline("""visual-question-answering""" , model="""hf-internal-testing/tiny-vilt-random-vqa""" ) SCREAMING_SNAKE_CASE_: List[str] =[ { """image""": Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ), """question""": """How many cats are there?""", }, { """image""": """./tests/fixtures/tests_samples/COCO/000000039769.png""", """question""": """How many cats are there?""", }, ] return vqa_pipeline, examples def lowerCamelCase__ ( self : Union[str, Any] , lowerCAmelCase : str , lowerCAmelCase : Any ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[Any] =vqa_pipeline(lowerCAmelCase , top_k=1 ) self.assertEqual( lowerCAmelCase , [ [{"""score""": ANY(lowerCAmelCase ), """answer""": ANY(lowerCAmelCase )}], [{"""score""": ANY(lowerCAmelCase ), """answer""": ANY(lowerCAmelCase )}], ] , ) @require_torch def lowerCamelCase__ ( self : Any ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[Any] =pipeline("""visual-question-answering""" , model="""hf-internal-testing/tiny-vilt-random-vqa""" ) SCREAMING_SNAKE_CASE_: List[Any] ="""./tests/fixtures/tests_samples/COCO/000000039769.png""" SCREAMING_SNAKE_CASE_: Tuple ="""How many cats are there?""" SCREAMING_SNAKE_CASE_: int =vqa_pipeline(image=lowerCAmelCase , question="""How many cats are there?""" , top_k=2 ) self.assertEqual( lowerCAmelCase , [{"""score""": ANY(lowerCAmelCase ), """answer""": ANY(lowerCAmelCase )}, {"""score""": ANY(lowerCAmelCase ), """answer""": ANY(lowerCAmelCase )}] ) SCREAMING_SNAKE_CASE_: List[str] =vqa_pipeline({"""image""": image, """question""": question} , top_k=2 ) self.assertEqual( lowerCAmelCase , [{"""score""": ANY(lowerCAmelCase ), """answer""": ANY(lowerCAmelCase )}, {"""score""": ANY(lowerCAmelCase ), """answer""": ANY(lowerCAmelCase )}] ) @slow @require_torch def lowerCamelCase__ ( self : Dict ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =pipeline("""visual-question-answering""" , model="""dandelin/vilt-b32-finetuned-vqa""" ) SCREAMING_SNAKE_CASE_: List[Any] ="""./tests/fixtures/tests_samples/COCO/000000039769.png""" SCREAMING_SNAKE_CASE_: Dict ="""How many cats are there?""" SCREAMING_SNAKE_CASE_: Union[str, Any] =vqa_pipeline(image=lowerCAmelCase , question=lowerCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(lowerCAmelCase , decimals=4 ) , [{"""score""": 0.8_7_9_9, """answer""": """2"""}, {"""score""": 0.2_9_6, """answer""": """1"""}] ) SCREAMING_SNAKE_CASE_: Optional[int] =vqa_pipeline({"""image""": image, """question""": question} , top_k=2 ) self.assertEqual( nested_simplify(lowerCAmelCase , decimals=4 ) , [{"""score""": 0.8_7_9_9, """answer""": """2"""}, {"""score""": 0.2_9_6, """answer""": """1"""}] ) SCREAMING_SNAKE_CASE_: Optional[int] =vqa_pipeline( [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}] , top_k=2 ) self.assertEqual( nested_simplify(lowerCAmelCase , decimals=4 ) , [[{"""score""": 0.8_7_9_9, """answer""": """2"""}, {"""score""": 0.2_9_6, """answer""": """1"""}]] * 2 , ) @require_tf @unittest.skip("""Visual question answering not implemented in TF""" ) def lowerCamelCase__ ( self : Dict ) -> str: '''simple docstring''' pass
36
"""simple docstring""" from typing import Dict import numpy as np import torch from . import residue_constants as rc from .tensor_utils import tensor_tree_map, tree_map def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Optional[Any] =[] SCREAMING_SNAKE_CASE_: List[str] =[] SCREAMING_SNAKE_CASE_: Any =[] for rt in rc.restypes: SCREAMING_SNAKE_CASE_: Optional[int] =rc.restype_name_to_atomaa_names[rc.restype_atoa[rt]] restype_atomaa_to_atomaa_list.append([(rc.atom_order[name] if name else 0) for name in atom_names] ) SCREAMING_SNAKE_CASE_: Any ={name: i for i, name in enumerate(lowercase )} restype_atomaa_to_atomaa_list.append( [(atom_name_to_idxaa[name] if name in atom_name_to_idxaa else 0) for name in rc.atom_types] ) restype_atomaa_mask_list.append([(1.0 if name else 0.0) for name in atom_names] ) # Add dummy mapping for restype 'UNK' restype_atomaa_to_atomaa_list.append([0] * 14 ) restype_atomaa_to_atomaa_list.append([0] * 37 ) restype_atomaa_mask_list.append([0.0] * 14 ) SCREAMING_SNAKE_CASE_: Union[str, Any] =torch.tensor( lowercase , dtype=torch.intaa , device=protein["""aatype"""].device , ) SCREAMING_SNAKE_CASE_: Optional[Any] =torch.tensor( lowercase , dtype=torch.intaa , device=protein["""aatype"""].device , ) SCREAMING_SNAKE_CASE_: List[str] =torch.tensor( lowercase , dtype=torch.floataa , device=protein["""aatype"""].device , ) SCREAMING_SNAKE_CASE_: Optional[Any] =protein["""aatype"""].to(torch.long ) # create the mapping for (residx, atom14) --> atom37, i.e. an array # with shape (num_res, 14) containing the atom37 indices for this protein SCREAMING_SNAKE_CASE_: List[str] =restype_atomaa_to_atomaa[protein_aatype] SCREAMING_SNAKE_CASE_: Any =restype_atomaa_mask[protein_aatype] SCREAMING_SNAKE_CASE_: Tuple =residx_atomaa_mask SCREAMING_SNAKE_CASE_: Dict =residx_atomaa_to_atomaa.long() # create the gather indices for mapping back SCREAMING_SNAKE_CASE_: Dict =restype_atomaa_to_atomaa[protein_aatype] SCREAMING_SNAKE_CASE_: Optional[int] =residx_atomaa_to_atomaa.long() # create the corresponding mask SCREAMING_SNAKE_CASE_: Optional[int] =torch.zeros([21, 37] , dtype=torch.floataa , device=protein["""aatype"""].device ) for restype, restype_letter in enumerate(rc.restypes ): SCREAMING_SNAKE_CASE_: int =rc.restype_atoa[restype_letter] SCREAMING_SNAKE_CASE_: Any =rc.residue_atoms[restype_name] for atom_name in atom_names: SCREAMING_SNAKE_CASE_: Optional[int] =rc.atom_order[atom_name] SCREAMING_SNAKE_CASE_: Dict =1 SCREAMING_SNAKE_CASE_: List[str] =restype_atomaa_mask[protein_aatype] SCREAMING_SNAKE_CASE_: List[Any] =residx_atomaa_mask return protein def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Any =tree_map(lambda lowercase : torch.tensor(lowercase , device=batch["""aatype"""].device ) , lowercase , np.ndarray ) SCREAMING_SNAKE_CASE_: int =tensor_tree_map(lambda lowercase : np.array(lowercase ) , make_atomaa_masks(lowercase ) ) return out
36
1
"""simple docstring""" # 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 _UpperCAmelCase = """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)
36
"""simple docstring""" from pathlib import Path from typing import List from transformers import is_torch_available, is_vision_available from transformers.testing_utils import get_tests_dir, is_tool_test from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText if is_torch_available(): import torch if is_vision_available(): from PIL import Image _UpperCAmelCase = ["""text""", """image""", """audio"""] def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: str =[] for input_type in input_types: if input_type == "text": inputs.append("""Text input""" ) elif input_type == "image": inputs.append( Image.open(Path(get_tests_dir("""fixtures/tests_samples/COCO""" ) ) / """000000039769.png""" ).resize((512, 512) ) ) elif input_type == "audio": inputs.append(torch.ones(3000 ) ) elif isinstance(lowercase , lowercase ): inputs.append(create_inputs(lowercase ) ) else: raise ValueError(f'''Invalid type requested: {input_type}''' ) return inputs def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: int =[] for output in outputs: if isinstance(lowercase , (str, AgentText) ): output_types.append("""text""" ) elif isinstance(lowercase , (Image.Image, AgentImage) ): output_types.append("""image""" ) elif isinstance(lowercase , (torch.Tensor, AgentAudio) ): output_types.append("""audio""" ) else: raise ValueError(f'''Invalid output: {output}''' ) return output_types @is_tool_test class a : def lowerCamelCase__ ( self : Tuple ) -> List[Any]: '''simple docstring''' self.assertTrue(hasattr(self.tool , """inputs""" ) ) self.assertTrue(hasattr(self.tool , """outputs""" ) ) SCREAMING_SNAKE_CASE_: Optional[int] =self.tool.inputs for _input in inputs: if isinstance(_input , lowerCAmelCase ): for __input in _input: self.assertTrue(__input in authorized_types ) else: self.assertTrue(_input in authorized_types ) SCREAMING_SNAKE_CASE_: Any =self.tool.outputs for _output in outputs: self.assertTrue(_output in authorized_types ) def lowerCamelCase__ ( self : str ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =create_inputs(self.tool.inputs ) SCREAMING_SNAKE_CASE_: List[Any] =self.tool(*lowerCAmelCase ) # There is a single output if len(self.tool.outputs ) == 1: SCREAMING_SNAKE_CASE_: str =[outputs] self.assertListEqual(output_types(lowerCAmelCase ) , self.tool.outputs ) def lowerCamelCase__ ( self : str ) -> Optional[Any]: '''simple docstring''' self.assertTrue(hasattr(self.tool , """description""" ) ) self.assertTrue(hasattr(self.tool , """default_checkpoint""" ) ) self.assertTrue(self.tool.description.startswith("""This is a tool that""" ) ) def lowerCamelCase__ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: str =create_inputs(self.tool.inputs ) SCREAMING_SNAKE_CASE_: Tuple =self.tool(*lowerCAmelCase ) if not isinstance(lowerCAmelCase , lowerCAmelCase ): SCREAMING_SNAKE_CASE_: int =[outputs] self.assertEqual(len(lowerCAmelCase ) , len(self.tool.outputs ) ) for output, output_type in zip(lowerCAmelCase , self.tool.outputs ): SCREAMING_SNAKE_CASE_: int =AGENT_TYPE_MAPPING[output_type] self.assertTrue(isinstance(lowerCAmelCase , lowerCAmelCase ) ) def lowerCamelCase__ ( self : List[Any] ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =create_inputs(self.tool.inputs ) SCREAMING_SNAKE_CASE_: Union[str, Any] =[] for _input, input_type in zip(lowerCAmelCase , self.tool.inputs ): if isinstance(lowerCAmelCase , lowerCAmelCase ): _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input ) for _input_type in input_type] ) else: _inputs.append(AGENT_TYPE_MAPPING[input_type](_input ) ) # Should not raise an error SCREAMING_SNAKE_CASE_: Dict =self.tool(*lowerCAmelCase ) if not isinstance(lowerCAmelCase , lowerCAmelCase ): SCREAMING_SNAKE_CASE_: List[str] =[outputs] self.assertEqual(len(lowerCAmelCase ) , len(self.tool.outputs ) )
36
1
"""simple docstring""" from __future__ import annotations import time _UpperCAmelCase = list[tuple[int, int]] _UpperCAmelCase = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] _UpperCAmelCase = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class a : def __init__( self : Optional[int] , lowerCAmelCase : int , lowerCAmelCase : int , lowerCAmelCase : int , lowerCAmelCase : int , lowerCAmelCase : Node | None ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =pos_x SCREAMING_SNAKE_CASE_: Optional[int] =pos_y SCREAMING_SNAKE_CASE_: List[str] =(pos_y, pos_x) SCREAMING_SNAKE_CASE_: Any =goal_x SCREAMING_SNAKE_CASE_: List[Any] =goal_y SCREAMING_SNAKE_CASE_: List[str] =parent class a : def __init__( self : int , lowerCAmelCase : tuple[int, int] , lowerCAmelCase : tuple[int, int] ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[str] =Node(start[1] , start[0] , goal[1] , goal[0] , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =Node(goal[1] , goal[0] , goal[1] , goal[0] , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Dict =[self.start] SCREAMING_SNAKE_CASE_: Tuple =False def lowerCamelCase__ ( self : str ) -> Path | None: '''simple docstring''' while self.node_queue: SCREAMING_SNAKE_CASE_: Dict =self.node_queue.pop(0 ) if current_node.pos == self.target.pos: SCREAMING_SNAKE_CASE_: Optional[Any] =True return self.retrace_path(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple =self.get_successors(lowerCAmelCase ) for node in successors: self.node_queue.append(lowerCAmelCase ) if not self.reached: return [self.start.pos] return None def lowerCamelCase__ ( self : List[str] , lowerCAmelCase : Node ) -> list[Node]: '''simple docstring''' SCREAMING_SNAKE_CASE_: int =[] for action in delta: SCREAMING_SNAKE_CASE_: Optional[Any] =parent.pos_x + action[1] SCREAMING_SNAKE_CASE_: Dict =parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(lowerCAmelCase ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(lowerCAmelCase , lowerCAmelCase , self.target.pos_y , self.target.pos_x , lowerCAmelCase ) ) return successors def lowerCamelCase__ ( self : Union[str, Any] , lowerCAmelCase : Node | None ) -> Path: '''simple docstring''' SCREAMING_SNAKE_CASE_: int =node SCREAMING_SNAKE_CASE_: int =[] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) SCREAMING_SNAKE_CASE_: str =current_node.parent path.reverse() return path class a : def __init__( self : Union[str, Any] , lowerCAmelCase : int , lowerCAmelCase : List[Any] ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[Any] =BreadthFirstSearch(lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =BreadthFirstSearch(lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[Any] =False def lowerCamelCase__ ( self : Union[str, Any] ) -> Path | None: '''simple docstring''' while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: SCREAMING_SNAKE_CASE_: Optional[int] =self.fwd_bfs.node_queue.pop(0 ) SCREAMING_SNAKE_CASE_: List[str] =self.bwd_bfs.node_queue.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: SCREAMING_SNAKE_CASE_: Any =True return self.retrace_bidirectional_path( lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =current_bwd_node SCREAMING_SNAKE_CASE_: Dict =current_fwd_node SCREAMING_SNAKE_CASE_: List[str] ={ self.fwd_bfs: self.fwd_bfs.get_successors(lowerCAmelCase ), self.bwd_bfs: self.bwd_bfs.get_successors(lowerCAmelCase ), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(lowerCAmelCase ) if not self.reached: return [self.fwd_bfs.start.pos] return None def lowerCamelCase__ ( self : Dict , lowerCAmelCase : Node , lowerCAmelCase : Node ) -> Path: '''simple docstring''' SCREAMING_SNAKE_CASE_: int =self.fwd_bfs.retrace_path(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple =self.bwd_bfs.retrace_path(lowerCAmelCase ) bwd_path.pop() bwd_path.reverse() SCREAMING_SNAKE_CASE_: Any =fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() _UpperCAmelCase = (0, 0) _UpperCAmelCase = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) _UpperCAmelCase = time.time() _UpperCAmelCase = BreadthFirstSearch(init, goal) _UpperCAmelCase = bfs.search() _UpperCAmelCase = time.time() - start_bfs_time print("""Unidirectional BFS computation time : """, bfs_time) _UpperCAmelCase = time.time() _UpperCAmelCase = BidirectionalBreadthFirstSearch(init, goal) _UpperCAmelCase = bd_bfs.search() _UpperCAmelCase = time.time() - start_bd_bfs_time print("""Bidirectional BFS computation time : """, bd_bfs_time)
36
"""simple docstring""" from __future__ import annotations def __magic_name__ ( lowercase , lowercase ): SCREAMING_SNAKE_CASE_: List[Any] =sorted(numsa + numsa ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Tuple =divmod(len(lowercase ) , 2 ) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() _UpperCAmelCase = [float(x) for x in input("""Enter the elements of first array: """).split()] _UpperCAmelCase = [float(x) for x in input("""Enter the elements of second array: """).split()] print(f"""The median of two arrays is: {median_of_two_arrays(array_a, array_a)}""")
36
1
"""simple docstring""" class a : def __init__( self : Optional[int] , lowerCAmelCase : list ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =set_counts SCREAMING_SNAKE_CASE_: Union[str, Any] =max(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[Any] =len(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[Any] =[1] * num_sets SCREAMING_SNAKE_CASE_: Union[str, Any] =list(range(lowerCAmelCase ) ) def lowerCamelCase__ ( self : Any , lowerCAmelCase : int , lowerCAmelCase : int ) -> bool: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[Any] =self.get_parent(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Union[str, Any] =self.get_parent(lowerCAmelCase ) if src_parent == dst_parent: return False if self.ranks[dst_parent] >= self.ranks[src_parent]: self.set_counts[dst_parent] += self.set_counts[src_parent] SCREAMING_SNAKE_CASE_: Union[str, Any] =0 SCREAMING_SNAKE_CASE_: Union[str, Any] =dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 SCREAMING_SNAKE_CASE_: Any =self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] SCREAMING_SNAKE_CASE_: List[str] =0 SCREAMING_SNAKE_CASE_: List[str] =src_parent SCREAMING_SNAKE_CASE_: Union[str, Any] =self.set_counts[src_parent] SCREAMING_SNAKE_CASE_: Tuple =max(self.max_set , lowerCAmelCase ) return True def lowerCamelCase__ ( self : Dict , lowerCAmelCase : int ) -> int: '''simple docstring''' if self.parents[disj_set] == disj_set: return disj_set SCREAMING_SNAKE_CASE_: Any =self.get_parent(self.parents[disj_set] ) return self.parents[disj_set]
36
"""simple docstring""" import copy import inspect import unittest from transformers import PretrainedConfig, SwiftFormerConfig from transformers.testing_utils import ( require_torch, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwiftFormerForImageClassification, SwiftFormerModel from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class a : def __init__( self : Any , lowerCAmelCase : Any , lowerCAmelCase : List[str]=13 , lowerCAmelCase : Dict=3 , lowerCAmelCase : Optional[Any]=True , lowerCAmelCase : Dict=True , lowerCAmelCase : Dict=0.1 , lowerCAmelCase : str=0.1 , lowerCAmelCase : List[str]=224 , lowerCAmelCase : List[str]=1000 , lowerCAmelCase : Optional[Any]=[3, 3, 6, 4] , lowerCAmelCase : int=[48, 56, 112, 220] , ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[int] =parent SCREAMING_SNAKE_CASE_: Any =batch_size SCREAMING_SNAKE_CASE_: Tuple =num_channels SCREAMING_SNAKE_CASE_: Union[str, Any] =is_training SCREAMING_SNAKE_CASE_: Tuple =use_labels SCREAMING_SNAKE_CASE_: Optional[int] =hidden_dropout_prob SCREAMING_SNAKE_CASE_: Tuple =attention_probs_dropout_prob SCREAMING_SNAKE_CASE_: List[Any] =num_labels SCREAMING_SNAKE_CASE_: int =image_size SCREAMING_SNAKE_CASE_: Optional[Any] =layer_depths SCREAMING_SNAKE_CASE_: List[Any] =embed_dims def lowerCamelCase__ ( self : List[Any] ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[str] =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_: List[Any] =None if self.use_labels: SCREAMING_SNAKE_CASE_: List[str] =ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE_: Tuple =self.get_config() return config, pixel_values, labels def lowerCamelCase__ ( self : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' return SwiftFormerConfig( depths=self.layer_depths , embed_dims=self.embed_dims , mlp_ratio=4 , downsamples=[True, True, True, True] , hidden_act="""gelu""" , num_labels=self.num_labels , down_patch_size=3 , down_stride=2 , down_pad=1 , drop_rate=0.0 , drop_path_rate=0.0 , use_layer_scale=lowerCAmelCase , layer_scale_init_value=1E-5 , ) def lowerCamelCase__ ( self : Any , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Optional[Any] , lowerCAmelCase : Optional[int] ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[str] =SwiftFormerModel(config=lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() SCREAMING_SNAKE_CASE_: Any =model(lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dims[-1], 7, 7) ) def lowerCamelCase__ ( self : Union[str, Any] , lowerCAmelCase : List[Any] , lowerCAmelCase : Optional[int] , lowerCAmelCase : Union[str, Any] ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[Any] =self.num_labels SCREAMING_SNAKE_CASE_: Dict =SwiftFormerForImageClassification(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() SCREAMING_SNAKE_CASE_: Dict =model(lowerCAmelCase , labels=lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) SCREAMING_SNAKE_CASE_: int =SwiftFormerForImageClassification(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() SCREAMING_SNAKE_CASE_: Tuple =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_: Dict =model(lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase__ ( self : int ) -> Optional[Any]: '''simple docstring''' ((SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_)): str =self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_: Tuple ={"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class a ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): UpperCamelCase : Optional[int] = (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else () UpperCamelCase : Tuple = ( {'feature-extraction': SwiftFormerModel, 'image-classification': SwiftFormerForImageClassification} if is_torch_available() else {} ) UpperCamelCase : Any = False UpperCamelCase : Optional[int] = False UpperCamelCase : Optional[Any] = False UpperCamelCase : Dict = False UpperCamelCase : List[str] = False def lowerCamelCase__ ( self : Dict ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =SwiftFormerModelTester(self ) SCREAMING_SNAKE_CASE_: Union[str, Any] =ConfigTester( self , config_class=lowerCAmelCase , has_text_modality=lowerCAmelCase , hidden_size=37 , num_attention_heads=12 , num_hidden_layers=12 , ) def lowerCamelCase__ ( self : Tuple ) -> int: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="""SwiftFormer does not use inputs_embeds""" ) def lowerCamelCase__ ( self : Tuple ) -> List[str]: '''simple docstring''' pass def lowerCamelCase__ ( self : Optional[int] ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[str] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_: Any =model_class(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[Any] =model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCAmelCase , nn.Linear ) ) def lowerCamelCase__ ( self : str ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[Any] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_: int =model_class(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[Any] =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE_: Any =[*signature.parameters.keys()] SCREAMING_SNAKE_CASE_: Tuple =["""pixel_values"""] self.assertListEqual(arg_names[:1] , lowerCAmelCase ) def lowerCamelCase__ ( self : int ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase ) def lowerCamelCase__ ( self : Any ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: int =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase ) @slow def lowerCamelCase__ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_: Optional[Any] =SwiftFormerModel.from_pretrained(lowerCAmelCase ) self.assertIsNotNone(lowerCAmelCase ) @unittest.skip(reason="""SwiftFormer does not output attentions""" ) def lowerCamelCase__ ( self : Optional[int] ) -> str: '''simple docstring''' pass def lowerCamelCase__ ( self : List[Any] ) -> List[str]: '''simple docstring''' def check_hidden_states_output(lowerCAmelCase : Optional[int] , lowerCAmelCase : str , lowerCAmelCase : Optional[int] ): SCREAMING_SNAKE_CASE_: Optional[Any] =model_class(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_: List[str] =model(**self._prepare_for_class(lowerCAmelCase , lowerCAmelCase ) ) SCREAMING_SNAKE_CASE_: Dict =outputs.hidden_states SCREAMING_SNAKE_CASE_: List[Any] =8 self.assertEqual(len(lowerCAmelCase ) , lowerCAmelCase ) # TODO # SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width) # with the width and height being successively divided by 2, after every 2 blocks for i in range(len(lowerCAmelCase ) ): self.assertEqual( hidden_states[i].shape , torch.Size( [ self.model_tester.batch_size, self.model_tester.embed_dims[i // 2], (self.model_tester.image_size // 4) // 2 ** (i // 2), (self.model_tester.image_size // 4) // 2 ** (i // 2), ] ) , ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: int =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_: Dict =True check_hidden_states_output(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE_: Any =True check_hidden_states_output(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) def lowerCamelCase__ ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' def _config_zero_init(lowerCAmelCase : str ): SCREAMING_SNAKE_CASE_: Dict =copy.deepcopy(lowerCAmelCase ) for key in configs_no_init.__dict__.keys(): if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key: setattr(lowerCAmelCase , lowerCAmelCase , 1E-10 ) if isinstance(getattr(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) , lowerCAmelCase ): SCREAMING_SNAKE_CASE_: Tuple =_config_zero_init(getattr(lowerCAmelCase , lowerCAmelCase ) ) setattr(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) return configs_no_init SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[Any] =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_: List[Any] =_config_zero_init(lowerCAmelCase ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_: Any =model_class(config=lowerCAmelCase ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1E9) / 1E9).round().item() , [0.0, 1.0] , msg=f'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def lowerCamelCase__ ( self : List[str] ) -> List[str]: '''simple docstring''' pass def __magic_name__ ( ): SCREAMING_SNAKE_CASE_: List[Any] =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class a ( unittest.TestCase ): @cached_property def lowerCamelCase__ ( self : str ) -> str: '''simple docstring''' return ViTImageProcessor.from_pretrained("""MBZUAI/swiftformer-xs""" ) if is_vision_available() else None @slow def lowerCamelCase__ ( self : Union[str, Any] ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: str =SwiftFormerForImageClassification.from_pretrained("""MBZUAI/swiftformer-xs""" ).to(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: str =self.default_image_processor SCREAMING_SNAKE_CASE_: int =prepare_img() SCREAMING_SNAKE_CASE_: Union[str, Any] =image_processor(images=lowerCAmelCase , return_tensors="""pt""" ).to(lowerCAmelCase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_: Dict =model(**lowerCAmelCase ) # verify the logits SCREAMING_SNAKE_CASE_: Optional[Any] =torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =torch.tensor([[-2.1_703E00, 2.1_107E00, -2.0_811E00]] ).to(lowerCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCAmelCase , atol=1E-4 ) )
36
1
"""simple docstring""" import unittest from transformers import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, is_vision_available, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class a : @staticmethod def lowerCamelCase__ ( *lowerCAmelCase : Tuple , **lowerCAmelCase : Optional[int] ) -> Optional[int]: '''simple docstring''' pass @is_pipeline_test @require_vision @require_torch class a ( unittest.TestCase ): UpperCamelCase : Union[str, Any] = MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING def lowerCamelCase__ ( self : int , lowerCAmelCase : str , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Tuple ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =pipeline( """zero-shot-object-detection""" , model="""hf-internal-testing/tiny-random-owlvit-object-detection""" ) SCREAMING_SNAKE_CASE_: List[Any] =[ { """image""": """./tests/fixtures/tests_samples/COCO/000000039769.png""", """candidate_labels""": ["""cat""", """remote""", """couch"""], } ] return object_detector, examples def lowerCamelCase__ ( self : str , lowerCAmelCase : List[str] , lowerCAmelCase : List[str] ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[Any] =object_detector(examples[0] , threshold=0.0 ) SCREAMING_SNAKE_CASE_: Union[str, Any] =len(lowerCAmelCase ) self.assertGreater(lowerCAmelCase , 0 ) self.assertEqual( lowerCAmelCase , [ { """score""": ANY(lowerCAmelCase ), """label""": ANY(lowerCAmelCase ), """box""": {"""xmin""": ANY(lowerCAmelCase ), """ymin""": ANY(lowerCAmelCase ), """xmax""": ANY(lowerCAmelCase ), """ymax""": ANY(lowerCAmelCase )}, } for i in range(lowerCAmelCase ) ] , ) @require_tf @unittest.skip("""Zero Shot Object Detection not implemented in TF""" ) def lowerCamelCase__ ( self : List[Any] ) -> List[str]: '''simple docstring''' pass @require_torch def lowerCamelCase__ ( self : Tuple ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[int] =pipeline( """zero-shot-object-detection""" , model="""hf-internal-testing/tiny-random-owlvit-object-detection""" ) SCREAMING_SNAKE_CASE_: int =object_detector( """./tests/fixtures/tests_samples/COCO/000000039769.png""" , candidate_labels=["""cat""", """remote""", """couch"""] , threshold=0.6_4 , ) self.assertEqual( nested_simplify(lowerCAmelCase , decimals=4 ) , [ {"""score""": 0.7_2_3_5, """label""": """cat""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}}, {"""score""": 0.7_2_1_8, """label""": """remote""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}}, {"""score""": 0.7_1_8_4, """label""": """couch""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}}, {"""score""": 0.6_7_4_8, """label""": """remote""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}}, {"""score""": 0.6_6_5_6, """label""": """cat""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}}, {"""score""": 0.6_6_1_4, """label""": """couch""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}}, {"""score""": 0.6_4_5_6, """label""": """remote""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}}, {"""score""": 0.6_4_2, """label""": """remote""", """box""": {"""xmin""": 67, """ymin""": 274, """xmax""": 93, """ymax""": 297}}, {"""score""": 0.6_4_1_9, """label""": """cat""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}}, ] , ) SCREAMING_SNAKE_CASE_: Optional[Any] =object_detector( [ { """image""": """./tests/fixtures/tests_samples/COCO/000000039769.png""", """candidate_labels""": ["""cat""", """remote""", """couch"""], } ] , threshold=0.6_4 , ) self.assertEqual( nested_simplify(lowerCAmelCase , decimals=4 ) , [ [ {"""score""": 0.7_2_3_5, """label""": """cat""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}}, {"""score""": 0.7_2_1_8, """label""": """remote""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}}, {"""score""": 0.7_1_8_4, """label""": """couch""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}}, {"""score""": 0.6_7_4_8, """label""": """remote""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}}, {"""score""": 0.6_6_5_6, """label""": """cat""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}}, {"""score""": 0.6_6_1_4, """label""": """couch""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}}, {"""score""": 0.6_4_5_6, """label""": """remote""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}}, {"""score""": 0.6_4_2, """label""": """remote""", """box""": {"""xmin""": 67, """ymin""": 274, """xmax""": 93, """ymax""": 297}}, {"""score""": 0.6_4_1_9, """label""": """cat""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}}, ] ] , ) @require_torch @slow def lowerCamelCase__ ( self : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: str =pipeline("""zero-shot-object-detection""" ) SCREAMING_SNAKE_CASE_: Optional[int] =object_detector( """http://images.cocodataset.org/val2017/000000039769.jpg""" , candidate_labels=["""cat""", """remote""", """couch"""] , ) self.assertEqual( nested_simplify(lowerCAmelCase , decimals=4 ) , [ {"""score""": 0.2_8_6_8, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}}, {"""score""": 0.2_7_7, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}}, {"""score""": 0.2_5_3_7, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}}, {"""score""": 0.1_4_7_4, """label""": """remote""", """box""": {"""xmin""": 335, """ymin""": 74, """xmax""": 371, """ymax""": 187}}, {"""score""": 0.1_2_0_8, """label""": """couch""", """box""": {"""xmin""": 4, """ymin""": 0, """xmax""": 642, """ymax""": 476}}, ] , ) SCREAMING_SNAKE_CASE_: Tuple =object_detector( [ { """image""": """http://images.cocodataset.org/val2017/000000039769.jpg""", """candidate_labels""": ["""cat""", """remote""", """couch"""], }, { """image""": """http://images.cocodataset.org/val2017/000000039769.jpg""", """candidate_labels""": ["""cat""", """remote""", """couch"""], }, ] , ) self.assertEqual( nested_simplify(lowerCAmelCase , decimals=4 ) , [ [ {"""score""": 0.2_8_6_8, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}}, {"""score""": 0.2_7_7, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}}, {"""score""": 0.2_5_3_7, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}}, {"""score""": 0.1_4_7_4, """label""": """remote""", """box""": {"""xmin""": 335, """ymin""": 74, """xmax""": 371, """ymax""": 187}}, {"""score""": 0.1_2_0_8, """label""": """couch""", """box""": {"""xmin""": 4, """ymin""": 0, """xmax""": 642, """ymax""": 476}}, ], [ {"""score""": 0.2_8_6_8, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}}, {"""score""": 0.2_7_7, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}}, {"""score""": 0.2_5_3_7, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}}, {"""score""": 0.1_4_7_4, """label""": """remote""", """box""": {"""xmin""": 335, """ymin""": 74, """xmax""": 371, """ymax""": 187}}, {"""score""": 0.1_2_0_8, """label""": """couch""", """box""": {"""xmin""": 4, """ymin""": 0, """xmax""": 642, """ymax""": 476}}, ], ] , ) @require_tf @unittest.skip("""Zero Shot Object Detection not implemented in TF""" ) def lowerCamelCase__ ( self : Union[str, Any] ) -> Any: '''simple docstring''' pass @require_torch @slow def lowerCamelCase__ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =0.2 SCREAMING_SNAKE_CASE_: List[Any] =pipeline("""zero-shot-object-detection""" ) SCREAMING_SNAKE_CASE_: Tuple =object_detector( """http://images.cocodataset.org/val2017/000000039769.jpg""" , candidate_labels=["""cat""", """remote""", """couch"""] , threshold=lowerCAmelCase , ) self.assertEqual( nested_simplify(lowerCAmelCase , decimals=4 ) , [ {"""score""": 0.2_8_6_8, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}}, {"""score""": 0.2_7_7, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}}, {"""score""": 0.2_5_3_7, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}}, ] , ) @require_torch @slow def lowerCamelCase__ ( self : int ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[int] =2 SCREAMING_SNAKE_CASE_: Dict =pipeline("""zero-shot-object-detection""" ) SCREAMING_SNAKE_CASE_: Dict =object_detector( """http://images.cocodataset.org/val2017/000000039769.jpg""" , candidate_labels=["""cat""", """remote""", """couch"""] , top_k=lowerCAmelCase , ) self.assertEqual( nested_simplify(lowerCAmelCase , decimals=4 ) , [ {"""score""": 0.2_8_6_8, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}}, {"""score""": 0.2_7_7, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}}, ] , )
36
"""simple docstring""" from math import pi def __magic_name__ ( lowercase , lowercase ): return 2 * pi * radius * (angle / 360) if __name__ == "__main__": print(arc_length(9_0, 1_0))
36
1
"""simple docstring""" import argparse import os import torch from transformers.utils import WEIGHTS_NAME _UpperCAmelCase = ["""small""", """medium""", """large"""] _UpperCAmelCase = """lm_head.decoder.weight""" _UpperCAmelCase = """lm_head.weight""" def __magic_name__ ( lowercase , lowercase ): SCREAMING_SNAKE_CASE_: List[Any] =torch.load(lowercase ) SCREAMING_SNAKE_CASE_: Union[str, Any] =d.pop(lowercase ) os.makedirs(lowercase , exist_ok=lowercase ) torch.save(lowercase , os.path.join(lowercase , lowercase ) ) if __name__ == "__main__": _UpperCAmelCase = argparse.ArgumentParser() parser.add_argument("""--dialogpt_path""", default=""".""", type=str) _UpperCAmelCase = parser.parse_args() for MODEL in DIALOGPT_MODELS: _UpperCAmelCase = os.path.join(args.dialogpt_path, f"""{MODEL}_ft.pkl""") _UpperCAmelCase = f"""./DialoGPT-{MODEL}""" convert_dialogpt_checkpoint( checkpoint_path, pytorch_dump_folder_path, )
36
"""simple docstring""" 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 a ( unittest.TestCase ): def lowerCamelCase__ ( self : Dict ) -> str: '''simple docstring''' super().tearDown() gc.collect() def lowerCamelCase__ ( self : Optional[Any] ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Dict =FlaxStableDiffusionPipeline.from_pretrained( """stabilityai/stable-diffusion-2""" , revision="""bf16""" , dtype=jnp.bfloataa , ) SCREAMING_SNAKE_CASE_: Union[str, Any] ="""A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE_: Any =jax.device_count() SCREAMING_SNAKE_CASE_: Dict =num_samples * [prompt] SCREAMING_SNAKE_CASE_: List[Any] =sd_pipe.prepare_inputs(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Union[str, Any] =replicate(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =shard(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Dict =jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE_: Union[str, Any] =jax.random.split(lowerCAmelCase , jax.device_count() ) SCREAMING_SNAKE_CASE_: Tuple =sd_pipe(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , num_inference_steps=25 , jit=lowerCAmelCase )[0] assert images.shape == (jax.device_count(), 1, 768, 768, 3) SCREAMING_SNAKE_CASE_: Dict =images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) SCREAMING_SNAKE_CASE_: Dict =images[0, 253:256, 253:256, -1] SCREAMING_SNAKE_CASE_: Optional[int] =jnp.asarray(jax.device_get(image_slice.flatten() ) ) SCREAMING_SNAKE_CASE_: Optional[int] =jnp.array([0.4_2_3_8, 0.4_4_1_4, 0.4_3_9_5, 0.4_4_5_3, 0.4_6_2_9, 0.4_5_9_0, 0.4_5_3_1, 0.4_5_5_0_8, 0.4_5_1_2] ) print(f'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2 def lowerCamelCase__ ( self : List[str] ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE_: int ="""stabilityai/stable-diffusion-2""" SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[int] =FlaxDPMSolverMultistepScheduler.from_pretrained(lowerCAmelCase , subfolder="""scheduler""" ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[int] =FlaxStableDiffusionPipeline.from_pretrained( lowerCAmelCase , scheduler=lowerCAmelCase , revision="""bf16""" , dtype=jnp.bfloataa , ) SCREAMING_SNAKE_CASE_: Optional[int] =scheduler_params SCREAMING_SNAKE_CASE_: Tuple ="""A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE_: Union[str, Any] =jax.device_count() SCREAMING_SNAKE_CASE_: Optional[Any] =num_samples * [prompt] SCREAMING_SNAKE_CASE_: List[Any] =sd_pipe.prepare_inputs(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple =replicate(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =shard(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Any =jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE_: Any =jax.random.split(lowerCAmelCase , jax.device_count() ) SCREAMING_SNAKE_CASE_: Tuple =sd_pipe(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , num_inference_steps=25 , jit=lowerCAmelCase )[0] assert images.shape == (jax.device_count(), 1, 768, 768, 3) SCREAMING_SNAKE_CASE_: str =images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) SCREAMING_SNAKE_CASE_: Any =images[0, 253:256, 253:256, -1] SCREAMING_SNAKE_CASE_: Optional[Any] =jnp.asarray(jax.device_get(image_slice.flatten() ) ) SCREAMING_SNAKE_CASE_: Optional[int] =jnp.array([0.4_3_3_6, 0.4_2_9_6_9, 0.4_4_5_3, 0.4_1_9_9, 0.4_2_9_7, 0.4_5_3_1, 0.4_4_3_4, 0.4_4_3_4, 0.4_2_9_7] ) print(f'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2
36
1
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class a ( UpperCAmelCase__ ): UpperCamelCase : Tuple = ['image_processor', 'tokenizer'] UpperCamelCase : Union[str, Any] = 'CLIPImageProcessor' UpperCamelCase : str = ('XLMRobertaTokenizer', 'XLMRobertaTokenizerFast') def __init__( self : Union[str, Any] , lowerCAmelCase : Union[str, Any]=None , lowerCAmelCase : Optional[int]=None , **lowerCAmelCase : List[str] ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[str] =None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , lowerCAmelCase , ) SCREAMING_SNAKE_CASE_: Tuple =kwargs.pop("""feature_extractor""" ) SCREAMING_SNAKE_CASE_: Any =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 : List[Any] , lowerCAmelCase : Optional[Any]=None , lowerCAmelCase : List[Any]=None , lowerCAmelCase : Union[str, Any]=None , **lowerCAmelCase : Optional[Any] ) -> Optional[int]: '''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: SCREAMING_SNAKE_CASE_: Optional[int] =self.tokenizer(lowerCAmelCase , return_tensors=lowerCAmelCase , **lowerCAmelCase ) if images is not None: SCREAMING_SNAKE_CASE_: str =self.image_processor(lowerCAmelCase , return_tensors=lowerCAmelCase , **lowerCAmelCase ) if text is not None and images is not None: SCREAMING_SNAKE_CASE_: Optional[Any] =image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**lowerCAmelCase ) , tensor_type=lowerCAmelCase ) def lowerCamelCase__ ( self : List[Any] , *lowerCAmelCase : Tuple , **lowerCAmelCase : Tuple ) -> List[Any]: '''simple docstring''' return self.tokenizer.batch_decode(*lowerCAmelCase , **lowerCAmelCase ) def lowerCamelCase__ ( self : Dict , *lowerCAmelCase : Dict , **lowerCAmelCase : List[Any] ) -> int: '''simple docstring''' return self.tokenizer.decode(*lowerCAmelCase , **lowerCAmelCase ) @property def lowerCamelCase__ ( self : Union[str, Any] ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[Any] =self.tokenizer.model_input_names SCREAMING_SNAKE_CASE_: int =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
36
"""simple docstring""" def __magic_name__ ( lowercase = 200_0000 ): SCREAMING_SNAKE_CASE_: List[Any] =[0 for i in range(n + 1 )] SCREAMING_SNAKE_CASE_: Union[str, Any] =1 SCREAMING_SNAKE_CASE_: Optional[Any] =1 for i in range(2 , int(n**0.5 ) + 1 ): if primality_list[i] == 0: for j in range(i * i , n + 1 , lowercase ): SCREAMING_SNAKE_CASE_: Optional[int] =1 SCREAMING_SNAKE_CASE_: Dict =0 for i in range(lowercase ): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(f"""{solution() = }""")
36
1
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = """▁""" _UpperCAmelCase = {"""vocab_file""": """sentencepiece.bpe.model"""} _UpperCAmelCase = { """vocab_file""": { """xlm-roberta-base""": """https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model""", """xlm-roberta-large""": """https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model""", """xlm-roberta-large-finetuned-conll02-dutch""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll02-spanish""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll03-english""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll03-german""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model""" ), } } _UpperCAmelCase = { """xlm-roberta-base""": 5_1_2, """xlm-roberta-large""": 5_1_2, """xlm-roberta-large-finetuned-conll02-dutch""": 5_1_2, """xlm-roberta-large-finetuned-conll02-spanish""": 5_1_2, """xlm-roberta-large-finetuned-conll03-english""": 5_1_2, """xlm-roberta-large-finetuned-conll03-german""": 5_1_2, } class a ( UpperCAmelCase__ ): UpperCamelCase : Optional[Any] = VOCAB_FILES_NAMES UpperCamelCase : List[str] = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : List[str] = ['input_ids', 'attention_mask'] def __init__( self : List[Any] , lowerCAmelCase : List[Any] , lowerCAmelCase : Optional[Any]="<s>" , lowerCAmelCase : List[Any]="</s>" , lowerCAmelCase : int="</s>" , lowerCAmelCase : Optional[Any]="<s>" , lowerCAmelCase : Union[str, Any]="<unk>" , lowerCAmelCase : str="<pad>" , lowerCAmelCase : Optional[int]="<mask>" , lowerCAmelCase : Optional[Dict[str, Any]] = None , **lowerCAmelCase : List[str] , ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[int] =AddedToken(lowerCAmelCase , lstrip=lowerCAmelCase , rstrip=lowerCAmelCase ) if isinstance(lowerCAmelCase , lowerCAmelCase ) else mask_token SCREAMING_SNAKE_CASE_: List[Any] ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=lowerCAmelCase , eos_token=lowerCAmelCase , unk_token=lowerCAmelCase , sep_token=lowerCAmelCase , cls_token=lowerCAmelCase , pad_token=lowerCAmelCase , mask_token=lowerCAmelCase , sp_model_kwargs=self.sp_model_kwargs , **lowerCAmelCase , ) SCREAMING_SNAKE_CASE_: Dict =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(lowerCAmelCase ) ) SCREAMING_SNAKE_CASE_: List[Any] =vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token SCREAMING_SNAKE_CASE_: Optional[int] ={"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab SCREAMING_SNAKE_CASE_: Optional[Any] =1 SCREAMING_SNAKE_CASE_: List[str] =len(self.sp_model ) + self.fairseq_offset SCREAMING_SNAKE_CASE_: List[Any] ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : Union[str, Any] ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =self.__dict__.copy() SCREAMING_SNAKE_CASE_: Optional[int] =None SCREAMING_SNAKE_CASE_: Dict =self.sp_model.serialized_model_proto() return state def __setstate__( self : Optional[int] , lowerCAmelCase : Optional[Any] ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[int] =d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): SCREAMING_SNAKE_CASE_: List[str] ={} SCREAMING_SNAKE_CASE_: Union[str, Any] =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def lowerCamelCase__ ( self : Any , lowerCAmelCase : List[int] , lowerCAmelCase : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] SCREAMING_SNAKE_CASE_: List[str] =[self.cls_token_id] SCREAMING_SNAKE_CASE_: Dict =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def lowerCamelCase__ ( self : Dict , lowerCAmelCase : List[int] , lowerCAmelCase : Optional[List[int]] = None , lowerCAmelCase : bool = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowerCAmelCase , token_ids_a=lowerCAmelCase , already_has_special_tokens=lowerCAmelCase ) if token_ids_a is None: return [1] + ([0] * len(lowerCAmelCase )) + [1] return [1] + ([0] * len(lowerCAmelCase )) + [1, 1] + ([0] * len(lowerCAmelCase )) + [1] def lowerCamelCase__ ( self : List[Any] , lowerCAmelCase : List[int] , lowerCAmelCase : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =[self.sep_token_id] SCREAMING_SNAKE_CASE_: List[Any] =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def lowerCamelCase__ ( self : str ) -> Any: '''simple docstring''' return len(self.sp_model ) + self.fairseq_offset + 1 # Add the <mask> token def lowerCamelCase__ ( self : Optional[int] ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[Any] ={self.convert_ids_to_tokens(lowerCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def lowerCamelCase__ ( self : List[str] , lowerCAmelCase : str ) -> List[str]: '''simple docstring''' return self.sp_model.encode(lowerCAmelCase , out_type=lowerCAmelCase ) def lowerCamelCase__ ( self : Optional[int] , lowerCAmelCase : Tuple ) -> Optional[Any]: '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE_: Dict =self.sp_model.PieceToId(lowerCAmelCase ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def lowerCamelCase__ ( self : List[str] , lowerCAmelCase : Any ) -> Optional[int]: '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def lowerCamelCase__ ( self : Dict , lowerCAmelCase : int ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict ="""""".join(lowerCAmelCase ).replace(lowerCAmelCase , """ """ ).strip() return out_string def lowerCamelCase__ ( self : Tuple , lowerCAmelCase : str , lowerCAmelCase : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(lowerCAmelCase ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE_: Any =os.path.join( lowerCAmelCase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCAmelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowerCAmelCase ) elif not os.path.isfile(self.vocab_file ): with open(lowerCAmelCase , """wb""" ) as fi: SCREAMING_SNAKE_CASE_: Union[str, Any] =self.sp_model.serialized_model_proto() fi.write(lowerCAmelCase ) return (out_vocab_file,)
36
"""simple docstring""" import argparse import torch from transformers import BertForMaskedLM if __name__ == "__main__": _UpperCAmelCase = argparse.ArgumentParser( description=( """Extraction some layers of the full BertForMaskedLM or RObertaForMaskedLM for Transfer Learned""" """ Distillation""" ) ) parser.add_argument("""--model_type""", default="""bert""", choices=["""bert"""]) parser.add_argument("""--model_name""", default="""bert-base-uncased""", type=str) parser.add_argument("""--dump_checkpoint""", default="""serialization_dir/tf_bert-base-uncased_0247911.pth""", type=str) parser.add_argument("""--vocab_transform""", action="""store_true""") _UpperCAmelCase = parser.parse_args() if args.model_type == "bert": _UpperCAmelCase = BertForMaskedLM.from_pretrained(args.model_name) _UpperCAmelCase = """bert""" else: raise ValueError("""args.model_type should be \"bert\".""") _UpperCAmelCase = model.state_dict() _UpperCAmelCase = {} for w in ["word_embeddings", "position_embeddings"]: _UpperCAmelCase = state_dict[f"""{prefix}.embeddings.{w}.weight"""] for w in ["weight", "bias"]: _UpperCAmelCase = state_dict[f"""{prefix}.embeddings.LayerNorm.{w}"""] _UpperCAmelCase = 0 for teacher_idx in [0, 2, 4, 7, 9, 1_1]: for w in ["weight", "bias"]: _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.query.{w}""" ] _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.key.{w}""" ] _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.value.{w}""" ] _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.output.dense.{w}""" ] _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.output.LayerNorm.{w}""" ] _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.intermediate.dense.{w}""" ] _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.output.dense.{w}""" ] _UpperCAmelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.output.LayerNorm.{w}""" ] std_idx += 1 _UpperCAmelCase = state_dict["""cls.predictions.decoder.weight"""] _UpperCAmelCase = state_dict["""cls.predictions.bias"""] if args.vocab_transform: for w in ["weight", "bias"]: _UpperCAmelCase = state_dict[f"""cls.predictions.transform.dense.{w}"""] _UpperCAmelCase = state_dict[f"""cls.predictions.transform.LayerNorm.{w}"""] print(f"""N layers selected for distillation: {std_idx}""") print(f"""Number of params transferred for distillation: {len(compressed_sd.keys())}""") print(f"""Save transferred checkpoint to {args.dump_checkpoint}.""") torch.save(compressed_sd, args.dump_checkpoint)
36
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _UpperCAmelCase = { """configuration_graphormer""": ["""GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GraphormerConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ """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 _UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
36
"""simple docstring""" def __magic_name__ ( lowercase , lowercase ): return int((input_a, input_a).count(0 ) == 0 ) def __magic_name__ ( ): assert and_gate(0 , 0 ) == 0 assert and_gate(0 , 1 ) == 0 assert and_gate(1 , 0 ) == 0 assert and_gate(1 , 1 ) == 1 if __name__ == "__main__": test_and_gate() print(and_gate(1, 0)) print(and_gate(0, 0)) print(and_gate(0, 1)) print(and_gate(1, 1))
36
1
"""simple docstring""" from __future__ import annotations def __magic_name__ ( lowercase ): if not nums: raise ValueError("""List is empty""" ) return sum(lowercase ) / len(lowercase ) if __name__ == "__main__": import doctest doctest.testmod()
36
"""simple docstring""" import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() _UpperCAmelCase = logging.get_logger("""transformers.models.speecht5""") def __magic_name__ ( lowercase , lowercase , lowercase ): hf_model.apply_weight_norm() SCREAMING_SNAKE_CASE_: Tuple =checkpoint["""input_conv.weight_g"""] SCREAMING_SNAKE_CASE_: Optional[int] =checkpoint["""input_conv.weight_v"""] SCREAMING_SNAKE_CASE_: Optional[int] =checkpoint["""input_conv.bias"""] for i in range(len(config.upsample_rates ) ): SCREAMING_SNAKE_CASE_: Any =checkpoint[f'''upsamples.{i}.1.weight_g'''] SCREAMING_SNAKE_CASE_: Any =checkpoint[f'''upsamples.{i}.1.weight_v'''] SCREAMING_SNAKE_CASE_: List[str] =checkpoint[f'''upsamples.{i}.1.bias'''] for i in range(len(config.upsample_rates ) * len(config.resblock_kernel_sizes ) ): for j in range(len(config.resblock_dilation_sizes ) ): SCREAMING_SNAKE_CASE_: Dict =checkpoint[f'''blocks.{i}.convs1.{j}.1.weight_g'''] SCREAMING_SNAKE_CASE_: Any =checkpoint[f'''blocks.{i}.convs1.{j}.1.weight_v'''] SCREAMING_SNAKE_CASE_: Union[str, Any] =checkpoint[f'''blocks.{i}.convs1.{j}.1.bias'''] SCREAMING_SNAKE_CASE_: Dict =checkpoint[f'''blocks.{i}.convs2.{j}.1.weight_g'''] SCREAMING_SNAKE_CASE_: Any =checkpoint[f'''blocks.{i}.convs2.{j}.1.weight_v'''] SCREAMING_SNAKE_CASE_: List[Any] =checkpoint[f'''blocks.{i}.convs2.{j}.1.bias'''] SCREAMING_SNAKE_CASE_: Tuple =checkpoint["""output_conv.1.weight_g"""] SCREAMING_SNAKE_CASE_: List[str] =checkpoint["""output_conv.1.weight_v"""] SCREAMING_SNAKE_CASE_: Optional[int] =checkpoint["""output_conv.1.bias"""] hf_model.remove_weight_norm() @torch.no_grad() def __magic_name__ ( lowercase , lowercase , lowercase , lowercase=None , lowercase=None , ): if config_path is not None: SCREAMING_SNAKE_CASE_: List[Any] =SpeechTaHifiGanConfig.from_pretrained(lowercase ) else: SCREAMING_SNAKE_CASE_: Optional[Any] =SpeechTaHifiGanConfig() SCREAMING_SNAKE_CASE_: Union[str, Any] =SpeechTaHifiGan(lowercase ) SCREAMING_SNAKE_CASE_: Any =torch.load(lowercase ) load_weights(orig_checkpoint["""model"""]["""generator"""] , lowercase , lowercase ) SCREAMING_SNAKE_CASE_: List[Any] =np.load(lowercase ) SCREAMING_SNAKE_CASE_: Any =stats[0].reshape(-1 ) SCREAMING_SNAKE_CASE_: str =stats[1].reshape(-1 ) SCREAMING_SNAKE_CASE_: Dict =torch.from_numpy(lowercase ).float() SCREAMING_SNAKE_CASE_: Dict =torch.from_numpy(lowercase ).float() model.save_pretrained(lowercase ) if repo_id: print("""Pushing to the hub...""" ) model.push_to_hub(lowercase ) if __name__ == "__main__": _UpperCAmelCase = argparse.ArgumentParser() parser.add_argument("""--checkpoint_path""", required=True, default=None, type=str, help="""Path to original checkpoint""") parser.add_argument("""--stats_path""", required=True, default=None, type=str, help="""Path to stats.npy file""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--pytorch_dump_folder_path""", required=True, default=None, type=str, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--push_to_hub""", default=None, type=str, help="""Where to upload the converted model on the 🤗 hub.""" ) _UpperCAmelCase = parser.parse_args() convert_hifigan_checkpoint( args.checkpoint_path, args.stats_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
36
1
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { """asapp/sew-tiny-100k""": """https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json""", # See all SEW models at https://huggingface.co/models?filter=sew } class a ( UpperCAmelCase__ ): UpperCamelCase : int = 'sew' def __init__( self : Any , lowerCAmelCase : Tuple=32 , lowerCAmelCase : Any=768 , lowerCAmelCase : str=12 , lowerCAmelCase : str=12 , lowerCAmelCase : List[Any]=3072 , lowerCAmelCase : int=2 , lowerCAmelCase : str="gelu" , lowerCAmelCase : int=0.1 , lowerCAmelCase : Dict=0.1 , lowerCAmelCase : Union[str, Any]=0.1 , lowerCAmelCase : str=0.0 , lowerCAmelCase : str=0.1 , lowerCAmelCase : Optional[Any]=0.1 , lowerCAmelCase : Optional[Any]=0.0_2 , lowerCAmelCase : Optional[Any]=1E-5 , lowerCAmelCase : Dict="group" , lowerCAmelCase : List[str]="gelu" , lowerCAmelCase : Any=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , lowerCAmelCase : str=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , lowerCAmelCase : List[str]=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , lowerCAmelCase : Optional[int]=False , lowerCAmelCase : List[Any]=128 , lowerCAmelCase : int=16 , lowerCAmelCase : List[str]=True , lowerCAmelCase : Optional[Any]=0.0_5 , lowerCAmelCase : Optional[Any]=10 , lowerCAmelCase : Union[str, Any]=2 , lowerCAmelCase : List[Any]=0.0 , lowerCAmelCase : str=10 , lowerCAmelCase : int=0 , lowerCAmelCase : Dict="mean" , lowerCAmelCase : Any=False , lowerCAmelCase : Dict=False , lowerCAmelCase : Optional[Any]=256 , lowerCAmelCase : Dict=0 , lowerCAmelCase : Union[str, Any]=1 , lowerCAmelCase : Tuple=2 , **lowerCAmelCase : Dict , ) -> str: '''simple docstring''' super().__init__(**lowerCAmelCase , pad_token_id=lowerCAmelCase , bos_token_id=lowerCAmelCase , eos_token_id=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Dict =hidden_size SCREAMING_SNAKE_CASE_: Dict =feat_extract_norm SCREAMING_SNAKE_CASE_: Dict =feat_extract_activation SCREAMING_SNAKE_CASE_: Tuple =list(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: str =list(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: str =list(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =conv_bias SCREAMING_SNAKE_CASE_: Optional[Any] =num_conv_pos_embeddings SCREAMING_SNAKE_CASE_: Optional[Any] =num_conv_pos_embedding_groups SCREAMING_SNAKE_CASE_: List[Any] =len(self.conv_dim ) SCREAMING_SNAKE_CASE_: Any =num_hidden_layers SCREAMING_SNAKE_CASE_: int =intermediate_size SCREAMING_SNAKE_CASE_: Tuple =squeeze_factor SCREAMING_SNAKE_CASE_: Dict =hidden_act SCREAMING_SNAKE_CASE_: Tuple =num_attention_heads SCREAMING_SNAKE_CASE_: List[Any] =hidden_dropout SCREAMING_SNAKE_CASE_: int =attention_dropout SCREAMING_SNAKE_CASE_: Dict =activation_dropout SCREAMING_SNAKE_CASE_: List[str] =feat_proj_dropout SCREAMING_SNAKE_CASE_: Dict =final_dropout SCREAMING_SNAKE_CASE_: Optional[Any] =layerdrop SCREAMING_SNAKE_CASE_: Any =layer_norm_eps SCREAMING_SNAKE_CASE_: Optional[Any] =initializer_range SCREAMING_SNAKE_CASE_: int =vocab_size 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)`,""" f'''but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)''' f'''= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 SCREAMING_SNAKE_CASE_: Dict =apply_spec_augment SCREAMING_SNAKE_CASE_: Optional[int] =mask_time_prob SCREAMING_SNAKE_CASE_: Optional[int] =mask_time_length SCREAMING_SNAKE_CASE_: Dict =mask_time_min_masks SCREAMING_SNAKE_CASE_: Dict =mask_feature_prob SCREAMING_SNAKE_CASE_: Tuple =mask_feature_length SCREAMING_SNAKE_CASE_: Tuple =mask_feature_min_masks # ctc loss SCREAMING_SNAKE_CASE_: Union[str, Any] =ctc_loss_reduction SCREAMING_SNAKE_CASE_: List[Any] =ctc_zero_infinity # sequence classification SCREAMING_SNAKE_CASE_: str =use_weighted_layer_sum SCREAMING_SNAKE_CASE_: List[str] =classifier_proj_size @property def lowerCamelCase__ ( self : Optional[int] ) -> Union[str, Any]: '''simple docstring''' return functools.reduce(operator.mul , self.conv_stride , 1 )
36
"""simple docstring""" import argparse import requests import torch from PIL import Image from transformers import ViTMAEConfig, ViTMAEForPreTraining, ViTMAEImageProcessor def __magic_name__ ( lowercase ): if "cls_token" in name: SCREAMING_SNAKE_CASE_: Optional[int] =name.replace("""cls_token""" , """vit.embeddings.cls_token""" ) if "mask_token" in name: SCREAMING_SNAKE_CASE_: Optional[int] =name.replace("""mask_token""" , """decoder.mask_token""" ) if "decoder_pos_embed" in name: SCREAMING_SNAKE_CASE_: int =name.replace("""decoder_pos_embed""" , """decoder.decoder_pos_embed""" ) if "pos_embed" in name and "decoder" not in name: SCREAMING_SNAKE_CASE_: str =name.replace("""pos_embed""" , """vit.embeddings.position_embeddings""" ) if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE_: str =name.replace("""patch_embed.proj""" , """vit.embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: SCREAMING_SNAKE_CASE_: int =name.replace("""patch_embed.norm""" , """vit.embeddings.norm""" ) if "decoder_blocks" in name: SCREAMING_SNAKE_CASE_: List[Any] =name.replace("""decoder_blocks""" , """decoder.decoder_layers""" ) if "blocks" in name: SCREAMING_SNAKE_CASE_: str =name.replace("""blocks""" , """vit.encoder.layer""" ) if "attn.proj" in name: SCREAMING_SNAKE_CASE_: Optional[Any] =name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: SCREAMING_SNAKE_CASE_: Union[str, Any] =name.replace("""attn""" , """attention.self""" ) if "norm1" in name: SCREAMING_SNAKE_CASE_: Optional[Any] =name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: SCREAMING_SNAKE_CASE_: int =name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE_: int =name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE_: Dict =name.replace("""mlp.fc2""" , """output.dense""" ) if "decoder_embed" in name: SCREAMING_SNAKE_CASE_: List[str] =name.replace("""decoder_embed""" , """decoder.decoder_embed""" ) if "decoder_norm" in name: SCREAMING_SNAKE_CASE_: Tuple =name.replace("""decoder_norm""" , """decoder.decoder_norm""" ) if "decoder_pred" in name: SCREAMING_SNAKE_CASE_: Any =name.replace("""decoder_pred""" , """decoder.decoder_pred""" ) if "norm.weight" in name and "decoder" not in name: SCREAMING_SNAKE_CASE_: List[str] =name.replace("""norm.weight""" , """vit.layernorm.weight""" ) if "norm.bias" in name and "decoder" not in name: SCREAMING_SNAKE_CASE_: List[str] =name.replace("""norm.bias""" , """vit.layernorm.bias""" ) return name def __magic_name__ ( lowercase , lowercase ): for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE_: Optional[int] =orig_state_dict.pop(lowercase ) if "qkv" in key: SCREAMING_SNAKE_CASE_: Dict =key.split(""".""" ) SCREAMING_SNAKE_CASE_: Optional[Any] =int(key_split[1] ) if "decoder_blocks" in key: SCREAMING_SNAKE_CASE_: int =config.decoder_hidden_size SCREAMING_SNAKE_CASE_: Optional[int] ="""decoder.decoder_layers.""" if "weight" in key: SCREAMING_SNAKE_CASE_: Dict =val[:dim, :] SCREAMING_SNAKE_CASE_: Tuple =val[dim : dim * 2, :] SCREAMING_SNAKE_CASE_: str =val[-dim:, :] elif "bias" in key: SCREAMING_SNAKE_CASE_: List[Any] =val[:dim] SCREAMING_SNAKE_CASE_: Tuple =val[dim : dim * 2] SCREAMING_SNAKE_CASE_: List[Any] =val[-dim:] else: SCREAMING_SNAKE_CASE_: Any =config.hidden_size SCREAMING_SNAKE_CASE_: Union[str, Any] ="""vit.encoder.layer.""" if "weight" in key: SCREAMING_SNAKE_CASE_: Optional[Any] =val[:dim, :] SCREAMING_SNAKE_CASE_: Optional[Any] =val[dim : dim * 2, :] SCREAMING_SNAKE_CASE_: Dict =val[-dim:, :] elif "bias" in key: SCREAMING_SNAKE_CASE_: Optional[Any] =val[:dim] SCREAMING_SNAKE_CASE_: Any =val[dim : dim * 2] SCREAMING_SNAKE_CASE_: Optional[Any] =val[-dim:] else: SCREAMING_SNAKE_CASE_: Tuple =val return orig_state_dict def __magic_name__ ( lowercase , lowercase ): SCREAMING_SNAKE_CASE_: Dict =ViTMAEConfig() if "large" in checkpoint_url: SCREAMING_SNAKE_CASE_: List[Any] =1024 SCREAMING_SNAKE_CASE_: Dict =4096 SCREAMING_SNAKE_CASE_: Tuple =24 SCREAMING_SNAKE_CASE_: int =16 elif "huge" in checkpoint_url: SCREAMING_SNAKE_CASE_: Union[str, Any] =14 SCREAMING_SNAKE_CASE_: Any =1280 SCREAMING_SNAKE_CASE_: Dict =5120 SCREAMING_SNAKE_CASE_: Optional[int] =32 SCREAMING_SNAKE_CASE_: Optional[Any] =16 SCREAMING_SNAKE_CASE_: Tuple =ViTMAEForPreTraining(lowercase ) SCREAMING_SNAKE_CASE_: Optional[int] =torch.hub.load_state_dict_from_url(lowercase , map_location="""cpu""" )["""model"""] SCREAMING_SNAKE_CASE_: Optional[Any] =ViTMAEImageProcessor(size=config.image_size ) SCREAMING_SNAKE_CASE_: str =convert_state_dict(lowercase , lowercase ) model.load_state_dict(lowercase ) model.eval() SCREAMING_SNAKE_CASE_: Tuple ="""https://user-images.githubusercontent.com/11435359/147738734-196fd92f-9260-48d5-ba7e-bf103d29364d.jpg""" SCREAMING_SNAKE_CASE_: List[Any] =Image.open(requests.get(lowercase , stream=lowercase ).raw ) SCREAMING_SNAKE_CASE_: int =ViTMAEImageProcessor(size=config.image_size ) SCREAMING_SNAKE_CASE_: int =image_processor(images=lowercase , return_tensors="""pt""" ) # forward pass torch.manual_seed(2 ) SCREAMING_SNAKE_CASE_: Optional[Any] =model(**lowercase ) SCREAMING_SNAKE_CASE_: Optional[int] =outputs.logits if "large" in checkpoint_url: SCREAMING_SNAKE_CASE_: Dict =torch.tensor( [[-0.7_309, -0.7_128, -1.0_169], [-1.0_161, -0.9_058, -1.1_878], [-1.0_478, -0.9_411, -1.1_911]] ) elif "huge" in checkpoint_url: SCREAMING_SNAKE_CASE_: Tuple =torch.tensor( [[-1.1_599, -0.9_199, -1.2_221], [-1.1_952, -0.9_269, -1.2_307], [-1.2_143, -0.9_337, -1.2_262]] ) else: SCREAMING_SNAKE_CASE_: Any =torch.tensor( [[-0.9_192, -0.8_481, -1.1_259], [-1.1_349, -1.0_034, -1.2_599], [-1.1_757, -1.0_429, -1.2_726]] ) # verify logits assert torch.allclose(logits[0, :3, :3] , lowercase , atol=1e-4 ) print(f'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowercase ) if __name__ == "__main__": _UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--checkpoint_url""", default="""https://dl.fbaipublicfiles.com/mae/visualize/mae_visualize_vit_base.pth""", type=str, help="""URL of the checkpoint you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) _UpperCAmelCase = parser.parse_args() convert_vit_mae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
36
1
"""simple docstring""" def __magic_name__ ( lowercase = 200_0000 ): SCREAMING_SNAKE_CASE_: List[Any] =[0 for i in range(n + 1 )] SCREAMING_SNAKE_CASE_: Union[str, Any] =1 SCREAMING_SNAKE_CASE_: Optional[Any] =1 for i in range(2 , int(n**0.5 ) + 1 ): if primality_list[i] == 0: for j in range(i * i , n + 1 , lowercase ): SCREAMING_SNAKE_CASE_: Optional[int] =1 SCREAMING_SNAKE_CASE_: Dict =0 for i in range(lowercase ): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(f"""{solution() = }""")
36
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _UpperCAmelCase = { """configuration_xlm""": ["""XLM_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XLMConfig""", """XLMOnnxConfig"""], """tokenization_xlm""": ["""XLMTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ """XLM_PRETRAINED_MODEL_ARCHIVE_LIST""", """XLMForMultipleChoice""", """XLMForQuestionAnswering""", """XLMForQuestionAnsweringSimple""", """XLMForSequenceClassification""", """XLMForTokenClassification""", """XLMModel""", """XLMPreTrainedModel""", """XLMWithLMHeadModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ """TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFXLMForMultipleChoice""", """TFXLMForQuestionAnsweringSimple""", """TFXLMForSequenceClassification""", """TFXLMForTokenClassification""", """TFXLMMainLayer""", """TFXLMModel""", """TFXLMPreTrainedModel""", """TFXLMWithLMHeadModel""", ] if TYPE_CHECKING: from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig from .tokenization_xlm import XLMTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm import ( XLM_PRETRAINED_MODEL_ARCHIVE_LIST, XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMPreTrainedModel, XLMWithLMHeadModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm import ( TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMForMultipleChoice, TFXLMForQuestionAnsweringSimple, TFXLMForSequenceClassification, TFXLMForTokenClassification, TFXLMMainLayer, TFXLMModel, TFXLMPreTrainedModel, TFXLMWithLMHeadModel, ) else: import sys _UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
36
1
"""simple docstring""" def __magic_name__ ( lowercase ): # noqa: E741 SCREAMING_SNAKE_CASE_: Any =len(lowercase ) SCREAMING_SNAKE_CASE_: List[Any] =0 SCREAMING_SNAKE_CASE_: Optional[Any] =[0] * n SCREAMING_SNAKE_CASE_: Union[str, Any] =[False] * n SCREAMING_SNAKE_CASE_: Union[str, Any] =[False] * n def dfs(lowercase , lowercase , lowercase , lowercase ): if parent == root: out_edge_count += 1 SCREAMING_SNAKE_CASE_: List[str] =True SCREAMING_SNAKE_CASE_: str =at for to in l[at]: if to == parent: pass elif not visited[to]: SCREAMING_SNAKE_CASE_: Optional[int] =dfs(lowercase , lowercase , lowercase , lowercase ) SCREAMING_SNAKE_CASE_: List[str] =min(low[at] , low[to] ) # AP found via bridge if at < low[to]: SCREAMING_SNAKE_CASE_: Any =True # AP found via cycle if at == low[to]: SCREAMING_SNAKE_CASE_: Dict =True else: SCREAMING_SNAKE_CASE_: Any =min(low[at] , lowercase ) return out_edge_count for i in range(lowercase ): if not visited[i]: SCREAMING_SNAKE_CASE_: Optional[int] =0 SCREAMING_SNAKE_CASE_: Tuple =dfs(lowercase , lowercase , -1 , lowercase ) SCREAMING_SNAKE_CASE_: Any =out_edge_count > 1 for x in range(len(lowercase ) ): if is_art[x] is True: print(lowercase ) # Adjacency list of graph _UpperCAmelCase = { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 5], 3: [2, 4], 4: [3], 5: [2, 6, 8], 6: [5, 7], 7: [6, 8], 8: [5, 7], } compute_ap(data)
36
"""simple docstring""" def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: int =False while is_sorted is False: # Until all the indices are traversed keep looping SCREAMING_SNAKE_CASE_: Tuple =True for i in range(0 , len(lowercase ) - 1 , 2 ): # iterating over all even indices if input_list[i] > input_list[i + 1]: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[int] =input_list[i + 1], input_list[i] # swapping if elements not in order SCREAMING_SNAKE_CASE_: Tuple =False for i in range(1 , len(lowercase ) - 1 , 2 ): # iterating over all odd indices if input_list[i] > input_list[i + 1]: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: str =input_list[i + 1], input_list[i] # swapping if elements not in order SCREAMING_SNAKE_CASE_: str =False return input_list if __name__ == "__main__": print("""Enter list to be sorted""") _UpperCAmelCase = [int(x) for x in input().split()] # inputing elements of the list in one line _UpperCAmelCase = odd_even_sort(input_list) print("""The sorted list is""") print(sorted_list)
36
1
"""simple docstring""" import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, ByTaTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): _UpperCAmelCase = """pt""" elif is_tf_available(): _UpperCAmelCase = """tf""" else: _UpperCAmelCase = """jax""" class a ( UpperCAmelCase__ , unittest.TestCase ): UpperCamelCase : Optional[int] = ByTaTokenizer UpperCamelCase : Any = False def lowerCamelCase__ ( self : Any ) -> int: '''simple docstring''' super().setUp() SCREAMING_SNAKE_CASE_: Optional[Any] =ByTaTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def lowerCamelCase__ ( self : Optional[Any] ) -> Dict: '''simple docstring''' return ByTaTokenizer.from_pretrained("""google/byt5-small""" ) def lowerCamelCase__ ( self : List[Any] , **lowerCAmelCase : Any ) -> ByTaTokenizer: '''simple docstring''' return self.tokenizer_class.from_pretrained(self.tmpdirname , **lowerCAmelCase ) def lowerCamelCase__ ( self : str , lowerCAmelCase : List[Any] , lowerCAmelCase : Any=False , lowerCAmelCase : Optional[Any]=20 , lowerCAmelCase : Any=5 ) -> Tuple[str, list]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[int] =[] for i in range(len(lowerCAmelCase ) ): try: SCREAMING_SNAKE_CASE_: List[str] =tokenizer.decode([i] , clean_up_tokenization_spaces=lowerCAmelCase ) except UnicodeDecodeError: pass toks.append((i, tok) ) SCREAMING_SNAKE_CASE_: Dict =list(filter(lambda lowerCAmelCase : re.match(R"""^[ a-zA-Z]+$""" , t[1] ) , lowerCAmelCase ) ) SCREAMING_SNAKE_CASE_: List[Any] =list(filter(lambda lowerCAmelCase : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=lowerCAmelCase ) , lowerCAmelCase ) ) if max_length is not None and len(lowerCAmelCase ) > max_length: SCREAMING_SNAKE_CASE_: Union[str, Any] =toks[:max_length] if min_length is not None and len(lowerCAmelCase ) < min_length and len(lowerCAmelCase ) > 0: while len(lowerCAmelCase ) < min_length: SCREAMING_SNAKE_CASE_: Dict =toks + toks # toks_str = [t[1] for t in toks] SCREAMING_SNAKE_CASE_: Tuple =[t[0] for t in toks] # Ensure consistency SCREAMING_SNAKE_CASE_: Dict =tokenizer.decode(lowerCAmelCase , clean_up_tokenization_spaces=lowerCAmelCase ) if " " not in output_txt and len(lowerCAmelCase ) > 1: SCREAMING_SNAKE_CASE_: str =( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=lowerCAmelCase ) + """ """ + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=lowerCAmelCase ) ) if with_prefix_space: SCREAMING_SNAKE_CASE_: Tuple =""" """ + output_txt SCREAMING_SNAKE_CASE_: Dict =tokenizer.encode(lowerCAmelCase , add_special_tokens=lowerCAmelCase ) return output_txt, output_ids def lowerCamelCase__ ( self : Optional[int] ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =self.ta_base_tokenizer SCREAMING_SNAKE_CASE_: Optional[Any] =tokenizer(["""hi</s>""", """I went to the gym</s>""", """</s>"""] ) SCREAMING_SNAKE_CASE_: int =tokenizer(["""hi""", """I went to the gym""", """"""] ) self.assertListEqual(batch_with_eos_added["""input_ids"""] , batch_without_eos_added["""input_ids"""] ) def lowerCamelCase__ ( self : Any ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Union[str, Any] =self.ta_base_tokenizer SCREAMING_SNAKE_CASE_: List[Any] ="""Unicode €.""" SCREAMING_SNAKE_CASE_: Any =tokenizer(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =[88, 113, 108, 102, 114, 103, 104, 35, 229, 133, 175, 49, 1] self.assertEqual(encoded["""input_ids"""] , lowerCAmelCase ) # decoding SCREAMING_SNAKE_CASE_: Optional[Any] =tokenizer.decode(lowerCAmelCase ) self.assertEqual(lowerCAmelCase , """Unicode €.</s>""" ) SCREAMING_SNAKE_CASE_: Optional[Any] =tokenizer("""e è é ê ë""" ) SCREAMING_SNAKE_CASE_: str =[104, 35, 198, 171, 35, 198, 172, 35, 198, 173, 35, 198, 174, 1] self.assertEqual(encoded["""input_ids"""] , lowerCAmelCase ) # decoding SCREAMING_SNAKE_CASE_: List[Any] =tokenizer.decode(lowerCAmelCase ) self.assertEqual(lowerCAmelCase , """e è é ê ë</s>""" ) # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode("""e è é ê ë""" ) ) , """e è é ê ë</s>""" ) def lowerCamelCase__ ( self : Tuple ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[Any] =self.ta_base_tokenizer SCREAMING_SNAKE_CASE_: int =["""A long paragraph for summarization.""", """Another paragraph for summarization."""] # fmt: off SCREAMING_SNAKE_CASE_: str =[68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 1, 0] # fmt: on SCREAMING_SNAKE_CASE_: List[str] =tokenizer(lowerCAmelCase , padding=lowerCAmelCase , return_tensors=lowerCAmelCase ) self.assertIsInstance(lowerCAmelCase , lowerCAmelCase ) if FRAMEWORK != "jax": SCREAMING_SNAKE_CASE_: Any =list(batch.input_ids.numpy()[0] ) else: SCREAMING_SNAKE_CASE_: Dict =list(batch.input_ids.tolist()[0] ) self.assertListEqual(lowerCAmelCase , lowerCAmelCase ) self.assertEqual((2, 37) , batch.input_ids.shape ) self.assertEqual((2, 37) , batch.attention_mask.shape ) def lowerCamelCase__ ( self : int ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =self.ta_base_tokenizer SCREAMING_SNAKE_CASE_: List[Any] =["""A long paragraph for summarization.""", """Another paragraph for summarization."""] SCREAMING_SNAKE_CASE_: List[Any] =tokenizer(lowerCAmelCase , padding=lowerCAmelCase , return_tensors=lowerCAmelCase ) # check if input_ids are returned and no decoder_input_ids self.assertIn("""input_ids""" , lowerCAmelCase ) self.assertIn("""attention_mask""" , lowerCAmelCase ) self.assertNotIn("""decoder_input_ids""" , lowerCAmelCase ) self.assertNotIn("""decoder_attention_mask""" , lowerCAmelCase ) def lowerCamelCase__ ( self : Optional[int] ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[Any] =self.ta_base_tokenizer SCREAMING_SNAKE_CASE_: str =[ """Summary of the text.""", """Another summary.""", ] SCREAMING_SNAKE_CASE_: Any =tokenizer( text_target=lowerCAmelCase , max_length=32 , padding="""max_length""" , truncation=lowerCAmelCase , return_tensors=lowerCAmelCase ) self.assertEqual(32 , targets["""input_ids"""].shape[1] ) def lowerCamelCase__ ( self : Any ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE_: str =self.ta_base_tokenizer SCREAMING_SNAKE_CASE_: Optional[int] =["""A long paragraph for summarization. </s>"""] SCREAMING_SNAKE_CASE_: List[str] =["""Summary of the text. </s>"""] # fmt: off SCREAMING_SNAKE_CASE_: Tuple =[68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 35, 1] SCREAMING_SNAKE_CASE_: List[str] =[86, 120, 112, 112, 100, 117, 124, 35, 114, 105, 35, 119, 107, 104, 35, 119, 104, 123, 119, 49, 35, 1] # fmt: on SCREAMING_SNAKE_CASE_: List[Any] =tokenizer(lowerCAmelCase , text_target=lowerCAmelCase ) self.assertEqual(lowerCAmelCase , batch["""input_ids"""][0] ) self.assertEqual(lowerCAmelCase , batch["""labels"""][0] ) def lowerCamelCase__ ( self : Tuple ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[int] =self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): self.assertNotEqual(tokenizer.model_max_length , 42 ) # Now let's start the test SCREAMING_SNAKE_CASE_: Tuple =self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): # Isolate this from the other tests because we save additional tokens/etc SCREAMING_SNAKE_CASE_: Any =tempfile.mkdtemp() SCREAMING_SNAKE_CASE_: str =""" He is very happy, UNwant\u00E9d,running""" SCREAMING_SNAKE_CASE_: Any =tokenizer.encode(lowerCAmelCase , add_special_tokens=lowerCAmelCase ) tokenizer.save_pretrained(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Any =tokenizer.__class__.from_pretrained(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Any =after_tokenizer.encode(lowerCAmelCase , add_special_tokens=lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , lowerCAmelCase ) shutil.rmtree(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =self.get_tokenizers(model_max_length=42 ) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): # Isolate this from the other tests because we save additional tokens/etc SCREAMING_SNAKE_CASE_: Any =tempfile.mkdtemp() SCREAMING_SNAKE_CASE_: Dict =""" He is very happy, UNwant\u00E9d,running""" tokenizer.add_tokens(["""bim""", """bambam"""] ) SCREAMING_SNAKE_CASE_: str =tokenizer.additional_special_tokens additional_special_tokens.append("""new_additional_special_token""" ) tokenizer.add_special_tokens({"""additional_special_tokens""": additional_special_tokens} ) SCREAMING_SNAKE_CASE_: str =tokenizer.encode(lowerCAmelCase , add_special_tokens=lowerCAmelCase ) tokenizer.save_pretrained(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =tokenizer.__class__.from_pretrained(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Union[str, Any] =after_tokenizer.encode(lowerCAmelCase , add_special_tokens=lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , lowerCAmelCase ) self.assertIn("""new_additional_special_token""" , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) SCREAMING_SNAKE_CASE_: str =tokenizer.__class__.from_pretrained(lowerCAmelCase , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(lowerCAmelCase ) def lowerCamelCase__ ( self : Dict ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Union[str, Any] =[] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(lowerCAmelCase ) with open(os.path.join(lowerCAmelCase , """special_tokens_map.json""" ) , encoding="""utf-8""" ) as json_file: SCREAMING_SNAKE_CASE_: Tuple =json.load(lowerCAmelCase ) with open(os.path.join(lowerCAmelCase , """tokenizer_config.json""" ) , encoding="""utf-8""" ) as json_file: SCREAMING_SNAKE_CASE_: List[Any] =json.load(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =[f'''<extra_id_{i}>''' for i in range(125 )] SCREAMING_SNAKE_CASE_: Optional[Any] =added_tokens_extra_ids + [ """an_additional_special_token""" ] SCREAMING_SNAKE_CASE_: List[str] =added_tokens_extra_ids + [ """an_additional_special_token""" ] with open(os.path.join(lowerCAmelCase , """special_tokens_map.json""" ) , """w""" , encoding="""utf-8""" ) as outfile: json.dump(lowerCAmelCase , lowerCAmelCase ) with open(os.path.join(lowerCAmelCase , """tokenizer_config.json""" ) , """w""" , encoding="""utf-8""" ) as outfile: json.dump(lowerCAmelCase , lowerCAmelCase ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files SCREAMING_SNAKE_CASE_: Union[str, Any] =tokenizer_class.from_pretrained( lowerCAmelCase , ) self.assertIn( """an_additional_special_token""" , tokenizer_without_change_in_init.additional_special_tokens ) # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( ["""an_additional_special_token"""] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(["""an_additional_special_token"""] ) ) , ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained SCREAMING_SNAKE_CASE_: Optional[int] =added_tokens_extra_ids + [AddedToken("""a_new_additional_special_token""" , lstrip=lowerCAmelCase )] SCREAMING_SNAKE_CASE_: List[Any] =tokenizer_class.from_pretrained( lowerCAmelCase , additional_special_tokens=lowerCAmelCase , ) self.assertIn("""a_new_additional_special_token""" , tokenizer.additional_special_tokens ) self.assertEqual( ["""a_new_additional_special_token"""] , tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(["""a_new_additional_special_token"""] ) ) , ) def lowerCamelCase__ ( self : int ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =[] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple =tokenizer_class.from_pretrained(lowerCAmelCase ) self.assertTrue(tokenizer.decode([255] ) == """""" ) def lowerCamelCase__ ( self : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' pass def lowerCamelCase__ ( self : List[str] ) -> Tuple: '''simple docstring''' pass def lowerCamelCase__ ( self : Union[str, Any] ) -> List[str]: '''simple docstring''' pass def lowerCamelCase__ ( self : Any ) -> Dict: '''simple docstring''' pass def lowerCamelCase__ ( self : List[str] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[int] =self.get_tokenizers(fast=lowerCAmelCase , do_lower_case=lowerCAmelCase ) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): SCREAMING_SNAKE_CASE_: List[Any] =["""t""", """h""", """i""", """s""", """ """, """i""", """s""", """ """, """a""", """ """, """t""", """e""", """x""", """t""", """</s>"""] SCREAMING_SNAKE_CASE_: str =tokenizer.convert_tokens_to_string(lowerCAmelCase ) self.assertIsInstance(lowerCAmelCase , lowerCAmelCase ) def lowerCamelCase__ ( self : Dict ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE_: str =self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): SCREAMING_SNAKE_CASE_: str =[ """bos_token""", """eos_token""", """unk_token""", """sep_token""", """pad_token""", """cls_token""", """mask_token""", ] SCREAMING_SNAKE_CASE_: List[Any] =0 SCREAMING_SNAKE_CASE_: Optional[int] =tokenizer.convert_ids_to_tokens( lowerCAmelCase , skip_special_tokens=lowerCAmelCase ) for attr in attributes_list: setattr(lowerCAmelCase , attr + """_id""" , lowerCAmelCase ) self.assertEqual(getattr(lowerCAmelCase , lowerCAmelCase ) , lowerCAmelCase ) self.assertEqual(getattr(lowerCAmelCase , attr + """_id""" ) , lowerCAmelCase ) setattr(lowerCAmelCase , attr + """_id""" , lowerCAmelCase ) self.assertEqual(getattr(lowerCAmelCase , lowerCAmelCase ) , lowerCAmelCase ) self.assertEqual(getattr(lowerCAmelCase , attr + """_id""" ) , lowerCAmelCase ) setattr(lowerCAmelCase , """additional_special_tokens_ids""" , [] ) self.assertListEqual(getattr(lowerCAmelCase , """additional_special_tokens""" ) , [] ) self.assertListEqual(getattr(lowerCAmelCase , """additional_special_tokens_ids""" ) , [] ) setattr(lowerCAmelCase , """additional_special_tokens_ids""" , [token_id_to_test_setters] ) self.assertListEqual(getattr(lowerCAmelCase , """additional_special_tokens""" ) , [token_to_test_setters] ) self.assertListEqual(getattr(lowerCAmelCase , """additional_special_tokens_ids""" ) , [token_id_to_test_setters] )
36
"""simple docstring""" def __magic_name__ ( lowercase ): return str(lowercase ) == str(lowercase )[::-1] def __magic_name__ ( lowercase ): return int(lowercase ) + int(str(lowercase )[::-1] ) def __magic_name__ ( lowercase = 1_0000 ): SCREAMING_SNAKE_CASE_: List[str] =[] for num in range(1 , lowercase ): SCREAMING_SNAKE_CASE_: List[Any] =0 SCREAMING_SNAKE_CASE_: int =num while iterations < 50: SCREAMING_SNAKE_CASE_: Optional[Any] =sum_reverse(lowercase ) iterations += 1 if is_palindrome(lowercase ): break else: lychrel_nums.append(lowercase ) return len(lowercase ) if __name__ == "__main__": print(f"""{solution() = }""")
36
1
"""simple docstring""" from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class a ( UpperCAmelCase__ ): UpperCamelCase : str = CustomTokenizer pass
36
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available from ...utils import OptionalDependencyNotAvailable _UpperCAmelCase = {"""configuration_dpt""": ["""DPT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """DPTConfig"""]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = ["""DPTFeatureExtractor"""] _UpperCAmelCase = ["""DPTImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ """DPT_PRETRAINED_MODEL_ARCHIVE_LIST""", """DPTForDepthEstimation""", """DPTForSemanticSegmentation""", """DPTModel""", """DPTPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_dpt import DPTFeatureExtractor from .image_processing_dpt import DPTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dpt import ( DPT_PRETRAINED_MODEL_ARCHIVE_LIST, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel, DPTPreTrainedModel, ) else: import sys _UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
36
1
"""simple docstring""" from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class a : def __init__( self : int , lowerCAmelCase : int , lowerCAmelCase : Any=2 , lowerCAmelCase : Union[str, Any]=3 , lowerCAmelCase : List[Any]=4 , lowerCAmelCase : Tuple=2 , lowerCAmelCase : Union[str, Any]=7 , lowerCAmelCase : List[Any]=True , lowerCAmelCase : int=True , lowerCAmelCase : Any=True , lowerCAmelCase : Dict=True , lowerCAmelCase : Optional[Any]=99 , lowerCAmelCase : int=36 , lowerCAmelCase : List[Any]=2 , lowerCAmelCase : List[str]=4 , lowerCAmelCase : int=37 , lowerCAmelCase : Union[str, Any]="gelu" , lowerCAmelCase : Dict=0.1 , lowerCAmelCase : int=0.1 , lowerCAmelCase : Optional[int]=512 , lowerCAmelCase : int=16 , lowerCAmelCase : List[Any]=2 , lowerCAmelCase : List[str]=0.0_2 , lowerCAmelCase : Optional[int]=6 , lowerCAmelCase : str=6 , lowerCAmelCase : str=3 , lowerCAmelCase : Any=4 , lowerCAmelCase : int=None , lowerCAmelCase : Optional[int]=1000 , ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: int =parent SCREAMING_SNAKE_CASE_: Dict =batch_size SCREAMING_SNAKE_CASE_: Optional[Any] =num_channels SCREAMING_SNAKE_CASE_: int =image_size SCREAMING_SNAKE_CASE_: int =patch_size SCREAMING_SNAKE_CASE_: Union[str, Any] =is_training SCREAMING_SNAKE_CASE_: List[str] =use_input_mask SCREAMING_SNAKE_CASE_: Tuple =use_token_type_ids SCREAMING_SNAKE_CASE_: List[Any] =use_labels SCREAMING_SNAKE_CASE_: List[Any] =vocab_size SCREAMING_SNAKE_CASE_: Any =hidden_size SCREAMING_SNAKE_CASE_: int =num_hidden_layers SCREAMING_SNAKE_CASE_: Union[str, Any] =num_attention_heads SCREAMING_SNAKE_CASE_: Dict =intermediate_size SCREAMING_SNAKE_CASE_: Tuple =hidden_act SCREAMING_SNAKE_CASE_: Any =hidden_dropout_prob SCREAMING_SNAKE_CASE_: Optional[int] =attention_probs_dropout_prob SCREAMING_SNAKE_CASE_: List[str] =max_position_embeddings SCREAMING_SNAKE_CASE_: int =type_vocab_size SCREAMING_SNAKE_CASE_: Union[str, Any] =type_sequence_label_size SCREAMING_SNAKE_CASE_: Optional[Any] =initializer_range SCREAMING_SNAKE_CASE_: Tuple =coordinate_size SCREAMING_SNAKE_CASE_: int =shape_size SCREAMING_SNAKE_CASE_: int =num_labels SCREAMING_SNAKE_CASE_: Optional[int] =num_choices SCREAMING_SNAKE_CASE_: Union[str, Any] =scope SCREAMING_SNAKE_CASE_: List[str] =range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) SCREAMING_SNAKE_CASE_: Tuple =text_seq_length SCREAMING_SNAKE_CASE_: Optional[Any] =(image_size // patch_size) ** 2 + 1 SCREAMING_SNAKE_CASE_: List[str] =self.text_seq_length + self.image_seq_length def lowerCamelCase__ ( self : int ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[Any] =ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE_: Any =ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) SCREAMING_SNAKE_CASE_: Optional[int] =bbox.numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: SCREAMING_SNAKE_CASE_: Dict =bbox[i, j, 3] SCREAMING_SNAKE_CASE_: Dict =bbox[i, j, 1] SCREAMING_SNAKE_CASE_: str =tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: SCREAMING_SNAKE_CASE_: List[Any] =bbox[i, j, 2] SCREAMING_SNAKE_CASE_: Optional[int] =bbox[i, j, 0] SCREAMING_SNAKE_CASE_: List[str] =tmp_coordinate SCREAMING_SNAKE_CASE_: str =tf.constant(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[Any] =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_: Tuple =None if self.use_input_mask: SCREAMING_SNAKE_CASE_: Optional[Any] =random_attention_mask([self.batch_size, self.text_seq_length] ) SCREAMING_SNAKE_CASE_: Dict =None if self.use_token_type_ids: SCREAMING_SNAKE_CASE_: str =ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE_: str =None SCREAMING_SNAKE_CASE_: Optional[int] =None if self.use_labels: SCREAMING_SNAKE_CASE_: Dict =ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE_: List[Any] =ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE_: List[str] =LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def lowerCamelCase__ ( self : Any , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Optional[int] , lowerCAmelCase : Any , lowerCAmelCase : Optional[int] , lowerCAmelCase : Any , lowerCAmelCase : Union[str, Any] ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[Any] =TFLayoutLMvaModel(config=lowerCAmelCase ) # text + image SCREAMING_SNAKE_CASE_: int =model(lowerCAmelCase , pixel_values=lowerCAmelCase , training=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Dict =model( lowerCAmelCase , bbox=lowerCAmelCase , pixel_values=lowerCAmelCase , attention_mask=lowerCAmelCase , token_type_ids=lowerCAmelCase , training=lowerCAmelCase , ) SCREAMING_SNAKE_CASE_: Optional[int] =model(lowerCAmelCase , bbox=lowerCAmelCase , pixel_values=lowerCAmelCase , training=lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only SCREAMING_SNAKE_CASE_: Tuple =model(lowerCAmelCase , training=lowerCAmelCase ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only SCREAMING_SNAKE_CASE_: Union[str, Any] =model({"""pixel_values""": pixel_values} , training=lowerCAmelCase ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def lowerCamelCase__ ( self : Optional[int] , lowerCAmelCase : str , lowerCAmelCase : Optional[int] , lowerCAmelCase : int , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : str , lowerCAmelCase : Dict , lowerCAmelCase : Tuple ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[int] =self.num_labels SCREAMING_SNAKE_CASE_: Tuple =TFLayoutLMvaForSequenceClassification(config=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[Any] =model( lowerCAmelCase , bbox=lowerCAmelCase , pixel_values=lowerCAmelCase , attention_mask=lowerCAmelCase , token_type_ids=lowerCAmelCase , labels=lowerCAmelCase , training=lowerCAmelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase__ ( self : List[Any] , lowerCAmelCase : Tuple , lowerCAmelCase : List[Any] , lowerCAmelCase : List[str] , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Any , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : str ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =self.num_labels SCREAMING_SNAKE_CASE_: Optional[int] =TFLayoutLMvaForTokenClassification(config=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =model( lowerCAmelCase , bbox=lowerCAmelCase , pixel_values=lowerCAmelCase , attention_mask=lowerCAmelCase , token_type_ids=lowerCAmelCase , labels=lowerCAmelCase , training=lowerCAmelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def lowerCamelCase__ ( self : Any , lowerCAmelCase : Tuple , lowerCAmelCase : Any , lowerCAmelCase : int , lowerCAmelCase : Any , lowerCAmelCase : List[Any] , lowerCAmelCase : Dict , lowerCAmelCase : Optional[Any] ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =2 SCREAMING_SNAKE_CASE_: int =TFLayoutLMvaForQuestionAnswering(config=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: int =model( lowerCAmelCase , bbox=lowerCAmelCase , pixel_values=lowerCAmelCase , attention_mask=lowerCAmelCase , token_type_ids=lowerCAmelCase , start_positions=lowerCAmelCase , end_positions=lowerCAmelCase , training=lowerCAmelCase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCamelCase__ ( self : str ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: str =self.prepare_config_and_inputs() ((SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_)): Optional[int] =config_and_inputs SCREAMING_SNAKE_CASE_: int ={ """input_ids""": input_ids, """bbox""": bbox, """pixel_values""": pixel_values, """token_type_ids""": token_type_ids, """attention_mask""": input_mask, } return config, inputs_dict @require_tf class a ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): UpperCamelCase : Optional[Any] = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) UpperCamelCase : List[Any] = ( {'document-question-answering': TFLayoutLMvaForQuestionAnswering, 'feature-extraction': TFLayoutLMvaModel} if is_tf_available() else {} ) UpperCamelCase : str = False UpperCamelCase : Union[str, Any] = False UpperCamelCase : Dict = False def lowerCamelCase__ ( self : List[Any] , lowerCAmelCase : str , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Any ) -> List[Any]: '''simple docstring''' return True def lowerCamelCase__ ( self : Tuple , lowerCAmelCase : int , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Optional[int]=False ) -> dict: '''simple docstring''' SCREAMING_SNAKE_CASE_: Union[str, Any] =copy.deepcopy(lowerCAmelCase ) if model_class in get_values(lowerCAmelCase ): SCREAMING_SNAKE_CASE_: Tuple ={ k: tf.tile(tf.expand_dims(lowerCAmelCase , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(lowerCAmelCase , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(lowerCAmelCase ): SCREAMING_SNAKE_CASE_: Union[str, Any] =tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(lowerCAmelCase ): SCREAMING_SNAKE_CASE_: List[Any] =tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) SCREAMING_SNAKE_CASE_: Dict =tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(lowerCAmelCase ): SCREAMING_SNAKE_CASE_: Union[str, Any] =tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(lowerCAmelCase ): SCREAMING_SNAKE_CASE_: Tuple =tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def lowerCamelCase__ ( self : Any ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[str] =TFLayoutLMvaModelTester(self ) SCREAMING_SNAKE_CASE_: int =ConfigTester(self , config_class=lowerCAmelCase , hidden_size=37 ) def lowerCamelCase__ ( self : Dict ) -> str: '''simple docstring''' self.config_tester.run_common_tests() def lowerCamelCase__ ( self : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[Any] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_: str =model_class(lowerCAmelCase ) if getattr(lowerCAmelCase , """hf_compute_loss""" , lowerCAmelCase ): # The number of elements in the loss should be the same as the number of elements in the label SCREAMING_SNAKE_CASE_: Optional[int] =self._prepare_for_class(inputs_dict.copy() , lowerCAmelCase , return_labels=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple =prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=lowerCAmelCase )[0] ] SCREAMING_SNAKE_CASE_: Any =added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs SCREAMING_SNAKE_CASE_: Union[str, Any] =self._prepare_for_class(inputs_dict.copy() , lowerCAmelCase , return_labels=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Any =prepared_for_class.pop("""input_ids""" ) SCREAMING_SNAKE_CASE_: Tuple =model(lowerCAmelCase , **lowerCAmelCase )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions SCREAMING_SNAKE_CASE_: List[Any] =self._prepare_for_class(inputs_dict.copy() , lowerCAmelCase , return_labels=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =prepared_for_class.pop("""input_ids""" ) if "labels" in prepared_for_class: SCREAMING_SNAKE_CASE_: str =prepared_for_class["""labels"""].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: SCREAMING_SNAKE_CASE_: Dict =-100 SCREAMING_SNAKE_CASE_: Any =tf.convert_to_tensor(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[Any] =model(lowerCAmelCase , **lowerCAmelCase )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict SCREAMING_SNAKE_CASE_: str =self._prepare_for_class(inputs_dict.copy() , lowerCAmelCase , return_labels=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =model(lowerCAmelCase )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple SCREAMING_SNAKE_CASE_: List[str] =self._prepare_for_class(inputs_dict.copy() , lowerCAmelCase , return_labels=lowerCAmelCase ) # Get keys that were added with the _prepare_for_class function SCREAMING_SNAKE_CASE_: List[Any] =prepared_for_class.keys() - inputs_dict.keys() SCREAMING_SNAKE_CASE_: List[str] =inspect.signature(model.call ).parameters SCREAMING_SNAKE_CASE_: Optional[Any] =list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple SCREAMING_SNAKE_CASE_: Any ={0: """input_ids"""} for label_key in label_keys: SCREAMING_SNAKE_CASE_: List[str] =signature_names.index(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: int =label_key SCREAMING_SNAKE_CASE_: str =sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple SCREAMING_SNAKE_CASE_: str =[] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: SCREAMING_SNAKE_CASE_: Any =prepared_for_class[value] SCREAMING_SNAKE_CASE_: Dict =tuple(lowerCAmelCase ) # Send to model SCREAMING_SNAKE_CASE_: Any =model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def lowerCamelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' ( ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ): Union[str, Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) def lowerCamelCase__ ( self : Optional[int] ) -> Union[str, Any]: '''simple docstring''' ( ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ): Tuple =self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE_: Optional[int] =type self.model_tester.create_and_check_model(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) def lowerCamelCase__ ( self : List[str] ) -> Any: '''simple docstring''' ( ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ): str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) def lowerCamelCase__ ( self : Any ) -> List[Any]: '''simple docstring''' ( ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ): Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) def lowerCamelCase__ ( self : List[Any] ) -> Any: '''simple docstring''' ( ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ): Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) @slow def lowerCamelCase__ ( self : str ) -> Optional[int]: '''simple docstring''' for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_: Dict =TFLayoutLMvaModel.from_pretrained(lowerCAmelCase ) self.assertIsNotNone(lowerCAmelCase ) def __magic_name__ ( ): SCREAMING_SNAKE_CASE_: Union[str, Any] =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf class a ( unittest.TestCase ): @cached_property def lowerCamelCase__ ( self : str ) -> Optional[int]: '''simple docstring''' return LayoutLMvaImageProcessor(apply_ocr=lowerCAmelCase ) if is_vision_available() else None @slow def lowerCamelCase__ ( self : Dict ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[Any] =TFLayoutLMvaModel.from_pretrained("""microsoft/layoutlmv3-base""" ) SCREAMING_SNAKE_CASE_: str =self.default_image_processor SCREAMING_SNAKE_CASE_: Dict =prepare_img() SCREAMING_SNAKE_CASE_: List[str] =image_processor(images=lowerCAmelCase , return_tensors="""tf""" ).pixel_values SCREAMING_SNAKE_CASE_: Union[str, Any] =tf.constant([[1, 2]] ) SCREAMING_SNAKE_CASE_: List[str] =tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass SCREAMING_SNAKE_CASE_: Tuple =model(input_ids=lowerCAmelCase , bbox=lowerCAmelCase , pixel_values=lowerCAmelCase , training=lowerCAmelCase ) # verify the logits SCREAMING_SNAKE_CASE_: List[Any] =(1, 199, 768) self.assertEqual(outputs.last_hidden_state.shape , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[Any] =tf.constant( [[-0.0_5_2_9, 0.3_6_1_8, 0.1_6_3_2], [-0.1_5_8_7, -0.1_6_6_7, -0.0_4_0_0], [-0.1_5_5_7, -0.1_6_7_1, -0.0_5_0_5]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , lowerCAmelCase , atol=1E-4 ) )
36
"""simple docstring""" from __future__ import annotations import math import random from typing import Any class a : def __init__( self : str ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: list[Any] =[] SCREAMING_SNAKE_CASE_: int =0 SCREAMING_SNAKE_CASE_: int =0 def lowerCamelCase__ ( self : Optional[Any] ) -> bool: '''simple docstring''' return self.head == self.tail def lowerCamelCase__ ( self : Tuple , lowerCAmelCase : Any ) -> None: '''simple docstring''' self.data.append(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =self.tail + 1 def lowerCamelCase__ ( self : int ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: int =self.data[self.head] SCREAMING_SNAKE_CASE_: Optional[int] =self.head + 1 return ret def lowerCamelCase__ ( self : Optional[Any] ) -> int: '''simple docstring''' return self.tail - self.head def lowerCamelCase__ ( self : str ) -> None: '''simple docstring''' print(self.data ) print("""**************""" ) print(self.data[self.head : self.tail] ) class a : def __init__( self : Union[str, Any] , lowerCAmelCase : Any ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =data SCREAMING_SNAKE_CASE_: MyNode | None =None SCREAMING_SNAKE_CASE_: MyNode | None =None SCREAMING_SNAKE_CASE_: int =1 def lowerCamelCase__ ( self : Optional[Any] ) -> Any: '''simple docstring''' return self.data def lowerCamelCase__ ( self : List[Any] ) -> MyNode | None: '''simple docstring''' return self.left def lowerCamelCase__ ( self : Dict ) -> MyNode | None: '''simple docstring''' return self.right def lowerCamelCase__ ( self : Any ) -> int: '''simple docstring''' return self.height def lowerCamelCase__ ( self : Any , lowerCAmelCase : Any ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[Any] =data def lowerCamelCase__ ( self : Dict , lowerCAmelCase : MyNode | None ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =node def lowerCamelCase__ ( self : List[Any] , lowerCAmelCase : MyNode | None ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: str =node def lowerCamelCase__ ( self : int , lowerCAmelCase : int ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =height def __magic_name__ ( lowercase ): if node is None: return 0 return node.get_height() def __magic_name__ ( lowercase , lowercase ): if a > b: return a return b def __magic_name__ ( lowercase ): print("""left rotation node:""" , node.get_data() ) SCREAMING_SNAKE_CASE_: List[Any] =node.get_left() assert ret is not None node.set_left(ret.get_right() ) ret.set_right(lowercase ) SCREAMING_SNAKE_CASE_: Tuple =my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowercase ) SCREAMING_SNAKE_CASE_: int =my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(lowercase ) return ret def __magic_name__ ( lowercase ): print("""right rotation node:""" , node.get_data() ) SCREAMING_SNAKE_CASE_: List[Any] =node.get_right() assert ret is not None node.set_right(ret.get_left() ) ret.set_left(lowercase ) SCREAMING_SNAKE_CASE_: List[Any] =my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowercase ) SCREAMING_SNAKE_CASE_: Optional[int] =my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(lowercase ) return ret def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Any =node.get_left() assert left_child is not None node.set_left(left_rotation(lowercase ) ) return right_rotation(lowercase ) def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Dict =node.get_right() assert right_child is not None node.set_right(right_rotation(lowercase ) ) return left_rotation(lowercase ) def __magic_name__ ( lowercase , lowercase ): if node is None: return MyNode(lowercase ) if data < node.get_data(): node.set_left(insert_node(node.get_left() , lowercase ) ) if ( get_height(node.get_left() ) - get_height(node.get_right() ) == 2 ): # an unbalance detected SCREAMING_SNAKE_CASE_: Union[str, Any] =node.get_left() assert left_child is not None if ( data < left_child.get_data() ): # new node is the left child of the left child SCREAMING_SNAKE_CASE_: Any =right_rotation(lowercase ) else: SCREAMING_SNAKE_CASE_: List[Any] =lr_rotation(lowercase ) else: node.set_right(insert_node(node.get_right() , lowercase ) ) if get_height(node.get_right() ) - get_height(node.get_left() ) == 2: SCREAMING_SNAKE_CASE_: Tuple =node.get_right() assert right_child is not None if data < right_child.get_data(): SCREAMING_SNAKE_CASE_: Optional[Any] =rl_rotation(lowercase ) else: SCREAMING_SNAKE_CASE_: Optional[int] =left_rotation(lowercase ) SCREAMING_SNAKE_CASE_: Tuple =my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowercase ) return node def __magic_name__ ( lowercase ): while True: SCREAMING_SNAKE_CASE_: Dict =root.get_right() if right_child is None: break SCREAMING_SNAKE_CASE_: str =right_child return root.get_data() def __magic_name__ ( lowercase ): while True: SCREAMING_SNAKE_CASE_: str =root.get_left() if left_child is None: break SCREAMING_SNAKE_CASE_: Dict =left_child return root.get_data() def __magic_name__ ( lowercase , lowercase ): SCREAMING_SNAKE_CASE_: str =root.get_left() SCREAMING_SNAKE_CASE_: List[Any] =root.get_right() if root.get_data() == data: if left_child is not None and right_child is not None: SCREAMING_SNAKE_CASE_: Union[str, Any] =get_left_most(lowercase ) root.set_data(lowercase ) root.set_right(del_node(lowercase , lowercase ) ) elif left_child is not None: SCREAMING_SNAKE_CASE_: Optional[int] =left_child elif right_child is not None: SCREAMING_SNAKE_CASE_: Any =right_child else: return None elif root.get_data() > data: if left_child is None: print("""No such data""" ) return root else: root.set_left(del_node(lowercase , lowercase ) ) else: # root.get_data() < data if right_child is None: return root else: root.set_right(del_node(lowercase , lowercase ) ) if get_height(lowercase ) - get_height(lowercase ) == 2: assert right_child is not None if get_height(right_child.get_right() ) > get_height(right_child.get_left() ): SCREAMING_SNAKE_CASE_: Tuple =left_rotation(lowercase ) else: SCREAMING_SNAKE_CASE_: Optional[Any] =rl_rotation(lowercase ) elif get_height(lowercase ) - get_height(lowercase ) == -2: assert left_child is not None if get_height(left_child.get_left() ) > get_height(left_child.get_right() ): SCREAMING_SNAKE_CASE_: Optional[Any] =right_rotation(lowercase ) else: SCREAMING_SNAKE_CASE_: str =lr_rotation(lowercase ) SCREAMING_SNAKE_CASE_: str =my_max(get_height(root.get_right() ) , get_height(root.get_left() ) ) + 1 root.set_height(lowercase ) return root class a : def __init__( self : int ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE_: MyNode | None =None def lowerCamelCase__ ( self : List[Any] ) -> int: '''simple docstring''' return get_height(self.root ) def lowerCamelCase__ ( self : Optional[int] , lowerCAmelCase : Any ) -> None: '''simple docstring''' print("""insert:""" + str(lowerCAmelCase ) ) SCREAMING_SNAKE_CASE_: Tuple =insert_node(self.root , lowerCAmelCase ) def lowerCamelCase__ ( self : List[Any] , lowerCAmelCase : Any ) -> None: '''simple docstring''' print("""delete:""" + str(lowerCAmelCase ) ) if self.root is None: print("""Tree is empty!""" ) return SCREAMING_SNAKE_CASE_: Union[str, Any] =del_node(self.root , lowerCAmelCase ) def __str__( self : List[str] , ) -> str: # a level traversale, gives a more intuitive look on the tree '''simple docstring''' SCREAMING_SNAKE_CASE_: List[Any] ="""""" SCREAMING_SNAKE_CASE_: str =MyQueue() q.push(self.root ) SCREAMING_SNAKE_CASE_: List[str] =self.get_height() if layer == 0: return output SCREAMING_SNAKE_CASE_: int =0 while not q.is_empty(): SCREAMING_SNAKE_CASE_: int =q.pop() SCREAMING_SNAKE_CASE_: List[Any] =""" """ * int(math.pow(2 , layer - 1 ) ) output += space if node is None: output += "*" q.push(lowerCAmelCase ) q.push(lowerCAmelCase ) else: output += str(node.get_data() ) q.push(node.get_left() ) q.push(node.get_right() ) output += space SCREAMING_SNAKE_CASE_: List[Any] =cnt + 1 for i in range(100 ): if cnt == math.pow(2 , lowerCAmelCase ) - 1: SCREAMING_SNAKE_CASE_: int =layer - 1 if layer == 0: output += "\n*************************************" return output output += "\n" break output += "\n*************************************" return output def __magic_name__ ( ): import doctest doctest.testmod() if __name__ == "__main__": _test() _UpperCAmelCase = AVLtree() _UpperCAmelCase = list(range(1_0)) random.shuffle(lst) for i in lst: t.insert(i) print(str(t)) random.shuffle(lst) for i in lst: t.del_node(i) print(str(t))
36
1
"""simple docstring""" from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _UpperCAmelCase = {"""configuration_focalnet""": ["""FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """FocalNetConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ """FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST""", """FocalNetForImageClassification""", """FocalNetForMaskedImageModeling""", """FocalNetBackbone""", """FocalNetModel""", """FocalNetPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_focalnet import ( FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST, FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, FocalNetPreTrainedModel, ) else: import sys _UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
36
"""simple docstring""" import string def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: List[Any] ="""""" for i in sequence: SCREAMING_SNAKE_CASE_: List[Any] =ord(lowercase ) if 65 <= extract <= 90: output += chr(155 - extract ) elif 97 <= extract <= 122: output += chr(219 - extract ) else: output += i return output def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Any =string.ascii_letters SCREAMING_SNAKE_CASE_: Tuple =string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1] return "".join( letters_reversed[letters.index(lowercase )] if c in letters else c for c in sequence ) def __magic_name__ ( ): from timeit import timeit print("""Running performance benchmarks...""" ) SCREAMING_SNAKE_CASE_: int ="""from string import printable ; from __main__ import atbash, atbash_slow""" print(f'''> atbash_slow(): {timeit("atbash_slow(printable)" , setup=lowercase )} seconds''' ) print(f'''> atbash(): {timeit("atbash(printable)" , setup=lowercase )} seconds''' ) if __name__ == "__main__": for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"): print(f"""{example} encrypted in atbash: {atbash(example)}""") benchmark()
36
1
"""simple docstring""" 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 a ( unittest.TestCase ): def lowerCamelCase__ ( self : Dict ) -> str: '''simple docstring''' super().tearDown() gc.collect() def lowerCamelCase__ ( self : Optional[Any] ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Dict =FlaxStableDiffusionPipeline.from_pretrained( """stabilityai/stable-diffusion-2""" , revision="""bf16""" , dtype=jnp.bfloataa , ) SCREAMING_SNAKE_CASE_: Union[str, Any] ="""A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE_: Any =jax.device_count() SCREAMING_SNAKE_CASE_: Dict =num_samples * [prompt] SCREAMING_SNAKE_CASE_: List[Any] =sd_pipe.prepare_inputs(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Union[str, Any] =replicate(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =shard(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Dict =jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE_: Union[str, Any] =jax.random.split(lowerCAmelCase , jax.device_count() ) SCREAMING_SNAKE_CASE_: Tuple =sd_pipe(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , num_inference_steps=25 , jit=lowerCAmelCase )[0] assert images.shape == (jax.device_count(), 1, 768, 768, 3) SCREAMING_SNAKE_CASE_: Dict =images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) SCREAMING_SNAKE_CASE_: Dict =images[0, 253:256, 253:256, -1] SCREAMING_SNAKE_CASE_: Optional[int] =jnp.asarray(jax.device_get(image_slice.flatten() ) ) SCREAMING_SNAKE_CASE_: Optional[int] =jnp.array([0.4_2_3_8, 0.4_4_1_4, 0.4_3_9_5, 0.4_4_5_3, 0.4_6_2_9, 0.4_5_9_0, 0.4_5_3_1, 0.4_5_5_0_8, 0.4_5_1_2] ) print(f'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2 def lowerCamelCase__ ( self : List[str] ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE_: int ="""stabilityai/stable-diffusion-2""" SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[int] =FlaxDPMSolverMultistepScheduler.from_pretrained(lowerCAmelCase , subfolder="""scheduler""" ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[int] =FlaxStableDiffusionPipeline.from_pretrained( lowerCAmelCase , scheduler=lowerCAmelCase , revision="""bf16""" , dtype=jnp.bfloataa , ) SCREAMING_SNAKE_CASE_: Optional[int] =scheduler_params SCREAMING_SNAKE_CASE_: Tuple ="""A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE_: Union[str, Any] =jax.device_count() SCREAMING_SNAKE_CASE_: Optional[Any] =num_samples * [prompt] SCREAMING_SNAKE_CASE_: List[Any] =sd_pipe.prepare_inputs(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple =replicate(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =shard(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Any =jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE_: Any =jax.random.split(lowerCAmelCase , jax.device_count() ) SCREAMING_SNAKE_CASE_: Tuple =sd_pipe(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , num_inference_steps=25 , jit=lowerCAmelCase )[0] assert images.shape == (jax.device_count(), 1, 768, 768, 3) SCREAMING_SNAKE_CASE_: str =images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) SCREAMING_SNAKE_CASE_: Any =images[0, 253:256, 253:256, -1] SCREAMING_SNAKE_CASE_: Optional[Any] =jnp.asarray(jax.device_get(image_slice.flatten() ) ) SCREAMING_SNAKE_CASE_: Optional[int] =jnp.array([0.4_3_3_6, 0.4_2_9_6_9, 0.4_4_5_3, 0.4_1_9_9, 0.4_2_9_7, 0.4_5_3_1, 0.4_4_3_4, 0.4_4_3_4, 0.4_2_9_7] ) print(f'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2
36
"""simple docstring""" import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class a : def __init__( self : Union[str, Any] , lowerCAmelCase : List[str]=2 , lowerCAmelCase : int=3 , lowerCAmelCase : Optional[Any]=64 , lowerCAmelCase : Union[str, Any]=None ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Union[str, Any] =np.random.default_rng(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =length SCREAMING_SNAKE_CASE_: Union[str, Any] =rng.normal(size=(length,) ).astype(np.floataa ) SCREAMING_SNAKE_CASE_: Tuple =a * self.x + b + rng.normal(scale=0.1 , size=(length,) ).astype(np.floataa ) def __len__( self : List[Any] ) -> str: '''simple docstring''' return self.length def __getitem__( self : Union[str, Any] , lowerCAmelCase : Any ) -> List[str]: '''simple docstring''' return {"x": self.x[i], "y": self.y[i]} class a ( torch.nn.Module ): def __init__( self : Optional[int] , lowerCAmelCase : str=0 , lowerCAmelCase : List[Any]=0 , lowerCAmelCase : Optional[int]=False ) -> Tuple: '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE_: int =torch.nn.Parameter(torch.tensor([2, 3] ).float() ) SCREAMING_SNAKE_CASE_: int =torch.nn.Parameter(torch.tensor([2, 3] ).float() ) SCREAMING_SNAKE_CASE_: Dict =True def lowerCamelCase__ ( self : str , lowerCAmelCase : Tuple=None ) -> int: '''simple docstring''' if self.first_batch: print(f'''Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}''' ) SCREAMING_SNAKE_CASE_: Union[str, Any] =False return x * self.a[0] + self.b[0] class a ( torch.nn.Module ): def __init__( self : Union[str, Any] , lowerCAmelCase : Any=0 , lowerCAmelCase : List[Any]=0 , lowerCAmelCase : List[Any]=False ) -> str: '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE_: List[str] =torch.nn.Parameter(torch.tensor(lowerCAmelCase ).float() ) SCREAMING_SNAKE_CASE_: Optional[int] =torch.nn.Parameter(torch.tensor(lowerCAmelCase ).float() ) SCREAMING_SNAKE_CASE_: List[Any] =True def lowerCamelCase__ ( self : List[str] , lowerCAmelCase : int=None ) -> Any: '''simple docstring''' if self.first_batch: print(f'''Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}''' ) SCREAMING_SNAKE_CASE_: Optional[int] =False return x * self.a + self.b def __magic_name__ ( lowercase , lowercase = 16 ): from datasets import load_dataset from transformers import AutoTokenizer SCREAMING_SNAKE_CASE_: Optional[Any] =AutoTokenizer.from_pretrained("""bert-base-cased""" ) SCREAMING_SNAKE_CASE_: Optional[int] ={"""train""": """tests/test_samples/MRPC/train.csv""", """validation""": """tests/test_samples/MRPC/dev.csv"""} SCREAMING_SNAKE_CASE_: Any =load_dataset("""csv""" , data_files=lowercase ) SCREAMING_SNAKE_CASE_: Any =datasets["""train"""].unique("""label""" ) SCREAMING_SNAKE_CASE_: List[Any] ={v: i for i, v in enumerate(lowercase )} def tokenize_function(lowercase ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE_: Dict =tokenizer( examples["""sentence1"""] , examples["""sentence2"""] , truncation=lowercase , max_length=lowercase , padding="""max_length""" ) if "label" in examples: SCREAMING_SNAKE_CASE_: Optional[int] =[label_to_id[l] for l in examples["""label"""]] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset SCREAMING_SNAKE_CASE_: List[Any] =datasets.map( lowercase , batched=lowercase , remove_columns=["""sentence1""", """sentence2""", """label"""] , ) def collate_fn(lowercase ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(lowercase , padding="""max_length""" , max_length=128 , return_tensors="""pt""" ) return tokenizer.pad(lowercase , padding="""longest""" , return_tensors="""pt""" ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE_: Optional[int] =DataLoader(tokenized_datasets["""train"""] , shuffle=lowercase , collate_fn=lowercase , batch_size=2 ) SCREAMING_SNAKE_CASE_: Dict =DataLoader(tokenized_datasets["""validation"""] , shuffle=lowercase , collate_fn=lowercase , batch_size=1 ) return train_dataloader, eval_dataloader
36
1
"""simple docstring""" import argparse from pathlib import Path import torch from transformers import OPTConfig, OPTModel from transformers.utils import logging logging.set_verbosity_info() _UpperCAmelCase = logging.get_logger(__name__) def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: str =torch.load(lowercase , map_location="""cpu""" ) if "model" in sd.keys(): SCREAMING_SNAKE_CASE_: Tuple =torch.load(lowercase , map_location="""cpu""" )["""model"""] # pop unnecessary weights SCREAMING_SNAKE_CASE_: Optional[int] =[ """decoder.version""", """decoder.output_projection.weight""", ] for key in keys_to_delete: if key in sd: sd.pop(lowercase ) SCREAMING_SNAKE_CASE_: Optional[Any] ={ """decoder.project_in_dim.weight""": """decoder.project_in.weight""", """decoder.project_out_dim.weight""": """decoder.project_out.weight""", """decoder.layer_norm.weight""": """decoder.final_layer_norm.weight""", """decoder.layer_norm.bias""": """decoder.final_layer_norm.bias""", } for old_key, new_key in keys_to_rename.items(): if old_key in sd: SCREAMING_SNAKE_CASE_: Dict =sd.pop(lowercase ) SCREAMING_SNAKE_CASE_: str =list(sd.keys() ) for key in keys: if ".qkv_proj." in key: SCREAMING_SNAKE_CASE_: Any =sd[key] # We split QKV in separate Q,K,V SCREAMING_SNAKE_CASE_: Dict =key.replace(""".qkv_proj.""" , """.q_proj.""" ) SCREAMING_SNAKE_CASE_: List[str] =key.replace(""".qkv_proj.""" , """.k_proj.""" ) SCREAMING_SNAKE_CASE_: List[str] =key.replace(""".qkv_proj.""" , """.v_proj.""" ) SCREAMING_SNAKE_CASE_: List[str] =value.shape[0] assert depth % 3 == 0 # `SequeuceParallelTransformerBlock` has QKV weight is separated in K,V,Q despite the naming: # https://cs.github.com/facebookresearch/metaseq/blob/51871bd73cd04c038f239ea2a26db1d7f6b37927/metaseq/modules/sequence_parallel_transformer_layer.py#L97 SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Dict =torch.split(lowercase , depth // 3 , dim=0 ) SCREAMING_SNAKE_CASE_: Tuple =q SCREAMING_SNAKE_CASE_: Optional[int] =k SCREAMING_SNAKE_CASE_: Dict =v del sd[key] return sd @torch.no_grad() def __magic_name__ ( lowercase , lowercase , lowercase=None ): SCREAMING_SNAKE_CASE_: List[Any] =load_checkpoint(lowercase ) if config is not None: SCREAMING_SNAKE_CASE_: List[Any] =OPTConfig.from_pretrained(lowercase ) else: SCREAMING_SNAKE_CASE_: Dict =OPTConfig() SCREAMING_SNAKE_CASE_: List[Any] =OPTModel(lowercase ).half().eval() model.load_state_dict(lowercase ) # Check results Path(lowercase ).mkdir(exist_ok=lowercase ) model.save_pretrained(lowercase ) if __name__ == "__main__": _UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--fairseq_path""", type=str, help=( """path to fairseq checkpoint in correct format. You can find all checkpoints in the correct format here:""" """ https://huggingface.co/models?other=opt_metasq""" ), ) parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--hf_config""", default=None, type=str, help="""Define HF config.""") _UpperCAmelCase = parser.parse_args() convert_opt_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, config=args.hf_config)
36
"""simple docstring""" def __magic_name__ ( lowercase ): if upper_limit < 0: raise ValueError("""Limit for the Catalan sequence must be ≥ 0""" ) SCREAMING_SNAKE_CASE_: Tuple =[0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 SCREAMING_SNAKE_CASE_: Any =1 if upper_limit > 0: SCREAMING_SNAKE_CASE_: List[str] =1 # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i for i in range(2 , upper_limit + 1 ): for j in range(lowercase ): catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1] return catalan_list if __name__ == "__main__": print("""\n********* Catalan Numbers Using Dynamic Programming ************\n""") print("""\n*** Enter -1 at any time to quit ***""") print("""\nEnter the upper limit (≥ 0) for the Catalan number sequence: """, end="""""") try: while True: _UpperCAmelCase = int(input().strip()) if N < 0: print("""\n********* Goodbye!! ************""") break else: print(f"""The Catalan numbers from 0 through {N} are:""") print(catalan_numbers(N)) print("""Try another upper limit for the sequence: """, end="""""") except (NameError, ValueError): print("""\n********* Invalid input, goodbye! ************\n""") import doctest doctest.testmod()
36
1
"""simple docstring""" import unittest import numpy as np from transformers import BertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models.bert.modeling_flax_bert import ( FlaxBertForMaskedLM, FlaxBertForMultipleChoice, FlaxBertForNextSentencePrediction, FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification, FlaxBertForTokenClassification, FlaxBertModel, ) class a ( unittest.TestCase ): def __init__( self : Optional[int] , lowerCAmelCase : List[str] , lowerCAmelCase : Tuple=13 , lowerCAmelCase : List[Any]=7 , lowerCAmelCase : List[str]=True , lowerCAmelCase : List[str]=True , lowerCAmelCase : int=True , lowerCAmelCase : List[Any]=True , lowerCAmelCase : str=99 , lowerCAmelCase : Optional[int]=32 , lowerCAmelCase : str=5 , lowerCAmelCase : Optional[Any]=4 , lowerCAmelCase : int=37 , lowerCAmelCase : Tuple="gelu" , lowerCAmelCase : Optional[int]=0.1 , lowerCAmelCase : Tuple=0.1 , lowerCAmelCase : Optional[int]=512 , lowerCAmelCase : Optional[Any]=16 , lowerCAmelCase : Tuple=2 , lowerCAmelCase : List[str]=0.0_2 , lowerCAmelCase : Any=4 , ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =parent SCREAMING_SNAKE_CASE_: int =batch_size SCREAMING_SNAKE_CASE_: Any =seq_length SCREAMING_SNAKE_CASE_: Any =is_training SCREAMING_SNAKE_CASE_: Optional[Any] =use_attention_mask SCREAMING_SNAKE_CASE_: List[Any] =use_token_type_ids SCREAMING_SNAKE_CASE_: Optional[int] =use_labels SCREAMING_SNAKE_CASE_: int =vocab_size SCREAMING_SNAKE_CASE_: Tuple =hidden_size SCREAMING_SNAKE_CASE_: List[str] =num_hidden_layers SCREAMING_SNAKE_CASE_: List[Any] =num_attention_heads SCREAMING_SNAKE_CASE_: List[Any] =intermediate_size SCREAMING_SNAKE_CASE_: Optional[Any] =hidden_act SCREAMING_SNAKE_CASE_: int =hidden_dropout_prob SCREAMING_SNAKE_CASE_: int =attention_probs_dropout_prob SCREAMING_SNAKE_CASE_: Dict =max_position_embeddings SCREAMING_SNAKE_CASE_: Tuple =type_vocab_size SCREAMING_SNAKE_CASE_: Optional[int] =type_sequence_label_size SCREAMING_SNAKE_CASE_: Optional[Any] =initializer_range SCREAMING_SNAKE_CASE_: Dict =num_choices def lowerCamelCase__ ( self : str ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[str] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE_: Union[str, Any] =None if self.use_attention_mask: SCREAMING_SNAKE_CASE_: int =random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE_: Any =None if self.use_token_type_ids: SCREAMING_SNAKE_CASE_: Dict =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE_: List[str] =BertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=lowerCAmelCase , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def lowerCamelCase__ ( self : Optional[int] ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[Any] =config_and_inputs SCREAMING_SNAKE_CASE_: List[str] ={"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict def lowerCamelCase__ ( self : str ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: int =self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Any =config_and_inputs SCREAMING_SNAKE_CASE_: Any =True SCREAMING_SNAKE_CASE_: List[str] =floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) SCREAMING_SNAKE_CASE_: List[str] =ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, attention_mask, encoder_hidden_states, encoder_attention_mask, ) @require_flax class a ( UpperCAmelCase__ , unittest.TestCase ): UpperCamelCase : Optional[Any] = True UpperCamelCase : Any = ( ( FlaxBertModel, FlaxBertForPreTraining, FlaxBertForMaskedLM, FlaxBertForMultipleChoice, FlaxBertForQuestionAnswering, FlaxBertForNextSentencePrediction, FlaxBertForSequenceClassification, FlaxBertForTokenClassification, FlaxBertForQuestionAnswering, ) if is_flax_available() else () ) def lowerCamelCase__ ( self : List[Any] ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[int] =FlaxBertModelTester(self ) @slow def lowerCamelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[Any] =FlaxBertModel.from_pretrained("""bert-base-cased""" ) SCREAMING_SNAKE_CASE_: str =model(np.ones((1, 1) ) ) self.assertIsNotNone(lowerCAmelCase )
36
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig _UpperCAmelCase = { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/config.json""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/config.json""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/config.json""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/config.json""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/config.json""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/config.json""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json""", } class a ( UpperCAmelCase__ ): UpperCamelCase : Any = 'albert' def __init__( self : Dict , lowerCAmelCase : List[str]=3_0000 , lowerCAmelCase : List[Any]=128 , lowerCAmelCase : List[str]=4096 , lowerCAmelCase : str=12 , lowerCAmelCase : str=1 , lowerCAmelCase : Tuple=64 , lowerCAmelCase : Dict=1_6384 , lowerCAmelCase : int=1 , lowerCAmelCase : str="gelu_new" , lowerCAmelCase : Dict=0 , lowerCAmelCase : Optional[Any]=0 , lowerCAmelCase : str=512 , lowerCAmelCase : Optional[int]=2 , lowerCAmelCase : List[Any]=0.0_2 , lowerCAmelCase : Union[str, Any]=1E-12 , lowerCAmelCase : Tuple=0.1 , lowerCAmelCase : List[Any]="absolute" , lowerCAmelCase : List[Any]=0 , lowerCAmelCase : int=2 , lowerCAmelCase : Optional[int]=3 , **lowerCAmelCase : int , ) -> Tuple: '''simple docstring''' super().__init__(pad_token_id=lowerCAmelCase , bos_token_id=lowerCAmelCase , eos_token_id=lowerCAmelCase , **lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =vocab_size SCREAMING_SNAKE_CASE_: Optional[int] =embedding_size SCREAMING_SNAKE_CASE_: Optional[int] =hidden_size SCREAMING_SNAKE_CASE_: Tuple =num_hidden_layers SCREAMING_SNAKE_CASE_: Any =num_hidden_groups SCREAMING_SNAKE_CASE_: List[Any] =num_attention_heads SCREAMING_SNAKE_CASE_: List[Any] =inner_group_num SCREAMING_SNAKE_CASE_: Optional[int] =hidden_act SCREAMING_SNAKE_CASE_: int =intermediate_size SCREAMING_SNAKE_CASE_: Any =hidden_dropout_prob SCREAMING_SNAKE_CASE_: Union[str, Any] =attention_probs_dropout_prob SCREAMING_SNAKE_CASE_: int =max_position_embeddings SCREAMING_SNAKE_CASE_: Any =type_vocab_size SCREAMING_SNAKE_CASE_: int =initializer_range SCREAMING_SNAKE_CASE_: List[Any] =layer_norm_eps SCREAMING_SNAKE_CASE_: Dict =classifier_dropout_prob SCREAMING_SNAKE_CASE_: int =position_embedding_type class a ( UpperCAmelCase__ ): @property def lowerCamelCase__ ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": SCREAMING_SNAKE_CASE_: str ={0: """batch""", 1: """choice""", 2: """sequence"""} else: SCREAMING_SNAKE_CASE_: Dict ={0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
36
1
"""simple docstring""" from scipy.stats import spearmanr import datasets _UpperCAmelCase = """ The Spearman rank-order correlation coefficient is a measure of the relationship between two datasets. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Positive correlations imply that as data in dataset x increases, so does data in dataset y. Negative correlations imply that as x increases, y decreases. Correlations of -1 or +1 imply an exact monotonic relationship. Unlike the Pearson correlation, the Spearman correlation does not assume that both datasets are normally distributed. The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Spearman correlation at least as extreme as the one computed from these datasets. The p-values are not entirely reliable but are probably reasonable for datasets larger than 500 or so. """ _UpperCAmelCase = """ Args: predictions (`List[float]`): Predicted labels, as returned by a model. references (`List[float]`): Ground truth labels. return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns only the spearmanr score. Defaults to `False`. Returns: spearmanr (`float`): Spearman correlation coefficient. p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input. Examples: Example 1: >>> spearmanr_metric = datasets.load_metric(\"spearmanr\") >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4]) >>> print(results) {'spearmanr': -0.7} Example 2: >>> spearmanr_metric = datasets.load_metric(\"spearmanr\") >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], ... predictions=[10, 9, 2.5, 6, 4], ... return_pvalue=True) >>> print(results['spearmanr']) -0.7 >>> print(round(results['spearmanr_pvalue'], 2)) 0.19 """ _UpperCAmelCase = r"""\ @book{kokoska2000crc, title={CRC standard probability and statistics tables and formulae}, author={Kokoska, Stephen and Zwillinger, Daniel}, year={2000}, publisher={Crc Press} } @article{2020SciPy-NMeth, author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and Haberland, Matt and Reddy, Tyler and Cournapeau, David and Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and Bright, Jonathan and {van der Walt}, St{\'e}fan J. and Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and Kern, Robert and Larson, Eric and Carey, C J and Polat, {\.I}lhan and Feng, Yu and Moore, Eric W. and {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and Harris, Charles R. and Archibald, Anne M. and Ribeiro, Ant{\^o}nio H. and Pedregosa, Fabian and {van Mulbregt}, Paul and {SciPy 1.0 Contributors}}, title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific Computing in Python}}, journal = {Nature Methods}, year = {2020}, volume = {17}, pages = {261--272}, adsurl = {https://rdcu.be/b08Wh}, doi = {10.1038/s41592-019-0686-2}, } """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a ( datasets.Metric ): def lowerCamelCase__ ( self : str ) -> List[Any]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""float""" ), """references""": datasets.Value("""float""" ), } ) , reference_urls=["""https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html"""] , ) def lowerCamelCase__ ( self : List[Any] , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : List[Any] , lowerCAmelCase : Dict=False ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =spearmanr(lowerCAmelCase , lowerCAmelCase ) if return_pvalue: return {"spearmanr": results[0], "spearmanr_pvalue": results[1]} else: return {"spearmanr": results[0]}
36
"""simple docstring""" from collections import Counter from pathlib import Path from typing import Optional, Tuple import yaml class a ( yaml.SafeLoader ): def lowerCamelCase__ ( self : int , lowerCAmelCase : List[str] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =[self.constructed_objects[key_node] for key_node, _ in node.value] SCREAMING_SNAKE_CASE_: Any =[tuple(lowerCAmelCase ) if isinstance(lowerCAmelCase , lowerCAmelCase ) else key for key in keys] SCREAMING_SNAKE_CASE_: Dict =Counter(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =[key for key in counter if counter[key] > 1] if duplicate_keys: raise TypeError(f'''Got duplicate yaml keys: {duplicate_keys}''' ) def lowerCamelCase__ ( self : Tuple , lowerCAmelCase : str , lowerCAmelCase : Optional[int]=False ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =super().construct_mapping(lowerCAmelCase , deep=lowerCAmelCase ) self._check_no_duplicates_on_constructed_node(lowerCAmelCase ) return mapping def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Dict =list(readme_content.splitlines() ) if full_content and full_content[0] == "---" and "---" in full_content[1:]: SCREAMING_SNAKE_CASE_: Union[str, Any] =full_content[1:].index("""---""" ) + 1 SCREAMING_SNAKE_CASE_: List[str] ="""\n""".join(full_content[1:sep_idx] ) return yamlblock, "\n".join(full_content[sep_idx + 1 :] ) return None, "\n".join(lowercase ) class a ( UpperCAmelCase__ ): # class attributes UpperCamelCase : Tuple = {'train_eval_index'} # train-eval-index in the YAML metadata @classmethod def lowerCamelCase__ ( cls : List[Any] , lowerCAmelCase : Path ) -> "DatasetMetadata": '''simple docstring''' with open(lowerCAmelCase , encoding="""utf-8""" ) as readme_file: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Union[str, Any] =_split_yaml_from_readme(readme_file.read() ) if yaml_string is not None: return cls.from_yaml_string(lowerCAmelCase ) else: return cls() def lowerCamelCase__ ( self : Any , lowerCAmelCase : Path ) -> List[str]: '''simple docstring''' if path.exists(): with open(lowerCAmelCase , encoding="""utf-8""" ) as readme_file: SCREAMING_SNAKE_CASE_: str =readme_file.read() else: SCREAMING_SNAKE_CASE_: str =None SCREAMING_SNAKE_CASE_: Tuple =self._to_readme(lowerCAmelCase ) with open(lowerCAmelCase , """w""" , encoding="""utf-8""" ) as readme_file: readme_file.write(lowerCAmelCase ) def lowerCamelCase__ ( self : Optional[Any] , lowerCAmelCase : Optional[str] = None ) -> str: '''simple docstring''' if readme_content is not None: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[str] =_split_yaml_from_readme(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] ="""---\n""" + self.to_yaml_string() + """---\n""" + content else: SCREAMING_SNAKE_CASE_: List[Any] ="""---\n""" + self.to_yaml_string() + """---\n""" return full_content @classmethod def lowerCamelCase__ ( cls : Optional[int] , lowerCAmelCase : str ) -> "DatasetMetadata": '''simple docstring''' SCREAMING_SNAKE_CASE_: int =yaml.load(lowerCAmelCase , Loader=_NoDuplicateSafeLoader ) or {} # Convert the YAML keys to DatasetMetadata fields SCREAMING_SNAKE_CASE_: List[Any] ={ (key.replace("""-""" , """_""" ) if key.replace("""-""" , """_""" ) in cls._FIELDS_WITH_DASHES else key): value for key, value in metadata_dict.items() } return cls(**lowerCAmelCase ) def lowerCamelCase__ ( self : Dict ) -> str: '''simple docstring''' return yaml.safe_dump( { (key.replace("""_""" , """-""" ) if key in self._FIELDS_WITH_DASHES else key): value for key, value in self.items() } , sort_keys=lowerCAmelCase , allow_unicode=lowerCAmelCase , encoding="""utf-8""" , ).decode("""utf-8""" ) _UpperCAmelCase = { """image-classification""": [], """translation""": [], """image-segmentation""": [], """fill-mask""": [], """automatic-speech-recognition""": [], """token-classification""": [], """sentence-similarity""": [], """audio-classification""": [], """question-answering""": [], """summarization""": [], """zero-shot-classification""": [], """table-to-text""": [], """feature-extraction""": [], """other""": [], """multiple-choice""": [], """text-classification""": [], """text-to-image""": [], """text2text-generation""": [], """zero-shot-image-classification""": [], """tabular-classification""": [], """tabular-regression""": [], """image-to-image""": [], """tabular-to-text""": [], """unconditional-image-generation""": [], """text-retrieval""": [], """text-to-speech""": [], """object-detection""": [], """audio-to-audio""": [], """text-generation""": [], """conversational""": [], """table-question-answering""": [], """visual-question-answering""": [], """image-to-text""": [], """reinforcement-learning""": [], """voice-activity-detection""": [], """time-series-forecasting""": [], """document-question-answering""": [], } if __name__ == "__main__": from argparse import ArgumentParser _UpperCAmelCase = ArgumentParser(usage="""Validate the yaml metadata block of a README.md file.""") ap.add_argument("""readme_filepath""") _UpperCAmelCase = ap.parse_args() _UpperCAmelCase = Path(args.readme_filepath) _UpperCAmelCase = DatasetMetadata.from_readme(readme_filepath) print(dataset_metadata) dataset_metadata.to_readme(readme_filepath)
36
1
"""simple docstring""" import webbrowser from sys import argv from urllib.parse import parse_qs, quote import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": _UpperCAmelCase = """%20""".join(argv[1:]) if len(argv) > 1 else quote(str(input("""Search: """))) print("""Googling.....""") _UpperCAmelCase = f"""https://www.google.com/search?q={query}&num=100""" _UpperCAmelCase = requests.get( url, headers={"""User-Agent""": str(UserAgent().random)}, ) try: _UpperCAmelCase = ( BeautifulSoup(res.text, """html.parser""") .find("""div""", attrs={"""class""": """yuRUbf"""}) .find("""a""") .get("""href""") ) except AttributeError: _UpperCAmelCase = parse_qs( BeautifulSoup(res.text, """html.parser""") .find("""div""", attrs={"""class""": """kCrYT"""}) .find("""a""") .get("""href""") )["""url"""][0] webbrowser.open(link)
36
"""simple docstring""" import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from xgboost import XGBClassifier def __magic_name__ ( lowercase ): return (data["data"], data["target"]) def __magic_name__ ( lowercase , lowercase ): SCREAMING_SNAKE_CASE_: Dict =XGBClassifier() classifier.fit(lowercase , lowercase ) return classifier def __magic_name__ ( ): SCREAMING_SNAKE_CASE_: Optional[Any] =load_iris() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Tuple =data_handling(lowercase ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[Any] =train_test_split( lowercase , lowercase , test_size=0.25 ) SCREAMING_SNAKE_CASE_: Tuple =iris["""target_names"""] # Create an XGBoost Classifier from the training data SCREAMING_SNAKE_CASE_: Optional[int] =xgboost(lowercase , lowercase ) # Display the confusion matrix of the classifier with both training and test sets ConfusionMatrixDisplay.from_estimator( lowercase , lowercase , lowercase , display_labels=lowercase , cmap="""Blues""" , normalize="""true""" , ) plt.title("""Normalized Confusion Matrix - IRIS Dataset""" ) plt.show() if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
36
1
"""simple docstring""" def __magic_name__ ( lowercase , lowercase ): if len(lowercase ) != len(lowercase ): raise ValueError("""String lengths must match!""" ) SCREAMING_SNAKE_CASE_: List[Any] =0 for chara, chara in zip(lowercase , lowercase ): if chara != chara: count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
36
"""simple docstring""" from typing import Dict import numpy as np import torch from . import residue_constants as rc from .tensor_utils import tensor_tree_map, tree_map def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Optional[Any] =[] SCREAMING_SNAKE_CASE_: List[str] =[] SCREAMING_SNAKE_CASE_: Any =[] for rt in rc.restypes: SCREAMING_SNAKE_CASE_: Optional[int] =rc.restype_name_to_atomaa_names[rc.restype_atoa[rt]] restype_atomaa_to_atomaa_list.append([(rc.atom_order[name] if name else 0) for name in atom_names] ) SCREAMING_SNAKE_CASE_: Any ={name: i for i, name in enumerate(lowercase )} restype_atomaa_to_atomaa_list.append( [(atom_name_to_idxaa[name] if name in atom_name_to_idxaa else 0) for name in rc.atom_types] ) restype_atomaa_mask_list.append([(1.0 if name else 0.0) for name in atom_names] ) # Add dummy mapping for restype 'UNK' restype_atomaa_to_atomaa_list.append([0] * 14 ) restype_atomaa_to_atomaa_list.append([0] * 37 ) restype_atomaa_mask_list.append([0.0] * 14 ) SCREAMING_SNAKE_CASE_: Union[str, Any] =torch.tensor( lowercase , dtype=torch.intaa , device=protein["""aatype"""].device , ) SCREAMING_SNAKE_CASE_: Optional[Any] =torch.tensor( lowercase , dtype=torch.intaa , device=protein["""aatype"""].device , ) SCREAMING_SNAKE_CASE_: List[str] =torch.tensor( lowercase , dtype=torch.floataa , device=protein["""aatype"""].device , ) SCREAMING_SNAKE_CASE_: Optional[Any] =protein["""aatype"""].to(torch.long ) # create the mapping for (residx, atom14) --> atom37, i.e. an array # with shape (num_res, 14) containing the atom37 indices for this protein SCREAMING_SNAKE_CASE_: List[str] =restype_atomaa_to_atomaa[protein_aatype] SCREAMING_SNAKE_CASE_: Any =restype_atomaa_mask[protein_aatype] SCREAMING_SNAKE_CASE_: Tuple =residx_atomaa_mask SCREAMING_SNAKE_CASE_: Dict =residx_atomaa_to_atomaa.long() # create the gather indices for mapping back SCREAMING_SNAKE_CASE_: Dict =restype_atomaa_to_atomaa[protein_aatype] SCREAMING_SNAKE_CASE_: Optional[int] =residx_atomaa_to_atomaa.long() # create the corresponding mask SCREAMING_SNAKE_CASE_: Optional[int] =torch.zeros([21, 37] , dtype=torch.floataa , device=protein["""aatype"""].device ) for restype, restype_letter in enumerate(rc.restypes ): SCREAMING_SNAKE_CASE_: int =rc.restype_atoa[restype_letter] SCREAMING_SNAKE_CASE_: Any =rc.residue_atoms[restype_name] for atom_name in atom_names: SCREAMING_SNAKE_CASE_: Optional[int] =rc.atom_order[atom_name] SCREAMING_SNAKE_CASE_: Dict =1 SCREAMING_SNAKE_CASE_: List[str] =restype_atomaa_mask[protein_aatype] SCREAMING_SNAKE_CASE_: List[Any] =residx_atomaa_mask return protein def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: Any =tree_map(lambda lowercase : torch.tensor(lowercase , device=batch["""aatype"""].device ) , lowercase , np.ndarray ) SCREAMING_SNAKE_CASE_: int =tensor_tree_map(lambda lowercase : np.array(lowercase ) , make_atomaa_masks(lowercase ) ) return out
36
1
"""simple docstring""" import logging import os from dataclasses import dataclass from typing import List, Optional, Union import tqdm from filelock import FileLock from transformers import ( BartTokenizer, BartTokenizerFast, DataProcessor, PreTrainedTokenizer, RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, is_tf_available, is_torch_available, ) _UpperCAmelCase = logging.getLogger(__name__) @dataclass(frozen=UpperCAmelCase__ ) class a : UpperCamelCase : str UpperCamelCase : str UpperCamelCase : Optional[str] = None UpperCamelCase : Optional[str] = None UpperCamelCase : Optional[str] = None @dataclass(frozen=UpperCAmelCase__ ) class a : UpperCamelCase : List[int] UpperCamelCase : Optional[List[int]] = None UpperCamelCase : Optional[List[int]] = None UpperCamelCase : Optional[Union[int, float]] = None UpperCamelCase : Optional[int] = None if is_torch_available(): import torch from torch.utils.data import Dataset class a ( UpperCAmelCase__ ): UpperCamelCase : List[InputFeatures] def __init__( self : Any , lowerCAmelCase : str , lowerCAmelCase : PreTrainedTokenizer , lowerCAmelCase : str , lowerCAmelCase : Optional[int] = None , lowerCAmelCase : str=False , lowerCAmelCase : bool = False , ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE_: str =hans_processors[task]() SCREAMING_SNAKE_CASE_: List[Any] =os.path.join( lowerCAmelCase , """cached_{}_{}_{}_{}""".format( """dev""" if evaluate else """train""" , tokenizer.__class__.__name__ , str(lowerCAmelCase ) , lowerCAmelCase , ) , ) SCREAMING_SNAKE_CASE_: List[str] =processor.get_labels() if tokenizer.__class__ in ( RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, BartTokenizer, BartTokenizerFast, ): # HACK(label indices are swapped in RoBERTa pretrained model) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[Any] =label_list[2], label_list[1] SCREAMING_SNAKE_CASE_: List[str] =label_list # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. SCREAMING_SNAKE_CASE_: List[Any] =cached_features_file + """.lock""" with FileLock(lowerCAmelCase ): if os.path.exists(lowerCAmelCase ) and not overwrite_cache: logger.info(f'''Loading features from cached file {cached_features_file}''' ) SCREAMING_SNAKE_CASE_: Any =torch.load(lowerCAmelCase ) else: logger.info(f'''Creating features from dataset file at {data_dir}''' ) SCREAMING_SNAKE_CASE_: Optional[Any] =( processor.get_dev_examples(lowerCAmelCase ) if evaluate else processor.get_train_examples(lowerCAmelCase ) ) logger.info("""Training examples: %s""" , len(lowerCAmelCase ) ) SCREAMING_SNAKE_CASE_: List[Any] =hans_convert_examples_to_features(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) logger.info("""Saving features into cached file %s""" , lowerCAmelCase ) torch.save(self.features , lowerCAmelCase ) def __len__( self : Any ) -> str: '''simple docstring''' return len(self.features ) def __getitem__( self : Any , lowerCAmelCase : Any ) -> InputFeatures: '''simple docstring''' return self.features[i] def lowerCamelCase__ ( self : str ) -> str: '''simple docstring''' return self.label_list if is_tf_available(): import tensorflow as tf class a : UpperCamelCase : List[InputFeatures] def __init__( self : Optional[Any] , lowerCAmelCase : str , lowerCAmelCase : PreTrainedTokenizer , lowerCAmelCase : str , lowerCAmelCase : Optional[int] = 128 , lowerCAmelCase : Tuple=False , lowerCAmelCase : bool = False , ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =hans_processors[task]() SCREAMING_SNAKE_CASE_: int =processor.get_labels() if tokenizer.__class__ in ( RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, BartTokenizer, BartTokenizerFast, ): # HACK(label indices are swapped in RoBERTa pretrained model) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[str] =label_list[2], label_list[1] SCREAMING_SNAKE_CASE_: Optional[Any] =label_list SCREAMING_SNAKE_CASE_: Tuple =processor.get_dev_examples(lowerCAmelCase ) if evaluate else processor.get_train_examples(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Any =hans_convert_examples_to_features(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) def gen(): for ex_index, ex in tqdm.tqdm(enumerate(self.features ) , desc="""convert examples to features""" ): if ex_index % 1_0000 == 0: logger.info("""Writing example %d of %d""" % (ex_index, len(lowerCAmelCase )) ) yield ( { "example_id": 0, "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label, ) SCREAMING_SNAKE_CASE_: int =tf.data.Dataset.from_generator( lowerCAmelCase , ( { """example_id""": tf.intaa, """input_ids""": tf.intaa, """attention_mask""": tf.intaa, """token_type_ids""": tf.intaa, }, tf.intaa, ) , ( { """example_id""": tf.TensorShape([] ), """input_ids""": tf.TensorShape([None, None] ), """attention_mask""": tf.TensorShape([None, None] ), """token_type_ids""": tf.TensorShape([None, None] ), }, tf.TensorShape([] ), ) , ) def lowerCamelCase__ ( self : Any ) -> Dict: '''simple docstring''' return self.dataset def __len__( self : str ) -> Dict: '''simple docstring''' return len(self.features ) def __getitem__( self : List[str] , lowerCAmelCase : Optional[Any] ) -> InputFeatures: '''simple docstring''' return self.features[i] def lowerCamelCase__ ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' return self.label_list class a ( UpperCAmelCase__ ): def lowerCamelCase__ ( self : str , lowerCAmelCase : List[Any] ) -> int: '''simple docstring''' return self._create_examples(self._read_tsv(os.path.join(lowerCAmelCase , """heuristics_train_set.txt""" ) ) , """train""" ) def lowerCamelCase__ ( self : int , lowerCAmelCase : Tuple ) -> Optional[Any]: '''simple docstring''' return self._create_examples(self._read_tsv(os.path.join(lowerCAmelCase , """heuristics_evaluation_set.txt""" ) ) , """dev""" ) def lowerCamelCase__ ( self : Optional[Any] ) -> Dict: '''simple docstring''' return ["contradiction", "entailment", "neutral"] def lowerCamelCase__ ( self : Dict , lowerCAmelCase : Dict , lowerCAmelCase : List[Any] ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE_: Union[str, Any] =[] for i, line in enumerate(lowerCAmelCase ): if i == 0: continue SCREAMING_SNAKE_CASE_: Dict ="""%s-%s""" % (set_type, line[0]) SCREAMING_SNAKE_CASE_: List[str] =line[5] SCREAMING_SNAKE_CASE_: List[Any] =line[6] SCREAMING_SNAKE_CASE_: Tuple =line[7][2:] if line[7].startswith("""ex""" ) else line[7] SCREAMING_SNAKE_CASE_: Union[str, Any] =line[0] examples.append(InputExample(guid=lowerCAmelCase , text_a=lowerCAmelCase , text_b=lowerCAmelCase , label=lowerCAmelCase , pairID=lowerCAmelCase ) ) return examples def __magic_name__ ( lowercase , lowercase , lowercase , lowercase , ): SCREAMING_SNAKE_CASE_: str ={label: i for i, label in enumerate(lowercase )} SCREAMING_SNAKE_CASE_: List[Any] =[] for ex_index, example in tqdm.tqdm(enumerate(lowercase ) , desc="""convert examples to features""" ): if ex_index % 1_0000 == 0: logger.info("""Writing example %d""" % (ex_index) ) SCREAMING_SNAKE_CASE_: List[Any] =tokenizer( example.text_a , example.text_b , add_special_tokens=lowercase , max_length=lowercase , padding="""max_length""" , truncation=lowercase , return_overflowing_tokens=lowercase , ) SCREAMING_SNAKE_CASE_: Union[str, Any] =label_map[example.label] if example.label in label_map else 0 SCREAMING_SNAKE_CASE_: str =int(example.pairID ) features.append(InputFeatures(**lowercase , label=lowercase , pairID=lowercase ) ) for i, example in enumerate(examples[:5] ): logger.info("""*** Example ***""" ) logger.info(f'''guid: {example}''' ) logger.info(f'''features: {features[i]}''' ) return features _UpperCAmelCase = { """hans""": 3, } _UpperCAmelCase = { """hans""": HansProcessor, }
36
"""simple docstring""" from pathlib import Path from typing import List from transformers import is_torch_available, is_vision_available from transformers.testing_utils import get_tests_dir, is_tool_test from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText if is_torch_available(): import torch if is_vision_available(): from PIL import Image _UpperCAmelCase = ["""text""", """image""", """audio"""] def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: str =[] for input_type in input_types: if input_type == "text": inputs.append("""Text input""" ) elif input_type == "image": inputs.append( Image.open(Path(get_tests_dir("""fixtures/tests_samples/COCO""" ) ) / """000000039769.png""" ).resize((512, 512) ) ) elif input_type == "audio": inputs.append(torch.ones(3000 ) ) elif isinstance(lowercase , lowercase ): inputs.append(create_inputs(lowercase ) ) else: raise ValueError(f'''Invalid type requested: {input_type}''' ) return inputs def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: int =[] for output in outputs: if isinstance(lowercase , (str, AgentText) ): output_types.append("""text""" ) elif isinstance(lowercase , (Image.Image, AgentImage) ): output_types.append("""image""" ) elif isinstance(lowercase , (torch.Tensor, AgentAudio) ): output_types.append("""audio""" ) else: raise ValueError(f'''Invalid output: {output}''' ) return output_types @is_tool_test class a : def lowerCamelCase__ ( self : Tuple ) -> List[Any]: '''simple docstring''' self.assertTrue(hasattr(self.tool , """inputs""" ) ) self.assertTrue(hasattr(self.tool , """outputs""" ) ) SCREAMING_SNAKE_CASE_: Optional[int] =self.tool.inputs for _input in inputs: if isinstance(_input , lowerCAmelCase ): for __input in _input: self.assertTrue(__input in authorized_types ) else: self.assertTrue(_input in authorized_types ) SCREAMING_SNAKE_CASE_: Any =self.tool.outputs for _output in outputs: self.assertTrue(_output in authorized_types ) def lowerCamelCase__ ( self : str ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =create_inputs(self.tool.inputs ) SCREAMING_SNAKE_CASE_: List[Any] =self.tool(*lowerCAmelCase ) # There is a single output if len(self.tool.outputs ) == 1: SCREAMING_SNAKE_CASE_: str =[outputs] self.assertListEqual(output_types(lowerCAmelCase ) , self.tool.outputs ) def lowerCamelCase__ ( self : str ) -> Optional[Any]: '''simple docstring''' self.assertTrue(hasattr(self.tool , """description""" ) ) self.assertTrue(hasattr(self.tool , """default_checkpoint""" ) ) self.assertTrue(self.tool.description.startswith("""This is a tool that""" ) ) def lowerCamelCase__ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: str =create_inputs(self.tool.inputs ) SCREAMING_SNAKE_CASE_: Tuple =self.tool(*lowerCAmelCase ) if not isinstance(lowerCAmelCase , lowerCAmelCase ): SCREAMING_SNAKE_CASE_: int =[outputs] self.assertEqual(len(lowerCAmelCase ) , len(self.tool.outputs ) ) for output, output_type in zip(lowerCAmelCase , self.tool.outputs ): SCREAMING_SNAKE_CASE_: int =AGENT_TYPE_MAPPING[output_type] self.assertTrue(isinstance(lowerCAmelCase , lowerCAmelCase ) ) def lowerCamelCase__ ( self : List[Any] ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =create_inputs(self.tool.inputs ) SCREAMING_SNAKE_CASE_: Union[str, Any] =[] for _input, input_type in zip(lowerCAmelCase , self.tool.inputs ): if isinstance(lowerCAmelCase , lowerCAmelCase ): _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input ) for _input_type in input_type] ) else: _inputs.append(AGENT_TYPE_MAPPING[input_type](_input ) ) # Should not raise an error SCREAMING_SNAKE_CASE_: Dict =self.tool(*lowerCAmelCase ) if not isinstance(lowerCAmelCase , lowerCAmelCase ): SCREAMING_SNAKE_CASE_: List[str] =[outputs] self.assertEqual(len(lowerCAmelCase ) , len(self.tool.outputs ) )
36
1
"""simple docstring""" from math import sqrt def __magic_name__ ( lowercase = 100_0000 ): SCREAMING_SNAKE_CASE_: int =0 SCREAMING_SNAKE_CASE_: int =0 SCREAMING_SNAKE_CASE_: int while num_cuboids <= limit: max_cuboid_size += 1 for sum_shortest_sides in range(2 , 2 * max_cuboid_size + 1 ): if sqrt(sum_shortest_sides**2 + max_cuboid_size**2 ).is_integer(): num_cuboids += ( min(lowercase , sum_shortest_sides // 2 ) - max(1 , sum_shortest_sides - max_cuboid_size ) + 1 ) return max_cuboid_size if __name__ == "__main__": print(f"""{solution() = }""")
36
"""simple docstring""" from __future__ import annotations def __magic_name__ ( lowercase , lowercase ): SCREAMING_SNAKE_CASE_: List[Any] =sorted(numsa + numsa ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Tuple =divmod(len(lowercase ) , 2 ) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() _UpperCAmelCase = [float(x) for x in input("""Enter the elements of first array: """).split()] _UpperCAmelCase = [float(x) for x in input("""Enter the elements of second array: """).split()] print(f"""The median of two arrays is: {median_of_two_arrays(array_a, array_a)}""")
36
1
"""simple docstring""" import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class a ( ctypes.Structure ): # _fields is a specific attr expected by ctypes UpperCamelCase : str = [('size', ctypes.c_int), ('visible', ctypes.c_byte)] def __magic_name__ ( ): if os.name == "nt": SCREAMING_SNAKE_CASE_: str =CursorInfo() SCREAMING_SNAKE_CASE_: int =ctypes.windll.kernelaa.GetStdHandle(-11 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(lowercase , ctypes.byref(lowercase ) ) SCREAMING_SNAKE_CASE_: Tuple =False ctypes.windll.kernelaa.SetConsoleCursorInfo(lowercase , ctypes.byref(lowercase ) ) elif os.name == "posix": sys.stdout.write("""\033[?25l""" ) sys.stdout.flush() def __magic_name__ ( ): if os.name == "nt": SCREAMING_SNAKE_CASE_: List[Any] =CursorInfo() SCREAMING_SNAKE_CASE_: Optional[int] =ctypes.windll.kernelaa.GetStdHandle(-11 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(lowercase , ctypes.byref(lowercase ) ) SCREAMING_SNAKE_CASE_: List[Any] =True ctypes.windll.kernelaa.SetConsoleCursorInfo(lowercase , ctypes.byref(lowercase ) ) elif os.name == "posix": sys.stdout.write("""\033[?25h""" ) sys.stdout.flush() @contextmanager def __magic_name__ ( ): try: hide_cursor() yield finally: show_cursor()
36
"""simple docstring""" import copy import inspect import unittest from transformers import PretrainedConfig, SwiftFormerConfig from transformers.testing_utils import ( require_torch, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwiftFormerForImageClassification, SwiftFormerModel from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class a : def __init__( self : Any , lowerCAmelCase : Any , lowerCAmelCase : List[str]=13 , lowerCAmelCase : Dict=3 , lowerCAmelCase : Optional[Any]=True , lowerCAmelCase : Dict=True , lowerCAmelCase : Dict=0.1 , lowerCAmelCase : str=0.1 , lowerCAmelCase : List[str]=224 , lowerCAmelCase : List[str]=1000 , lowerCAmelCase : Optional[Any]=[3, 3, 6, 4] , lowerCAmelCase : int=[48, 56, 112, 220] , ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[int] =parent SCREAMING_SNAKE_CASE_: Any =batch_size SCREAMING_SNAKE_CASE_: Tuple =num_channels SCREAMING_SNAKE_CASE_: Union[str, Any] =is_training SCREAMING_SNAKE_CASE_: Tuple =use_labels SCREAMING_SNAKE_CASE_: Optional[int] =hidden_dropout_prob SCREAMING_SNAKE_CASE_: Tuple =attention_probs_dropout_prob SCREAMING_SNAKE_CASE_: List[Any] =num_labels SCREAMING_SNAKE_CASE_: int =image_size SCREAMING_SNAKE_CASE_: Optional[Any] =layer_depths SCREAMING_SNAKE_CASE_: List[Any] =embed_dims def lowerCamelCase__ ( self : List[Any] ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[str] =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_: List[Any] =None if self.use_labels: SCREAMING_SNAKE_CASE_: List[str] =ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE_: Tuple =self.get_config() return config, pixel_values, labels def lowerCamelCase__ ( self : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' return SwiftFormerConfig( depths=self.layer_depths , embed_dims=self.embed_dims , mlp_ratio=4 , downsamples=[True, True, True, True] , hidden_act="""gelu""" , num_labels=self.num_labels , down_patch_size=3 , down_stride=2 , down_pad=1 , drop_rate=0.0 , drop_path_rate=0.0 , use_layer_scale=lowerCAmelCase , layer_scale_init_value=1E-5 , ) def lowerCamelCase__ ( self : Any , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Optional[Any] , lowerCAmelCase : Optional[int] ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[str] =SwiftFormerModel(config=lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() SCREAMING_SNAKE_CASE_: Any =model(lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dims[-1], 7, 7) ) def lowerCamelCase__ ( self : Union[str, Any] , lowerCAmelCase : List[Any] , lowerCAmelCase : Optional[int] , lowerCAmelCase : Union[str, Any] ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[Any] =self.num_labels SCREAMING_SNAKE_CASE_: Dict =SwiftFormerForImageClassification(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() SCREAMING_SNAKE_CASE_: Dict =model(lowerCAmelCase , labels=lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) SCREAMING_SNAKE_CASE_: int =SwiftFormerForImageClassification(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() SCREAMING_SNAKE_CASE_: Tuple =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_: Dict =model(lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase__ ( self : int ) -> Optional[Any]: '''simple docstring''' ((SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_)): str =self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_: Tuple ={"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class a ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): UpperCamelCase : Optional[int] = (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else () UpperCamelCase : Tuple = ( {'feature-extraction': SwiftFormerModel, 'image-classification': SwiftFormerForImageClassification} if is_torch_available() else {} ) UpperCamelCase : Any = False UpperCamelCase : Optional[int] = False UpperCamelCase : Optional[Any] = False UpperCamelCase : Dict = False UpperCamelCase : List[str] = False def lowerCamelCase__ ( self : Dict ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =SwiftFormerModelTester(self ) SCREAMING_SNAKE_CASE_: Union[str, Any] =ConfigTester( self , config_class=lowerCAmelCase , has_text_modality=lowerCAmelCase , hidden_size=37 , num_attention_heads=12 , num_hidden_layers=12 , ) def lowerCamelCase__ ( self : Tuple ) -> int: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="""SwiftFormer does not use inputs_embeds""" ) def lowerCamelCase__ ( self : Tuple ) -> List[str]: '''simple docstring''' pass def lowerCamelCase__ ( self : Optional[int] ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[str] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_: Any =model_class(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[Any] =model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCAmelCase , nn.Linear ) ) def lowerCamelCase__ ( self : str ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[Any] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_: int =model_class(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[Any] =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE_: Any =[*signature.parameters.keys()] SCREAMING_SNAKE_CASE_: Tuple =["""pixel_values"""] self.assertListEqual(arg_names[:1] , lowerCAmelCase ) def lowerCamelCase__ ( self : int ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase ) def lowerCamelCase__ ( self : Any ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: int =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase ) @slow def lowerCamelCase__ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_: Optional[Any] =SwiftFormerModel.from_pretrained(lowerCAmelCase ) self.assertIsNotNone(lowerCAmelCase ) @unittest.skip(reason="""SwiftFormer does not output attentions""" ) def lowerCamelCase__ ( self : Optional[int] ) -> str: '''simple docstring''' pass def lowerCamelCase__ ( self : List[Any] ) -> List[str]: '''simple docstring''' def check_hidden_states_output(lowerCAmelCase : Optional[int] , lowerCAmelCase : str , lowerCAmelCase : Optional[int] ): SCREAMING_SNAKE_CASE_: Optional[Any] =model_class(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_: List[str] =model(**self._prepare_for_class(lowerCAmelCase , lowerCAmelCase ) ) SCREAMING_SNAKE_CASE_: Dict =outputs.hidden_states SCREAMING_SNAKE_CASE_: List[Any] =8 self.assertEqual(len(lowerCAmelCase ) , lowerCAmelCase ) # TODO # SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width) # with the width and height being successively divided by 2, after every 2 blocks for i in range(len(lowerCAmelCase ) ): self.assertEqual( hidden_states[i].shape , torch.Size( [ self.model_tester.batch_size, self.model_tester.embed_dims[i // 2], (self.model_tester.image_size // 4) // 2 ** (i // 2), (self.model_tester.image_size // 4) // 2 ** (i // 2), ] ) , ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: int =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_: Dict =True check_hidden_states_output(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE_: Any =True check_hidden_states_output(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) def lowerCamelCase__ ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' def _config_zero_init(lowerCAmelCase : str ): SCREAMING_SNAKE_CASE_: Dict =copy.deepcopy(lowerCAmelCase ) for key in configs_no_init.__dict__.keys(): if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key: setattr(lowerCAmelCase , lowerCAmelCase , 1E-10 ) if isinstance(getattr(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) , lowerCAmelCase ): SCREAMING_SNAKE_CASE_: Tuple =_config_zero_init(getattr(lowerCAmelCase , lowerCAmelCase ) ) setattr(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) return configs_no_init SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[Any] =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_: List[Any] =_config_zero_init(lowerCAmelCase ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_: Any =model_class(config=lowerCAmelCase ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1E9) / 1E9).round().item() , [0.0, 1.0] , msg=f'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def lowerCamelCase__ ( self : List[str] ) -> List[str]: '''simple docstring''' pass def __magic_name__ ( ): SCREAMING_SNAKE_CASE_: List[Any] =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class a ( unittest.TestCase ): @cached_property def lowerCamelCase__ ( self : str ) -> str: '''simple docstring''' return ViTImageProcessor.from_pretrained("""MBZUAI/swiftformer-xs""" ) if is_vision_available() else None @slow def lowerCamelCase__ ( self : Union[str, Any] ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: str =SwiftFormerForImageClassification.from_pretrained("""MBZUAI/swiftformer-xs""" ).to(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: str =self.default_image_processor SCREAMING_SNAKE_CASE_: int =prepare_img() SCREAMING_SNAKE_CASE_: Union[str, Any] =image_processor(images=lowerCAmelCase , return_tensors="""pt""" ).to(lowerCAmelCase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_: Dict =model(**lowerCAmelCase ) # verify the logits SCREAMING_SNAKE_CASE_: Optional[Any] =torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =torch.tensor([[-2.1_703E00, 2.1_107E00, -2.0_811E00]] ).to(lowerCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCAmelCase , atol=1E-4 ) )
36
1
"""simple docstring""" 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 _UpperCAmelCase = logging.get_logger(__name__) # pylint: disable=invalid-name class a ( UpperCAmelCase__ ): def __init__( self : int , lowerCAmelCase : CLIPSegForImageSegmentation , lowerCAmelCase : CLIPSegProcessor , lowerCAmelCase : AutoencoderKL , lowerCAmelCase : CLIPTextModel , lowerCAmelCase : CLIPTokenizer , lowerCAmelCase : UNetaDConditionModel , lowerCAmelCase : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , lowerCAmelCase : StableDiffusionSafetyChecker , lowerCAmelCase : CLIPImageProcessor , ) -> Any: '''simple docstring''' super().__init__() if hasattr(scheduler.config , """steps_offset""" ) and scheduler.config.steps_offset != 1: SCREAMING_SNAKE_CASE_: Optional[int] =( 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""" , lowerCAmelCase , standard_warn=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[Any] =dict(scheduler.config ) SCREAMING_SNAKE_CASE_: int =1 SCREAMING_SNAKE_CASE_: Any =FrozenDict(lowerCAmelCase ) if hasattr(scheduler.config , """skip_prk_steps""" ) and scheduler.config.skip_prk_steps is False: SCREAMING_SNAKE_CASE_: int =( 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""" , lowerCAmelCase , standard_warn=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[Any] =dict(scheduler.config ) SCREAMING_SNAKE_CASE_: Any =True SCREAMING_SNAKE_CASE_: List[Any] =FrozenDict(lowerCAmelCase ) 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=lowerCAmelCase , segmentation_processor=lowerCAmelCase , vae=lowerCAmelCase , text_encoder=lowerCAmelCase , tokenizer=lowerCAmelCase , unet=lowerCAmelCase , scheduler=lowerCAmelCase , safety_checker=lowerCAmelCase , feature_extractor=lowerCAmelCase , ) def lowerCamelCase__ ( self : Optional[int] , lowerCAmelCase : Optional[Union[str, int]] = "auto" ) -> Union[str, Any]: '''simple docstring''' if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory SCREAMING_SNAKE_CASE_: Dict =self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(lowerCAmelCase ) def lowerCamelCase__ ( self : str ) -> List[Any]: '''simple docstring''' self.enable_attention_slicing(lowerCAmelCase ) def lowerCamelCase__ ( self : Any ) -> List[Any]: '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) SCREAMING_SNAKE_CASE_: List[Any] =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(lowerCAmelCase , lowerCAmelCase ) @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def lowerCamelCase__ ( self : Any ) -> Union[str, Any]: '''simple docstring''' if self.device != torch.device("""meta""" ) or not hasattr(self.unet , """_hf_hook""" ): return self.device for module in self.unet.modules(): if ( hasattr(lowerCAmelCase , """_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 : Tuple , lowerCAmelCase : Union[str, List[str]] , lowerCAmelCase : Union[torch.FloatTensor, PIL.Image.Image] , lowerCAmelCase : str , lowerCAmelCase : int = 512 , lowerCAmelCase : int = 512 , lowerCAmelCase : int = 50 , lowerCAmelCase : float = 7.5 , lowerCAmelCase : Optional[Union[str, List[str]]] = None , lowerCAmelCase : Optional[int] = 1 , lowerCAmelCase : float = 0.0 , lowerCAmelCase : Optional[torch.Generator] = None , lowerCAmelCase : Optional[torch.FloatTensor] = None , lowerCAmelCase : Optional[str] = "pil" , lowerCAmelCase : bool = True , lowerCAmelCase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , lowerCAmelCase : int = 1 , **lowerCAmelCase : str , ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[int] =self.segmentation_processor( text=[text] , images=[image] , padding="""max_length""" , return_tensors="""pt""" ).to(self.device ) SCREAMING_SNAKE_CASE_: List[str] =self.segmentation_model(**lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Any =torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy() SCREAMING_SNAKE_CASE_: Any =self.numpy_to_pil(lowerCAmelCase )[0].resize(image.size ) # Run inpainting pipeline with the generated mask SCREAMING_SNAKE_CASE_: List[Any] =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=lowerCAmelCase , image=lowerCAmelCase , mask_image=lowerCAmelCase , height=lowerCAmelCase , width=lowerCAmelCase , num_inference_steps=lowerCAmelCase , guidance_scale=lowerCAmelCase , negative_prompt=lowerCAmelCase , num_images_per_prompt=lowerCAmelCase , eta=lowerCAmelCase , generator=lowerCAmelCase , latents=lowerCAmelCase , output_type=lowerCAmelCase , return_dict=lowerCAmelCase , callback=lowerCAmelCase , callback_steps=lowerCAmelCase , )
36
"""simple docstring""" from math import pi def __magic_name__ ( lowercase , lowercase ): return 2 * pi * radius * (angle / 360) if __name__ == "__main__": print(arc_length(9_0, 1_0))
36
1