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''' from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __A = {'''configuration_van''': ['''VAN_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''VanConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ '''VAN_PRETRAINED_MODEL_ARCHIVE_LIST''', '''VanForImageClassification''', '''VanModel''', '''VanPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_van import VAN_PRETRAINED_CONFIG_ARCHIVE_MAP, VanConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_van import ( VAN_PRETRAINED_MODEL_ARCHIVE_LIST, VanForImageClassification, VanModel, VanPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
61
'''simple docstring''' from __future__ import annotations from collections import deque from collections.abc import Sequence from dataclasses import dataclass from typing import Any @dataclass class a_ : _snake_case = 42 _snake_case = None _snake_case = None def _SCREAMING_SNAKE_CASE ( ) -> Node | None: """simple docstring""" __snake_case : str = Node(1 ) __snake_case : Tuple = Node(2 ) __snake_case : Optional[int] = Node(3 ) __snake_case : List[str] = Node(4 ) __snake_case : List[str] = Node(5 ) return tree def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> list[int]: """simple docstring""" return [root.data, *preorder(root.left ), *preorder(root.right )] if root else [] def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> list[int]: """simple docstring""" return postorder(root.left ) + postorder(root.right ) + [root.data] if root else [] def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> list[int]: """simple docstring""" return [*inorder(root.left ), root.data, *inorder(root.right )] if root else [] def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> int: """simple docstring""" return (max(height(root.left ) , height(root.right ) ) + 1) if root else 0 def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> Sequence[Node | None]: """simple docstring""" __snake_case : list[Any] = [] if root is None: return output __snake_case : Optional[int] = deque([root] ) while process_queue: __snake_case : List[str] = process_queue.popleft() output.append(node.data ) if node.left: process_queue.append(node.left ) if node.right: process_queue.append(node.right ) return output def _SCREAMING_SNAKE_CASE ( A : Node | None , A : int ) -> Sequence[Node | None]: """simple docstring""" __snake_case : list[Any] = [] def populate_output(A : Node | None , A : int ) -> None: if not root: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.left , level - 1 ) populate_output(root.right , level - 1 ) populate_output(A , A ) return output def _SCREAMING_SNAKE_CASE ( A : Node | None , A : int ) -> Sequence[Node | None]: """simple docstring""" __snake_case : list[Any] = [] def populate_output(A : Node | None , A : int ) -> None: if root is None: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.right , level - 1 ) populate_output(root.left , level - 1 ) populate_output(A , A ) return output def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> Sequence[Node | None] | list[Any]: """simple docstring""" if root is None: return [] __snake_case : list[Sequence[Node | None]] = [] __snake_case : List[Any] = 0 __snake_case : int = height(A ) for h in range(1 , height_tree + 1 ): if not flag: output.append(get_nodes_from_left_to_right(A , A ) ) __snake_case : int = 1 else: output.append(get_nodes_from_right_to_left(A , A ) ) __snake_case : Tuple = 0 return output def _SCREAMING_SNAKE_CASE ( ) -> None: # Main function for testing. """simple docstring""" __snake_case : Optional[int] = make_tree() print(F"""In-order Traversal: {inorder(A )}""" ) print(F"""Pre-order Traversal: {preorder(A )}""" ) print(F"""Post-order Traversal: {postorder(A )}""" , '\n' ) print(F"""Height of Tree: {height(A )}""" , '\n' ) print('Complete Level Order Traversal: ' ) print(level_order(A ) , '\n' ) print('Level-wise order Traversal: ' ) for level in range(1 , height(A ) + 1 ): print(F"""Level {level}:""" , get_nodes_from_left_to_right(A , level=A ) ) print('\nZigZag order Traversal: ' ) print(zigzag(A ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
61
1
'''simple docstring''' import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DetaImageProcessor class a_ ( unittest.TestCase ): def __init__(self , __a , __a=7 , __a=3 , __a=3_0 , __a=4_0_0 , __a=True , __a=None , __a=True , __a=[0.5, 0.5, 0.5] , __a=[0.5, 0.5, 0.5] , __a=True , __a=1 / 2_5_5 , __a=True , ) -> Optional[int]: """simple docstring""" __snake_case : Union[str, Any] = size if size is not None else {'shortest_edge': 1_8, 'longest_edge': 1_3_3_3} __snake_case : Tuple = parent __snake_case : Any = batch_size __snake_case : Union[str, Any] = num_channels __snake_case : str = min_resolution __snake_case : Tuple = max_resolution __snake_case : List[str] = do_resize __snake_case : int = size __snake_case : Optional[Any] = do_normalize __snake_case : Any = image_mean __snake_case : Any = image_std __snake_case : Optional[Any] = do_rescale __snake_case : Optional[Any] = rescale_factor __snake_case : List[str] = do_pad def SCREAMING_SNAKE_CASE__ (self) -> Any: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def SCREAMING_SNAKE_CASE__ (self , __a , __a=False) -> Any: """simple docstring""" if not batched: __snake_case : List[str] = image_inputs[0] if isinstance(__a , Image.Image): __snake_case ,__snake_case : Tuple = image.size else: __snake_case ,__snake_case : str = image.shape[1], image.shape[2] if w < h: __snake_case : List[Any] = int(self.size['shortest_edge'] * h / w) __snake_case : List[Any] = self.size['shortest_edge'] elif w > h: __snake_case : Optional[Any] = self.size['shortest_edge'] __snake_case : List[str] = int(self.size['shortest_edge'] * w / h) else: __snake_case : Any = self.size['shortest_edge'] __snake_case : str = self.size['shortest_edge'] else: __snake_case : List[Any] = [] for image in image_inputs: __snake_case ,__snake_case : List[Any] = self.get_expected_values([image]) expected_values.append((expected_height, expected_width)) __snake_case : Optional[Any] = max(__a , key=lambda __a: item[0])[0] __snake_case : int = max(__a , key=lambda __a: item[1])[1] return expected_height, expected_width @require_torch @require_vision class a_ ( UpperCamelCase_ , unittest.TestCase ): _snake_case = DetaImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : Optional[Any] = DetaImageProcessingTester(self) @property def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" __snake_case : str = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(__a , 'image_mean')) self.assertTrue(hasattr(__a , 'image_std')) self.assertTrue(hasattr(__a , 'do_normalize')) self.assertTrue(hasattr(__a , 'do_resize')) self.assertTrue(hasattr(__a , 'do_rescale')) self.assertTrue(hasattr(__a , 'do_pad')) self.assertTrue(hasattr(__a , 'size')) def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size , {'shortest_edge': 1_8, 'longest_edge': 1_3_3_3}) self.assertEqual(image_processor.do_pad , __a) def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : Optional[int] = self.image_processing_class(**self.image_processor_dict) # create random PIL images __snake_case : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a) for image in image_inputs: self.assertIsInstance(__a , Image.Image) # Test not batched input __snake_case : List[str] = image_processing(image_inputs[0] , return_tensors='pt').pixel_values __snake_case ,__snake_case : Any = self.image_processor_tester.get_expected_values(__a) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __snake_case ,__snake_case : List[Any] = self.image_processor_tester.get_expected_values(__a , batched=__a) __snake_case : List[Any] = image_processing(__a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE__ (self) -> Tuple: """simple docstring""" __snake_case : Union[str, Any] = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors __snake_case : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a , numpify=__a) for image in image_inputs: self.assertIsInstance(__a , np.ndarray) # Test not batched input __snake_case : str = image_processing(image_inputs[0] , return_tensors='pt').pixel_values __snake_case ,__snake_case : List[str] = self.image_processor_tester.get_expected_values(__a) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __snake_case : Any = image_processing(__a , return_tensors='pt').pixel_values __snake_case ,__snake_case : List[str] = self.image_processor_tester.get_expected_values(__a , batched=__a) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" __snake_case : str = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors __snake_case : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a , torchify=__a) for image in image_inputs: self.assertIsInstance(__a , torch.Tensor) # Test not batched input __snake_case : List[str] = image_processing(image_inputs[0] , return_tensors='pt').pixel_values __snake_case ,__snake_case : Optional[Any] = self.image_processor_tester.get_expected_values(__a) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __snake_case : Any = image_processing(__a , return_tensors='pt').pixel_values __snake_case ,__snake_case : str = self.image_processor_tester.get_expected_values(__a , batched=__a) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" __snake_case : Optional[int] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png') with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r') as f: __snake_case : Optional[int] = json.loads(f.read()) __snake_case : str = {'image_id': 3_9_7_6_9, 'annotations': target} # encode them __snake_case : List[Any] = DetaImageProcessor() __snake_case : Optional[Any] = image_processing(images=__a , annotations=__a , return_tensors='pt') # verify pixel values __snake_case : Union[str, Any] = torch.Size([1, 3, 8_0_0, 1_0_6_6]) self.assertEqual(encoding['pixel_values'].shape , __a) __snake_case : List[str] = torch.tensor([0.2_796, 0.3_138, 0.3_481]) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , __a , atol=1E-4)) # verify area __snake_case : Optional[int] = torch.tensor([5_887.9_600, 11_250.2_061, 489_353.8_438, 837_122.7_500, 147_967.5_156, 165_732.3_438]) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , __a)) # verify boxes __snake_case : Any = torch.Size([6, 4]) self.assertEqual(encoding['labels'][0]['boxes'].shape , __a) __snake_case : str = torch.tensor([0.5_503, 0.2_765, 0.0_604, 0.2_215]) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , __a , atol=1E-3)) # verify image_id __snake_case : List[str] = torch.tensor([3_9_7_6_9]) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , __a)) # verify is_crowd __snake_case : Optional[Any] = torch.tensor([0, 0, 0, 0, 0, 0]) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , __a)) # verify class_labels __snake_case : Optional[Any] = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7]) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , __a)) # verify orig_size __snake_case : Dict = torch.tensor([4_8_0, 6_4_0]) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , __a)) # verify size __snake_case : Dict = torch.tensor([8_0_0, 1_0_6_6]) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , __a)) @slow def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : Tuple = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png') with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r') as f: __snake_case : List[Any] = json.loads(f.read()) __snake_case : List[str] = {'file_name': '000000039769.png', 'image_id': 3_9_7_6_9, 'segments_info': target} __snake_case : int = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic') # encode them __snake_case : Union[str, Any] = DetaImageProcessor(format='coco_panoptic') __snake_case : Dict = image_processing(images=__a , annotations=__a , masks_path=__a , return_tensors='pt') # verify pixel values __snake_case : List[Any] = torch.Size([1, 3, 8_0_0, 1_0_6_6]) self.assertEqual(encoding['pixel_values'].shape , __a) __snake_case : List[str] = torch.tensor([0.2_796, 0.3_138, 0.3_481]) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , __a , atol=1E-4)) # verify area __snake_case : Dict = torch.tensor([147_979.6_875, 165_527.0_469, 484_638.5_938, 11_292.9_375, 5_879.6_562, 7_634.1_147]) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , __a)) # verify boxes __snake_case : Tuple = torch.Size([6, 4]) self.assertEqual(encoding['labels'][0]['boxes'].shape , __a) __snake_case : Tuple = torch.tensor([0.2_625, 0.5_437, 0.4_688, 0.8_625]) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , __a , atol=1E-3)) # verify image_id __snake_case : Dict = torch.tensor([3_9_7_6_9]) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , __a)) # verify is_crowd __snake_case : Tuple = torch.tensor([0, 0, 0, 0, 0, 0]) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , __a)) # verify class_labels __snake_case : Optional[Any] = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3]) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , __a)) # verify masks __snake_case : Optional[int] = 8_2_2_8_7_3 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , __a) # verify orig_size __snake_case : Optional[int] = torch.tensor([4_8_0, 6_4_0]) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , __a)) # verify size __snake_case : Tuple = torch.tensor([8_0_0, 1_0_6_6]) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , __a))
61
'''simple docstring''' from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class a_ : def __init__(self , __a = None) -> None: """simple docstring""" if components is None: __snake_case : List[str] = [] __snake_case : Optional[int] = list(__a) def __len__(self) -> int: """simple docstring""" return len(self.__components) def __str__(self) -> str: """simple docstring""" return "(" + ",".join(map(__a , self.__components)) + ")" def __add__(self , __a) -> Vector: """simple docstring""" __snake_case : Optional[Any] = len(self) if size == len(__a): __snake_case : Optional[int] = [self.__components[i] + other.component(__a) for i in range(__a)] return Vector(__a) else: raise Exception('must have the same size') def __sub__(self , __a) -> Vector: """simple docstring""" __snake_case : Optional[Any] = len(self) if size == len(__a): __snake_case : Optional[int] = [self.__components[i] - other.component(__a) for i in range(__a)] return Vector(__a) else: # error case raise Exception('must have the same size') @overload def __mul__(self , __a) -> Vector: """simple docstring""" ... @overload def __mul__(self , __a) -> float: """simple docstring""" ... def __mul__(self , __a) -> float | Vector: """simple docstring""" if isinstance(__a , (float, int)): __snake_case : str = [c * other for c in self.__components] return Vector(__a) elif isinstance(__a , __a) and len(self) == len(__a): __snake_case : List[Any] = len(self) __snake_case : Dict = [self.__components[i] * other.component(__a) for i in range(__a)] return sum(__a) else: # error case raise Exception('invalid operand!') def SCREAMING_SNAKE_CASE__ (self) -> Vector: """simple docstring""" return Vector(self.__components) def SCREAMING_SNAKE_CASE__ (self , __a) -> float: """simple docstring""" if isinstance(__a , __a) and -len(self.__components) <= i < len(self.__components): return self.__components[i] else: raise Exception('index out of range') def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> None: """simple docstring""" assert -len(self.__components) <= pos < len(self.__components) __snake_case : int = value def SCREAMING_SNAKE_CASE__ (self) -> float: """simple docstring""" if len(self.__components) == 0: raise Exception('Vector is empty') __snake_case : Tuple = [c**2 for c in self.__components] return math.sqrt(sum(__a)) def SCREAMING_SNAKE_CASE__ (self , __a , __a = False) -> float: """simple docstring""" __snake_case : Tuple = self * other __snake_case : Optional[int] = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den)) else: return math.acos(num / den) def _SCREAMING_SNAKE_CASE ( A : int ) -> Vector: """simple docstring""" assert isinstance(A , A ) return Vector([0] * dimension ) def _SCREAMING_SNAKE_CASE ( A : int , A : int ) -> Vector: """simple docstring""" assert isinstance(A , A ) and (isinstance(A , A )) __snake_case : Any = [0] * dimension __snake_case : int = 1 return Vector(A ) def _SCREAMING_SNAKE_CASE ( A : float , A : Vector , A : Vector ) -> Vector: """simple docstring""" assert ( isinstance(A , A ) and isinstance(A , A ) and (isinstance(A , (int, float) )) ) return x * scalar + y def _SCREAMING_SNAKE_CASE ( A : int , A : int , A : int ) -> Vector: """simple docstring""" random.seed(A ) __snake_case : List[Any] = [random.randint(A , A ) for _ in range(A )] return Vector(A ) class a_ : def __init__(self , __a , __a , __a) -> None: """simple docstring""" __snake_case : Union[str, Any] = matrix __snake_case : int = w __snake_case : str = h def __str__(self) -> str: """simple docstring""" __snake_case : Dict = '' for i in range(self.__height): ans += "|" for j in range(self.__width): if j < self.__width - 1: ans += str(self.__matrix[i][j]) + "," else: ans += str(self.__matrix[i][j]) + "|\n" return ans def __add__(self , __a) -> Matrix: """simple docstring""" if self.__width == other.width() and self.__height == other.height(): __snake_case : Tuple = [] for i in range(self.__height): __snake_case : List[Any] = [ self.__matrix[i][j] + other.component(__a , __a) for j in range(self.__width) ] matrix.append(__a) return Matrix(__a , self.__width , self.__height) else: raise Exception('matrix must have the same dimension!') def __sub__(self , __a) -> Matrix: """simple docstring""" if self.__width == other.width() and self.__height == other.height(): __snake_case : str = [] for i in range(self.__height): __snake_case : List[str] = [ self.__matrix[i][j] - other.component(__a , __a) for j in range(self.__width) ] matrix.append(__a) return Matrix(__a , self.__width , self.__height) else: raise Exception('matrices must have the same dimension!') @overload def __mul__(self , __a) -> Matrix: """simple docstring""" ... @overload def __mul__(self , __a) -> Vector: """simple docstring""" ... def __mul__(self , __a) -> Vector | Matrix: """simple docstring""" if isinstance(__a , __a): # matrix-vector if len(__a) == self.__width: __snake_case : Tuple = zero_vector(self.__height) for i in range(self.__height): __snake_case : Union[str, Any] = [ self.__matrix[i][j] * other.component(__a) for j in range(self.__width) ] ans.change_component(__a , sum(__a)) return ans else: raise Exception( 'vector must have the same size as the ' 'number of columns of the matrix!') elif isinstance(__a , (int, float)): # matrix-scalar __snake_case : str = [ [self.__matrix[i][j] * other for j in range(self.__width)] for i in range(self.__height) ] return Matrix(__a , self.__width , self.__height) return None def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" return self.__height def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" return self.__width def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> float: """simple docstring""" if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception('change_component: indices out of bounds') def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> None: """simple docstring""" if 0 <= x < self.__height and 0 <= y < self.__width: __snake_case : List[Any] = value else: raise Exception('change_component: indices out of bounds') def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> float: """simple docstring""" if self.__height != self.__width: raise Exception('Matrix is not square') __snake_case : List[Any] = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(__a)): __snake_case : Tuple = minor[i][:y] + minor[i][y + 1 :] return Matrix(__a , self.__width - 1 , self.__height - 1).determinant() def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> float: """simple docstring""" if self.__height != self.__width: raise Exception('Matrix is not square') if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(__a , __a) else: raise Exception('Indices out of bounds') def SCREAMING_SNAKE_CASE__ (self) -> float: """simple docstring""" if self.__height != self.__width: raise Exception('Matrix is not square') if self.__height < 1: raise Exception('Matrix has no element') elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: __snake_case : Any = [ self.__matrix[0][y] * self.cofactor(0 , __a) for y in range(self.__width) ] return sum(__a) def _SCREAMING_SNAKE_CASE ( A : int ) -> Matrix: """simple docstring""" __snake_case : list[list[float]] = [[0] * n for _ in range(A )] return Matrix(A , A , A ) def _SCREAMING_SNAKE_CASE ( A : int , A : int , A : int , A : int ) -> Matrix: """simple docstring""" random.seed(A ) __snake_case : list[list[float]] = [ [random.randint(A , A ) for _ in range(A )] for _ in range(A ) ] return Matrix(A , A , A )
61
1
'''simple docstring''' from __future__ import annotations __A = '''#''' class a_ : def __init__(self) -> None: """simple docstring""" __snake_case : dict = {} def SCREAMING_SNAKE_CASE__ (self , __a) -> None: """simple docstring""" __snake_case : Optional[int] = self._trie for char in text: if char not in trie: __snake_case : str = {} __snake_case : Tuple = trie[char] __snake_case : int = True def SCREAMING_SNAKE_CASE__ (self , __a) -> tuple | list: """simple docstring""" __snake_case : Optional[Any] = self._trie for char in prefix: if char in trie: __snake_case : str = trie[char] else: return [] return self._elements(__a) def SCREAMING_SNAKE_CASE__ (self , __a) -> tuple: """simple docstring""" __snake_case : Union[str, Any] = [] for c, v in d.items(): __snake_case : List[str] = [' '] if c == END else [(c + s) for s in self._elements(__a)] result.extend(__a) return tuple(__a) __A = Trie() __A = ('''depart''', '''detergent''', '''daring''', '''dog''', '''deer''', '''deal''') for word in words: trie.insert_word(word) def _SCREAMING_SNAKE_CASE ( A : str ) -> tuple: """simple docstring""" __snake_case : int = trie.find_word(A ) return tuple(string + word for word in suffixes ) def _SCREAMING_SNAKE_CASE ( ) -> None: """simple docstring""" print(autocomplete_using_trie('de' ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
61
'''simple docstring''' import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification if is_tf_available(): from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification if is_flax_available(): from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification __A = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co __A = '''main''' # Default branch name __A = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2''' # One particular commit (not the top of `main`) __A = '''aaaaaaa''' # This commit does not exist, so we should 404. __A = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684''' # Sha-1 of config.json on the top of `main`, for checking purposes __A = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3''' @contextlib.contextmanager def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: """simple docstring""" print('Welcome!' ) yield print('Bye!' ) @contextlib.contextmanager def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]: """simple docstring""" print('Bonjour!' ) yield print('Au revoir!' ) class a_ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" assert transformers.__spec__ is not None assert importlib.util.find_spec('transformers') is not None class a_ ( unittest.TestCase ): @unittest.mock.patch('sys.stdout' , new_callable=io.StringIO) def SCREAMING_SNAKE_CASE__ (self , __a) -> int: """simple docstring""" with ContextManagers([]): print('Transformers are awesome!') # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue() , 'Transformers are awesome!\n') @unittest.mock.patch('sys.stdout' , new_callable=io.StringIO) def SCREAMING_SNAKE_CASE__ (self , __a) -> List[str]: """simple docstring""" with ContextManagers([context_en()]): print('Transformers are awesome!') # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue() , 'Welcome!\nTransformers are awesome!\nBye!\n') @unittest.mock.patch('sys.stdout' , new_callable=io.StringIO) def SCREAMING_SNAKE_CASE__ (self , __a) -> Tuple: """simple docstring""" with ContextManagers([context_fr(), context_en()]): print('Transformers are awesome!') # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue() , 'Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n') @require_torch def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" self.assertEqual(find_labels(__a) , ['labels']) self.assertEqual(find_labels(__a) , ['labels', 'next_sentence_label']) self.assertEqual(find_labels(__a) , ['start_positions', 'end_positions']) class a_ ( UpperCamelCase_ ): pass self.assertEqual(find_labels(__a) , ['labels']) @require_tf def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" self.assertEqual(find_labels(__a) , ['labels']) self.assertEqual(find_labels(__a) , ['labels', 'next_sentence_label']) self.assertEqual(find_labels(__a) , ['start_positions', 'end_positions']) class a_ ( UpperCamelCase_ ): pass self.assertEqual(find_labels(__a) , ['labels']) @require_flax def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" self.assertEqual(find_labels(__a) , []) self.assertEqual(find_labels(__a) , []) self.assertEqual(find_labels(__a) , []) class a_ ( UpperCamelCase_ ): pass self.assertEqual(find_labels(__a) , [])
61
1
'''simple docstring''' import math class a_ : def __init__(self , __a=0) -> Any: # a graph with Node 0,1,...,N-1 """simple docstring""" __snake_case : List[str] = n __snake_case : Tuple = [ [math.inf for j in range(0 , __a)] for i in range(0 , __a) ] # adjacency matrix for weight __snake_case : Union[str, Any] = [ [math.inf for j in range(0 , __a)] for i in range(0 , __a) ] # dp[i][j] stores minimum distance from i to j def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Tuple: """simple docstring""" __snake_case : Union[str, Any] = w def SCREAMING_SNAKE_CASE__ (self) -> Tuple: """simple docstring""" for k in range(0 , self.n): for i in range(0 , self.n): for j in range(0 , self.n): __snake_case : List[Any] = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j]) def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> Optional[int]: """simple docstring""" return self.dp[u][v] if __name__ == "__main__": __A = Graph(5) graph.add_edge(0, 2, 9) graph.add_edge(0, 4, 1_0) graph.add_edge(1, 3, 5) graph.add_edge(2, 3, 7) graph.add_edge(3, 0, 1_0) graph.add_edge(3, 1, 2) graph.add_edge(3, 2, 1) graph.add_edge(3, 4, 6) graph.add_edge(4, 1, 3) graph.add_edge(4, 2, 4) graph.add_edge(4, 3, 9) graph.floyd_warshall() graph.show_min(1, 4) graph.show_min(0, 3)
61
'''simple docstring''' # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A = {'''configuration_timm_backbone''': ['''TimmBackboneConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ['''TimmBackbone'''] if TYPE_CHECKING: from .configuration_timm_backbone import TimmBackboneConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timm_backbone import TimmBackbone else: import sys __A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
61
1
'''simple docstring''' import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL __A = logging.get_logger(__name__) def _SCREAMING_SNAKE_CASE ( A : np.ndarray , A : Union[int, Iterable[int]] , A : bool , A : int ) -> Tuple[int, int]: """simple docstring""" def constraint_to_multiple_of(A : Any , A : Optional[Any] , A : List[Any]=0 , A : Union[str, Any]=None ): __snake_case : Optional[Any] = round(val / multiple ) * multiple if max_val is not None and x > max_val: __snake_case : Optional[Any] = math.floor(val / multiple ) * multiple if x < min_val: __snake_case : Optional[int] = math.ceil(val / multiple ) * multiple return x __snake_case : Tuple = (output_size, output_size) if isinstance(A , A ) else output_size __snake_case ,__snake_case : Any = get_image_size(A ) __snake_case ,__snake_case : Tuple = output_size # determine new height and width __snake_case : Optional[Any] = output_height / input_height __snake_case : List[Any] = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width __snake_case : Optional[int] = scale_width else: # fit height __snake_case : Tuple = scale_height __snake_case : Optional[int] = constraint_to_multiple_of(scale_height * input_height , multiple=A ) __snake_case : int = constraint_to_multiple_of(scale_width * input_width , multiple=A ) return (new_height, new_width) class a_ ( UpperCamelCase_ ): _snake_case = ["""pixel_values"""] def __init__(self , __a = True , __a = None , __a = PILImageResampling.BILINEAR , __a = False , __a = 1 , __a = True , __a = 1 / 2_5_5 , __a = True , __a = None , __a = None , **__a , ) -> None: """simple docstring""" super().__init__(**__a) __snake_case : Tuple = size if size is not None else {'height': 3_8_4, 'width': 3_8_4} __snake_case : Optional[int] = get_size_dict(__a) __snake_case : int = do_resize __snake_case : Any = size __snake_case : Any = keep_aspect_ratio __snake_case : int = ensure_multiple_of __snake_case : Dict = resample __snake_case : Union[str, Any] = do_rescale __snake_case : List[str] = rescale_factor __snake_case : int = do_normalize __snake_case : str = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __snake_case : Tuple = image_std if image_std is not None else IMAGENET_STANDARD_STD def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a = False , __a = 1 , __a = PILImageResampling.BICUBIC , __a = None , **__a , ) -> np.ndarray: """simple docstring""" __snake_case : Any = get_size_dict(__a) if "height" not in size or "width" not in size: raise ValueError(F"""The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}""") __snake_case : Optional[int] = get_resize_output_image_size( __a , output_size=(size['height'], size['width']) , keep_aspect_ratio=__a , multiple=__a , ) return resize(__a , size=__a , resample=__a , data_format=__a , **__a) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a = None , **__a , ) -> Union[str, Any]: """simple docstring""" return rescale(__a , scale=__a , data_format=__a , **__a) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a , __a = None , **__a , ) -> np.ndarray: """simple docstring""" return normalize(__a , mean=__a , std=__a , data_format=__a , **__a) def SCREAMING_SNAKE_CASE__ (self , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = ChannelDimension.FIRST , **__a , ) -> PIL.Image.Image: """simple docstring""" __snake_case : Optional[Any] = do_resize if do_resize is not None else self.do_resize __snake_case : Optional[int] = size if size is not None else self.size __snake_case : Any = get_size_dict(__a) __snake_case : Tuple = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio __snake_case : List[Any] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of __snake_case : List[str] = resample if resample is not None else self.resample __snake_case : int = do_rescale if do_rescale is not None else self.do_rescale __snake_case : List[Any] = rescale_factor if rescale_factor is not None else self.rescale_factor __snake_case : Dict = do_normalize if do_normalize is not None else self.do_normalize __snake_case : Dict = image_mean if image_mean is not None else self.image_mean __snake_case : Union[str, Any] = image_std if image_std is not None else self.image_std __snake_case : Optional[Any] = make_list_of_images(__a) if not valid_images(__a): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.') if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.') if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.') if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.') # All transformations expect numpy arrays. __snake_case : Any = [to_numpy_array(__a) for image in images] if do_resize: __snake_case : int = [self.resize(image=__a , size=__a , resample=__a) for image in images] if do_rescale: __snake_case : Optional[int] = [self.rescale(image=__a , scale=__a) for image in images] if do_normalize: __snake_case : Optional[int] = [self.normalize(image=__a , mean=__a , std=__a) for image in images] __snake_case : List[str] = [to_channel_dimension_format(__a , __a) for image in images] __snake_case : Any = {'pixel_values': images} return BatchFeature(data=__a , tensor_type=__a) def SCREAMING_SNAKE_CASE__ (self , __a , __a = None) -> str: """simple docstring""" __snake_case : List[str] = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(__a) != len(__a): raise ValueError( 'Make sure that you pass in as many target sizes as the batch dimension of the logits') if is_torch_tensor(__a): __snake_case : int = target_sizes.numpy() __snake_case : List[str] = [] for idx in range(len(__a)): __snake_case : List[str] = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0) , size=target_sizes[idx] , mode='bilinear' , align_corners=__a) __snake_case : Dict = resized_logits[0].argmax(dim=0) semantic_segmentation.append(__a) else: __snake_case : Dict = logits.argmax(dim=1) __snake_case : Tuple = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])] return semantic_segmentation
61
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( A : int ) -> int: """simple docstring""" __snake_case : str = 1 for i in range(1 , num + 1 ): fact *= i return fact def _SCREAMING_SNAKE_CASE ( A : int ) -> int: """simple docstring""" __snake_case : Union[str, Any] = 0 while number > 0: __snake_case : Dict = number % 10 sum_of_digits += last_digit __snake_case : Union[str, Any] = number // 10 # Removing the last_digit from the given number return sum_of_digits def _SCREAMING_SNAKE_CASE ( A : int = 1_00 ) -> int: """simple docstring""" __snake_case : List[Any] = factorial(A ) __snake_case : Dict = split_and_add(A ) return result if __name__ == "__main__": print(solution(int(input('''Enter the Number: ''').strip())))
61
1
'''simple docstring''' import inspect import unittest from transformers import RegNetConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device 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 RegNetForImageClassification, RegNetModel from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class a_ : def __init__(self , __a , __a=3 , __a=3_2 , __a=3 , __a=1_0 , __a=[1_0, 2_0, 3_0, 4_0] , __a=[1, 1, 2, 1] , __a=True , __a=True , __a="relu" , __a=3 , __a=None , ) -> Tuple: """simple docstring""" __snake_case : List[str] = parent __snake_case : List[Any] = batch_size __snake_case : Dict = image_size __snake_case : Union[str, Any] = num_channels __snake_case : Dict = embeddings_size __snake_case : Optional[Any] = hidden_sizes __snake_case : int = depths __snake_case : str = is_training __snake_case : List[str] = use_labels __snake_case : List[Any] = hidden_act __snake_case : List[str] = num_labels __snake_case : Dict = scope __snake_case : Dict = len(__a) def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" __snake_case : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) __snake_case : Union[str, Any] = None if self.use_labels: __snake_case : Optional[Any] = ids_tensor([self.batch_size] , self.num_labels) __snake_case : int = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]: """simple docstring""" return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , ) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Optional[int]: """simple docstring""" __snake_case : Tuple = RegNetModel(config=__a) model.to(__a) model.eval() __snake_case : Optional[int] = model(__a) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2) , ) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> List[Any]: """simple docstring""" __snake_case : str = self.num_labels __snake_case : List[Any] = RegNetForImageClassification(__a) model.to(__a) model.eval() __snake_case : int = model(__a , labels=__a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" __snake_case : Union[str, Any] = self.prepare_config_and_inputs() __snake_case ,__snake_case ,__snake_case : List[Any] = config_and_inputs __snake_case : str = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class a_ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): _snake_case = (RegNetModel, RegNetForImageClassification) if is_torch_available() else () _snake_case = ( {"""feature-extraction""": RegNetModel, """image-classification""": RegNetForImageClassification} if is_torch_available() else {} ) _snake_case = False _snake_case = False _snake_case = False _snake_case = False def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" __snake_case : Optional[Any] = RegNetModelTester(self) __snake_case : Optional[Any] = ConfigTester(self , config_class=__a , has_text_modality=__a) def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" return @unittest.skip(reason='RegNet does not use inputs_embeds') def SCREAMING_SNAKE_CASE__ (self) -> str: """simple docstring""" pass @unittest.skip(reason='RegNet does not support input and output embeddings') def SCREAMING_SNAKE_CASE__ (self) -> str: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case ,__snake_case : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : List[Any] = model_class(__a) __snake_case : List[str] = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic __snake_case : Any = [*signature.parameters.keys()] __snake_case : Any = ['pixel_values'] self.assertListEqual(arg_names[:1] , __a) def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" __snake_case : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a) def SCREAMING_SNAKE_CASE__ (self) -> Tuple: """simple docstring""" __snake_case ,__snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : Tuple = model_class(config=__a) for name, module in model.named_modules(): if isinstance(__a , (nn.BatchNormad, nn.GroupNorm)): self.assertTrue( torch.all(module.weight == 1) , msg=F"""Parameter {name} of model {model_class} seems not properly initialized""" , ) self.assertTrue( torch.all(module.bias == 0) , msg=F"""Parameter {name} of model {model_class} seems not properly initialized""" , ) def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" def check_hidden_states_output(__a , __a , __a): __snake_case : Optional[int] = model_class(__a) model.to(__a) model.eval() with torch.no_grad(): __snake_case : Optional[Any] = model(**self._prepare_for_class(__a , __a)) __snake_case : Any = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __snake_case : List[str] = self.model_tester.num_stages self.assertEqual(len(__a) , expected_num_stages + 1) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) __snake_case ,__snake_case : List[str] = self.model_tester.prepare_config_and_inputs_for_common() __snake_case : str = ['basic', 'bottleneck'] for model_class in self.all_model_classes: for layer_type in layers_type: __snake_case : List[Any] = layer_type __snake_case : Tuple = True check_hidden_states_output(__a , __a , __a) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __snake_case : Optional[int] = True check_hidden_states_output(__a , __a , __a) def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" __snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__a) @slow def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case : Tuple = RegNetModel.from_pretrained(__a) self.assertIsNotNone(__a) def _SCREAMING_SNAKE_CASE ( ) -> str: """simple docstring""" __snake_case : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class a_ ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]: """simple docstring""" return ( AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) if is_vision_available() else None ) @slow def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" __snake_case : Dict = RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]).to(__a) __snake_case : List[str] = self.default_image_processor __snake_case : List[str] = prepare_img() __snake_case : int = image_processor(images=__a , return_tensors='pt').to(__a) # forward pass with torch.no_grad(): __snake_case : List[str] = model(**__a) # verify the logits __snake_case : str = torch.Size((1, 1_0_0_0)) self.assertEqual(outputs.logits.shape , __a) __snake_case : Optional[Any] = torch.tensor([-0.4_180, -1.5_051, -3.4_836]).to(__a) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __a , atol=1E-4))
61
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor class a_ ( unittest.TestCase ): def __init__(self , __a , __a=7 , __a=3 , __a=1_8 , __a=3_0 , __a=4_0_0 , __a=True , __a=None , __a=True , __a=None , __a=True , __a=[0.48_145_466, 0.4_578_275, 0.40_821_073] , __a=[0.26_862_954, 0.26_130_258, 0.27_577_711] , __a=True , ) -> List[Any]: """simple docstring""" __snake_case : Tuple = size if size is not None else {'height': 2_2_4, 'width': 2_2_4} __snake_case : Any = crop_size if crop_size is not None else {'height': 1_8, 'width': 1_8} __snake_case : Optional[int] = parent __snake_case : Dict = batch_size __snake_case : str = num_channels __snake_case : Optional[Any] = image_size __snake_case : Optional[int] = min_resolution __snake_case : Tuple = max_resolution __snake_case : Optional[int] = do_resize __snake_case : Optional[int] = size __snake_case : Union[str, Any] = do_center_crop __snake_case : List[Any] = crop_size __snake_case : int = do_normalize __snake_case : Optional[Any] = image_mean __snake_case : str = image_std __snake_case : Optional[Any] = do_convert_rgb def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def SCREAMING_SNAKE_CASE__ (self , __a=False , __a=False , __a=False) -> List[str]: """simple docstring""" assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" if equal_resolution: __snake_case : Optional[int] = [] for i in range(self.batch_size): image_inputs.append( np.random.randint( 2_5_5 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta)) else: __snake_case : Dict = [] for i in range(self.batch_size): __snake_case ,__snake_case : Optional[Any] = np.random.choice(np.arange(self.min_resolution , self.max_resolution) , 2) image_inputs.append(np.random.randint(2_5_5 , size=(self.num_channels, width, height) , dtype=np.uinta)) if not numpify and not torchify: # PIL expects the channel dimension as last dimension __snake_case : int = [Image.fromarray(np.moveaxis(__a , 0 , -1)) for x in image_inputs] if torchify: __snake_case : List[Any] = [torch.from_numpy(__a) for x in image_inputs] return image_inputs @require_torch @require_vision class a_ ( UpperCamelCase_ , unittest.TestCase ): _snake_case = ChineseCLIPImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : Union[str, Any] = ChineseCLIPImageProcessingTester(self , do_center_crop=__a) @property def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : int = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(__a , 'do_resize')) self.assertTrue(hasattr(__a , 'size')) self.assertTrue(hasattr(__a , 'do_center_crop')) self.assertTrue(hasattr(__a , 'center_crop')) self.assertTrue(hasattr(__a , 'do_normalize')) self.assertTrue(hasattr(__a , 'image_mean')) self.assertTrue(hasattr(__a , 'image_std')) self.assertTrue(hasattr(__a , 'do_convert_rgb')) def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size , {'height': 2_2_4, 'width': 2_2_4}) self.assertEqual(image_processor.crop_size , {'height': 1_8, 'width': 1_8}) __snake_case : List[str] = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 , crop_size=8_4) self.assertEqual(image_processor.size , {'shortest_edge': 4_2}) self.assertEqual(image_processor.crop_size , {'height': 8_4, 'width': 8_4}) def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" __snake_case : List[Any] = self.image_processing_class(**self.image_processor_dict) # create random PIL images __snake_case : Optional[Any] = self.image_processor_tester.prepare_inputs(equal_resolution=__a) for image in image_inputs: self.assertIsInstance(__a , Image.Image) # Test not batched input __snake_case : 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __snake_case : List[Any] = image_processing(__a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" __snake_case : Union[str, Any] = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors __snake_case : Optional[int] = self.image_processor_tester.prepare_inputs(equal_resolution=__a , numpify=__a) for image in image_inputs: self.assertIsInstance(__a , np.ndarray) # Test not batched input __snake_case : List[Any] = image_processing(image_inputs[0] , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __snake_case : int = image_processing(__a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : Any = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors __snake_case : Tuple = self.image_processor_tester.prepare_inputs(equal_resolution=__a , torchify=__a) for image in image_inputs: self.assertIsInstance(__a , torch.Tensor) # Test not batched input __snake_case : Any = image_processing(image_inputs[0] , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __snake_case : Union[str, Any] = image_processing(__a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) @require_torch @require_vision class a_ ( UpperCamelCase_ , unittest.TestCase ): _snake_case = ChineseCLIPImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" __snake_case : Optional[Any] = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=__a) __snake_case : List[Any] = 3 @property def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : Any = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(__a , 'do_resize')) self.assertTrue(hasattr(__a , 'size')) self.assertTrue(hasattr(__a , 'do_center_crop')) self.assertTrue(hasattr(__a , 'center_crop')) self.assertTrue(hasattr(__a , 'do_normalize')) self.assertTrue(hasattr(__a , 'image_mean')) self.assertTrue(hasattr(__a , 'image_std')) self.assertTrue(hasattr(__a , 'do_convert_rgb')) def SCREAMING_SNAKE_CASE__ (self) -> Tuple: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : List[Any] = self.image_processing_class(**self.image_processor_dict) # create random PIL images __snake_case : Union[str, Any] = self.image_processor_tester.prepare_inputs(equal_resolution=__a) for image in image_inputs: self.assertIsInstance(__a , Image.Image) # Test not batched input __snake_case : Optional[int] = image_processing(image_inputs[0] , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __snake_case : Optional[int] = image_processing(__a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , )
61
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 __A = logging.get_logger(__name__) __A = { '''facebook/data2vec-vision-base-ft''': ( '''https://huggingface.co/facebook/data2vec-vision-base-ft/resolve/main/config.json''' ), } class a_ ( UpperCamelCase_ ): _snake_case = """data2vec-vision""" def __init__(self , __a=7_6_8 , __a=1_2 , __a=1_2 , __a=3_0_7_2 , __a="gelu" , __a=0.0 , __a=0.0 , __a=0.02 , __a=1E-12 , __a=2_2_4 , __a=1_6 , __a=3 , __a=False , __a=False , __a=False , __a=False , __a=0.1 , __a=0.1 , __a=True , __a=[3, 5, 7, 1_1] , __a=[1, 2, 3, 6] , __a=True , __a=0.4 , __a=2_5_6 , __a=1 , __a=False , __a=2_5_5 , **__a , ) -> Dict: """simple docstring""" super().__init__(**__a) __snake_case : Dict = hidden_size __snake_case : List[str] = num_hidden_layers __snake_case : Dict = num_attention_heads __snake_case : Union[str, Any] = intermediate_size __snake_case : Union[str, Any] = hidden_act __snake_case : Any = hidden_dropout_prob __snake_case : Tuple = attention_probs_dropout_prob __snake_case : str = initializer_range __snake_case : Optional[int] = layer_norm_eps __snake_case : List[str] = image_size __snake_case : Tuple = patch_size __snake_case : str = num_channels __snake_case : Tuple = use_mask_token __snake_case : int = use_absolute_position_embeddings __snake_case : Dict = use_relative_position_bias __snake_case : int = use_shared_relative_position_bias __snake_case : Optional[Any] = layer_scale_init_value __snake_case : int = drop_path_rate __snake_case : Union[str, Any] = use_mean_pooling # decode head attributes (semantic segmentation) __snake_case : int = out_indices __snake_case : Union[str, Any] = pool_scales # auxiliary head attributes (semantic segmentation) __snake_case : Union[str, Any] = use_auxiliary_head __snake_case : int = auxiliary_loss_weight __snake_case : Tuple = auxiliary_channels __snake_case : Union[str, Any] = auxiliary_num_convs __snake_case : Optional[int] = auxiliary_concat_input __snake_case : Tuple = semantic_loss_ignore_index class a_ ( UpperCamelCase_ ): _snake_case = version.parse("""1.11""" ) @property def SCREAMING_SNAKE_CASE__ (self) -> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ]) @property def SCREAMING_SNAKE_CASE__ (self) -> float: """simple docstring""" return 1E-4
61
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { '''sayakpaul/vit-msn-base''': '''https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json''', # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class a_ ( UpperCamelCase_ ): _snake_case = """vit_msn""" def __init__(self , __a=7_6_8 , __a=1_2 , __a=1_2 , __a=3_0_7_2 , __a="gelu" , __a=0.0 , __a=0.0 , __a=0.02 , __a=1E-06 , __a=2_2_4 , __a=1_6 , __a=3 , __a=True , **__a , ) -> Any: """simple docstring""" super().__init__(**__a) __snake_case : List[str] = hidden_size __snake_case : Optional[int] = num_hidden_layers __snake_case : Optional[Any] = num_attention_heads __snake_case : str = intermediate_size __snake_case : List[str] = hidden_act __snake_case : List[Any] = hidden_dropout_prob __snake_case : Tuple = attention_probs_dropout_prob __snake_case : List[str] = initializer_range __snake_case : Optional[int] = layer_norm_eps __snake_case : Dict = image_size __snake_case : int = patch_size __snake_case : Dict = num_channels __snake_case : Tuple = qkv_bias
61
1
'''simple docstring''' import random from .binary_exp_mod import bin_exp_mod def _SCREAMING_SNAKE_CASE ( A : Tuple , A : List[str]=10_00 ) -> str: """simple docstring""" if n < 2: return False if n % 2 == 0: return n == 2 # this means n is odd __snake_case : List[str] = n - 1 __snake_case : List[str] = 0 while d % 2 == 0: d /= 2 exp += 1 # n - 1=d*(2**exp) __snake_case : Dict = 0 while count < prec: __snake_case : str = random.randint(2 , n - 1 ) __snake_case : int = bin_exp_mod(A , A , A ) if b != 1: __snake_case : List[str] = True for _ in range(A ): if b == n - 1: __snake_case : str = False break __snake_case : int = b * b b %= n if flag: return False count += 1 return True if __name__ == "__main__": __A = abs(int(input('''Enter bound : ''').strip())) print('''Here\'s the list of primes:''') print(''', '''.join(str(i) for i in range(n + 1) if is_prime_big(i)))
61
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( A : float , A : list[float] ) -> float: """simple docstring""" if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) __snake_case : List[str] = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(A ) ) return round(A , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
61
1
'''simple docstring''' import argparse import torch from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() __A = logging.get_logger(__name__) __A = [ ['''attention''', '''attn'''], ['''encoder_attention''', '''encoder_attn'''], ['''q_lin''', '''q_proj'''], ['''k_lin''', '''k_proj'''], ['''v_lin''', '''v_proj'''], ['''out_lin''', '''out_proj'''], ['''norm_embeddings''', '''layernorm_embedding'''], ['''position_embeddings''', '''embed_positions'''], ['''embeddings''', '''embed_tokens'''], ['''ffn.lin''', '''fc'''], ] def _SCREAMING_SNAKE_CASE ( A : Optional[int] ) -> Optional[int]: """simple docstring""" if k == "embeddings.weight": return "shared.weight" for parlai_name, hf_name in PATTERNS: __snake_case : List[str] = k.replace(A , A ) if k.startswith('encoder' ): __snake_case : Any = k.replace('.attn' , '.self_attn' ) __snake_case : int = k.replace('norm1' , 'self_attn_layer_norm' ) __snake_case : Optional[int] = k.replace('norm2' , 'final_layer_norm' ) elif k.startswith('decoder' ): __snake_case : int = k.replace('norm1' , 'self_attn_layer_norm' ) __snake_case : Dict = k.replace('norm2' , 'encoder_attn_layer_norm' ) __snake_case : int = k.replace('norm3' , 'final_layer_norm' ) return k def _SCREAMING_SNAKE_CASE ( A : Tuple ) -> Optional[int]: """simple docstring""" __snake_case : List[Any] = [ 'model.encoder.layernorm_embedding.weight', 'model.encoder.layernorm_embedding.bias', 'model.decoder.layernorm_embedding.weight', 'model.decoder.layernorm_embedding.bias', ] for k in keys: __snake_case : Any = sd.pop(A ) __snake_case : str = k.replace('layernorm_embedding' , 'layer_norm' ) assert new_k not in sd __snake_case : int = v __A = ['''START'''] @torch.no_grad() def _SCREAMING_SNAKE_CASE ( A : str , A : List[Any] , A : List[Any] ) -> Any: """simple docstring""" __snake_case : str = torch.load(A , map_location='cpu' ) __snake_case : int = model['model'] __snake_case : str = BlenderbotConfig.from_json_file(A ) __snake_case : Dict = BlenderbotForConditionalGeneration(A ) __snake_case : Any = m.model.state_dict().keys() __snake_case : List[str] = [] __snake_case : int = {} for k, v in sd.items(): if k in IGNORE_KEYS: continue __snake_case : Tuple = rename_state_dict_key(A ) if new_k not in valid_keys: failures.append([k, new_k] ) else: __snake_case : Optional[int] = v if cfg.normalize_before: # Blenderbot-3B checkpoints. Rename layernorm_embedding -> layer_norm rename_layernorm_keys(A ) m.model.load_state_dict(A , strict=A ) m.half() m.save_pretrained(A ) if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument('''--src_path''', type=str, help='''like blenderbot-model.bin''') parser.add_argument('''--save_dir''', default='''hf_blenderbot''', type=str, help='''Where to save converted model.''') parser.add_argument( '''--hf_config_json''', default='''blenderbot-3b-config.json''', type=str, help='''Path to config to use''' ) __A = parser.parse_args() convert_parlai_checkpoint(args.src_path, args.save_dir, args.hf_config_json)
61
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __A = { '''configuration_distilbert''': [ '''DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DistilBertConfig''', '''DistilBertOnnxConfig''', ], '''tokenization_distilbert''': ['''DistilBertTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ['''DistilBertTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ '''DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''DistilBertForMaskedLM''', '''DistilBertForMultipleChoice''', '''DistilBertForQuestionAnswering''', '''DistilBertForSequenceClassification''', '''DistilBertForTokenClassification''', '''DistilBertModel''', '''DistilBertPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ '''TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFDistilBertForMaskedLM''', '''TFDistilBertForMultipleChoice''', '''TFDistilBertForQuestionAnswering''', '''TFDistilBertForSequenceClassification''', '''TFDistilBertForTokenClassification''', '''TFDistilBertMainLayer''', '''TFDistilBertModel''', '''TFDistilBertPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ '''FlaxDistilBertForMaskedLM''', '''FlaxDistilBertForMultipleChoice''', '''FlaxDistilBertForQuestionAnswering''', '''FlaxDistilBertForSequenceClassification''', '''FlaxDistilBertForTokenClassification''', '''FlaxDistilBertModel''', '''FlaxDistilBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_distilbert import ( DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DistilBertConfig, DistilBertOnnxConfig, ) from .tokenization_distilbert import DistilBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_distilbert_fast import DistilBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_distilbert import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, DistilBertPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertMainLayer, TFDistilBertModel, TFDistilBertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, FlaxDistilBertPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
61
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, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL __A = logging.get_logger(__name__) class a_ ( UpperCamelCase_ ): _snake_case = ["""pixel_values"""] def __init__(self , __a = True , __a = None , __a = None , __a = PILImageResampling.BILINEAR , __a = True , __a = 1 / 2_5_5 , __a = True , __a = None , __a = None , **__a , ) -> None: """simple docstring""" super().__init__(**__a) __snake_case : Tuple = size if size is not None else {'shortest_edge': 3_8_4} __snake_case : List[Any] = get_size_dict(__a , default_to_square=__a) __snake_case : int = do_resize __snake_case : List[str] = size # Default value set here for backwards compatibility where the value in config is None __snake_case : Any = crop_pct if crop_pct is not None else 2_2_4 / 2_5_6 __snake_case : Tuple = resample __snake_case : Dict = do_rescale __snake_case : Any = rescale_factor __snake_case : str = do_normalize __snake_case : Union[str, Any] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __snake_case : Dict = image_std if image_std is not None else IMAGENET_STANDARD_STD def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a , __a = PILImageResampling.BICUBIC , __a = None , **__a , ) -> np.ndarray: """simple docstring""" __snake_case : Dict = get_size_dict(__a , default_to_square=__a) if "shortest_edge" not in size: raise ValueError(F"""Size dictionary must contain 'shortest_edge' key. Got {size.keys()}""") __snake_case : List[str] = size['shortest_edge'] if shortest_edge < 3_8_4: # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct __snake_case : Any = int(shortest_edge / crop_pct) __snake_case : Any = get_resize_output_image_size(__a , size=__a , default_to_square=__a) __snake_case : int = resize(image=__a , size=__a , resample=__a , data_format=__a , **__a) # then crop to (shortest_edge, shortest_edge) return center_crop(image=__a , size=(shortest_edge, shortest_edge) , data_format=__a , **__a) else: # warping (no cropping) when evaluated at 384 or larger return resize( __a , size=(shortest_edge, shortest_edge) , resample=__a , data_format=__a , **__a) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a = None , **__a , ) -> Any: """simple docstring""" return rescale(__a , scale=__a , data_format=__a , **__a) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a , __a = None , **__a , ) -> np.ndarray: """simple docstring""" return normalize(__a , mean=__a , std=__a , data_format=__a , **__a) def SCREAMING_SNAKE_CASE__ (self , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = ChannelDimension.FIRST , **__a , ) -> PIL.Image.Image: """simple docstring""" __snake_case : Optional[int] = do_resize if do_resize is not None else self.do_resize __snake_case : Dict = crop_pct if crop_pct is not None else self.crop_pct __snake_case : Tuple = resample if resample is not None else self.resample __snake_case : Any = do_rescale if do_rescale is not None else self.do_rescale __snake_case : Any = rescale_factor if rescale_factor is not None else self.rescale_factor __snake_case : Union[str, Any] = do_normalize if do_normalize is not None else self.do_normalize __snake_case : Optional[int] = image_mean if image_mean is not None else self.image_mean __snake_case : Optional[Any] = image_std if image_std is not None else self.image_std __snake_case : List[str] = size if size is not None else self.size __snake_case : Any = get_size_dict(__a , default_to_square=__a) __snake_case : Dict = make_list_of_images(__a) if not valid_images(__a): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.') if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.') if do_resize and size["shortest_edge"] < 3_8_4 and crop_pct is None: raise ValueError('crop_pct must be specified if size < 384.') if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.') if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.') # All transformations expect numpy arrays. __snake_case : Tuple = [to_numpy_array(__a) for image in images] if do_resize: __snake_case : Optional[int] = [self.resize(image=__a , size=__a , crop_pct=__a , resample=__a) for image in images] if do_rescale: __snake_case : Optional[int] = [self.rescale(image=__a , scale=__a) for image in images] if do_normalize: __snake_case : Any = [self.normalize(image=__a , mean=__a , std=__a) for image in images] __snake_case : Dict = [to_channel_dimension_format(__a , __a) for image in images] __snake_case : Union[str, Any] = {'pixel_values': images} return BatchFeature(data=__a , tensor_type=__a)
61
'''simple docstring''' # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. __A = abspath(join(dirname(dirname(__file__)), '''src''')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='''ignore''', category=FutureWarning) def _SCREAMING_SNAKE_CASE ( A : Tuple ) -> str: """simple docstring""" from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(A ) def _SCREAMING_SNAKE_CASE ( A : int ) -> Optional[int]: """simple docstring""" from diffusers.utils.testing_utils import pytest_terminal_summary_main __snake_case : Any = terminalreporter.config.getoption('--make-reports' ) if make_reports: pytest_terminal_summary_main(A , id=A )
61
1
'''simple docstring''' from __future__ import annotations from collections import deque class a_ : def __init__(self , __a) -> Optional[Any]: """simple docstring""" __snake_case : list[dict] = [] self.adlist.append( {'value': '', 'next_states': [], 'fail_state': 0, 'output': []}) for keyword in keywords: self.add_keyword(__a) self.set_fail_transitions() def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> int | None: """simple docstring""" for state in self.adlist[current_state]["next_states"]: if char == self.adlist[state]["value"]: return state return None def SCREAMING_SNAKE_CASE__ (self , __a) -> None: """simple docstring""" __snake_case : Dict = 0 for character in keyword: __snake_case : Optional[Any] = self.find_next_state(__a , __a) if next_state is None: self.adlist.append( { 'value': character, 'next_states': [], 'fail_state': 0, 'output': [], }) self.adlist[current_state]["next_states"].append(len(self.adlist) - 1) __snake_case : List[Any] = len(self.adlist) - 1 else: __snake_case : Union[str, Any] = next_state self.adlist[current_state]["output"].append(__a) def SCREAMING_SNAKE_CASE__ (self) -> None: """simple docstring""" __snake_case : deque = deque() for node in self.adlist[0]["next_states"]: q.append(__a) __snake_case : int = 0 while q: __snake_case : List[Any] = q.popleft() for child in self.adlist[r]["next_states"]: q.append(__a) __snake_case : List[Any] = self.adlist[r]['fail_state'] while ( self.find_next_state(__a , self.adlist[child]['value']) is None and state != 0 ): __snake_case : int = self.adlist[state]['fail_state'] __snake_case : Dict = self.find_next_state( __a , self.adlist[child]['value']) if self.adlist[child]["fail_state"] is None: __snake_case : Optional[Any] = 0 __snake_case : List[Any] = ( self.adlist[child]['output'] + self.adlist[self.adlist[child]['fail_state']]['output'] ) def SCREAMING_SNAKE_CASE__ (self , __a) -> dict[str, list[int]]: """simple docstring""" __snake_case : dict = {} # returns a dict with keywords and list of its occurrences __snake_case : Optional[Any] = 0 for i in range(len(__a)): while ( self.find_next_state(__a , string[i]) is None and current_state != 0 ): __snake_case : Tuple = self.adlist[current_state]['fail_state'] __snake_case : Optional[int] = self.find_next_state(__a , string[i]) if next_state is None: __snake_case : Optional[int] = 0 else: __snake_case : Tuple = next_state for key in self.adlist[current_state]["output"]: if key not in result: __snake_case : int = [] result[key].append(i - len(__a) + 1) return result if __name__ == "__main__": import doctest doctest.testmod()
61
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __A = { '''configuration_biogpt''': ['''BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BioGptConfig'''], '''tokenization_biogpt''': ['''BioGptTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ '''BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BioGptForCausalLM''', '''BioGptForTokenClassification''', '''BioGptForSequenceClassification''', '''BioGptModel''', '''BioGptPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
61
1
'''simple docstring''' import argparse import json from collections import OrderedDict from functools import partial from pathlib import Path import timm import torch from huggingface_hub import hf_hub_download from transformers import LevitConfig, LevitForImageClassificationWithTeacher, LevitImageProcessor from transformers.utils import logging logging.set_verbosity_info() __A = logging.get_logger() def _SCREAMING_SNAKE_CASE ( A : int , A : str , A : LevitConfig , A : Path , A : bool = True ) -> Dict: """simple docstring""" print(F"""Converting {name}...""" ) with torch.no_grad(): if hidden_sizes == 1_28: if name[-1] == "S": __snake_case : Optional[int] = timm.create_model('levit_128s' , pretrained=A ) else: __snake_case : Tuple = timm.create_model('levit_128' , pretrained=A ) if hidden_sizes == 1_92: __snake_case : int = timm.create_model('levit_192' , pretrained=A ) if hidden_sizes == 2_56: __snake_case : List[Any] = timm.create_model('levit_256' , pretrained=A ) if hidden_sizes == 3_84: __snake_case : int = timm.create_model('levit_384' , pretrained=A ) from_model.eval() __snake_case : str = LevitForImageClassificationWithTeacher(A ).eval() __snake_case : int = OrderedDict() __snake_case : Optional[Any] = from_model.state_dict() __snake_case : Tuple = list(from_model.state_dict().keys() ) __snake_case : List[str] = list(our_model.state_dict().keys() ) print(len(A ) , len(A ) ) for i in range(len(A ) ): __snake_case : Optional[int] = weights[og_keys[i]] our_model.load_state_dict(A ) __snake_case : Tuple = torch.randn((2, 3, 2_24, 2_24) ) __snake_case : Union[str, Any] = from_model(A ) __snake_case : List[str] = our_model(A ).logits assert torch.allclose(A , A ), "The model logits don't match the original one." __snake_case : int = name print(A ) if push_to_hub: our_model.save_pretrained(save_directory / checkpoint_name ) __snake_case : int = LevitImageProcessor() image_processor.save_pretrained(save_directory / checkpoint_name ) print(F"""Pushed {checkpoint_name}""" ) def _SCREAMING_SNAKE_CASE ( A : Path , A : str = None , A : bool = True ) -> List[Any]: """simple docstring""" __snake_case : Optional[Any] = 'imagenet-1k-id2label.json' __snake_case : Tuple = 10_00 __snake_case : Dict = (1, num_labels) __snake_case : List[str] = 'huggingface/label-files' __snake_case : Any = num_labels __snake_case : str = json.load(open(hf_hub_download(A , A , repo_type='dataset' ) , 'r' ) ) __snake_case : Any = {int(A ): v for k, v in idalabel.items()} __snake_case : int = idalabel __snake_case : Union[str, Any] = {v: k for k, v in idalabel.items()} __snake_case : Optional[int] = partial(A , num_labels=A , idalabel=A , labelaid=A ) __snake_case : Dict = { 'levit-128S': 1_28, 'levit-128': 1_28, 'levit-192': 1_92, 'levit-256': 2_56, 'levit-384': 3_84, } __snake_case : Union[str, Any] = { 'levit-128S': ImageNetPreTrainedConfig( hidden_sizes=[1_28, 2_56, 3_84] , num_attention_heads=[4, 6, 8] , depths=[2, 3, 4] , key_dim=[16, 16, 16] , drop_path_rate=0 , ), 'levit-128': ImageNetPreTrainedConfig( hidden_sizes=[1_28, 2_56, 3_84] , num_attention_heads=[4, 8, 12] , depths=[4, 4, 4] , key_dim=[16, 16, 16] , drop_path_rate=0 , ), 'levit-192': ImageNetPreTrainedConfig( hidden_sizes=[1_92, 2_88, 3_84] , num_attention_heads=[3, 5, 6] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0 , ), 'levit-256': ImageNetPreTrainedConfig( hidden_sizes=[2_56, 3_84, 5_12] , num_attention_heads=[4, 6, 8] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0 , ), 'levit-384': ImageNetPreTrainedConfig( hidden_sizes=[3_84, 5_12, 7_68] , num_attention_heads=[6, 9, 12] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0.1 , ), } if model_name: convert_weight_and_push( names_to_hidden_sizes[model_name] , A , names_to_config[model_name] , A , A ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(names_to_hidden_sizes[model_name] , A , A , A , A ) return config, expected_shape if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default=None, type=str, help='''The name of the model you wish to convert, it must be one of the supported Levit* architecture,''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default='''levit-dump-folder/''', type=Path, required=False, help='''Path to the output PyTorch model directory.''', ) parser.add_argument('''--push_to_hub''', action='''store_true''', help='''Push model and image processor to the hub''') parser.add_argument( '''--no-push_to_hub''', dest='''push_to_hub''', action='''store_false''', help='''Do not push model and image processor to the hub''', ) __A = parser.parse_args() __A = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
61
'''simple docstring''' from packaging import version from .import_utils import is_accelerate_available if is_accelerate_available(): import accelerate def _SCREAMING_SNAKE_CASE ( A : Optional[Any] ) -> int: """simple docstring""" if not is_accelerate_available(): return method __snake_case : Optional[Any] = version.parse(accelerate.__version__ ).base_version if version.parse(A ) < version.parse('0.17.0' ): return method def wrapper(self : Optional[Any] , *A : Optional[Any] , **A : Optional[int] ): if hasattr(self , '_hf_hook' ) and hasattr(self._hf_hook , 'pre_forward' ): self._hf_hook.pre_forward(self ) return method(self , *A , **A ) return wrapper
61
1
'''simple docstring''' import torch from diffusers import KDPMaDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class a_ ( UpperCamelCase_ ): _snake_case = (KDPMaDiscreteScheduler,) _snake_case = 10 def SCREAMING_SNAKE_CASE__ (self , **__a) -> List[str]: """simple docstring""" __snake_case : Any = { 'num_train_timesteps': 1_1_0_0, 'beta_start': 0.0_001, 'beta_end': 0.02, 'beta_schedule': 'linear', } config.update(**__a) return config def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=__a) def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001] , [0.0_002, 0.002, 0.02]): self.check_over_configs(beta_start=__a , beta_end=__a) def SCREAMING_SNAKE_CASE__ (self) -> Tuple: """simple docstring""" for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=__a) def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__a) def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" __snake_case : List[Any] = self.scheduler_classes[0] __snake_case : Optional[int] = self.get_scheduler_config(prediction_type='v_prediction') __snake_case : str = scheduler_class(**__a) scheduler.set_timesteps(self.num_inference_steps) __snake_case : str = self.dummy_model() __snake_case : Any = self.dummy_sample_deter * scheduler.init_noise_sigma __snake_case : Dict = sample.to(__a) for i, t in enumerate(scheduler.timesteps): __snake_case : Any = scheduler.scale_model_input(__a , __a) __snake_case : str = model(__a , __a) __snake_case : int = scheduler.step(__a , __a , __a) __snake_case : Tuple = output.prev_sample __snake_case : Optional[Any] = torch.sum(torch.abs(__a)) __snake_case : List[str] = torch.mean(torch.abs(__a)) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 4.6_934E-07) < 1E-2 assert abs(result_mean.item() - 6.1_112E-10) < 1E-3 else: # CUDA assert abs(result_sum.item() - 4.693_428_650_170_972E-07) < 1E-2 assert abs(result_mean.item() - 0.0_002) < 1E-3 def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" if torch_device == "mps": return __snake_case : str = self.scheduler_classes[0] __snake_case : int = self.get_scheduler_config() __snake_case : Optional[int] = scheduler_class(**__a) scheduler.set_timesteps(self.num_inference_steps) __snake_case : List[Any] = self.dummy_model() __snake_case : Optional[int] = self.dummy_sample_deter * scheduler.init_noise_sigma __snake_case : Tuple = sample.to(__a) for i, t in enumerate(scheduler.timesteps): __snake_case : Tuple = scheduler.scale_model_input(__a , __a) __snake_case : Dict = model(__a , __a) __snake_case : Dict = scheduler.step(__a , __a , __a) __snake_case : Optional[int] = output.prev_sample __snake_case : str = torch.sum(torch.abs(__a)) __snake_case : Tuple = torch.mean(torch.abs(__a)) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 20.4_125) < 1E-2 assert abs(result_mean.item() - 0.0_266) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.4_125) < 1E-2 assert abs(result_mean.item() - 0.0_266) < 1E-3 def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]: """simple docstring""" if torch_device == "mps": return __snake_case : Dict = self.scheduler_classes[0] __snake_case : str = self.get_scheduler_config() __snake_case : Dict = scheduler_class(**__a) scheduler.set_timesteps(self.num_inference_steps , device=__a) __snake_case : str = self.dummy_model() __snake_case : Tuple = self.dummy_sample_deter.to(__a) * scheduler.init_noise_sigma for t in scheduler.timesteps: __snake_case : Optional[Any] = scheduler.scale_model_input(__a , __a) __snake_case : str = model(__a , __a) __snake_case : str = scheduler.step(__a , __a , __a) __snake_case : Optional[Any] = output.prev_sample __snake_case : int = torch.sum(torch.abs(__a)) __snake_case : Dict = torch.mean(torch.abs(__a)) if str(__a).startswith('cpu'): # The following sum varies between 148 and 156 on mps. Why? assert abs(result_sum.item() - 20.4_125) < 1E-2 assert abs(result_mean.item() - 0.0_266) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.4_125) < 1E-2 assert abs(result_mean.item() - 0.0_266) < 1E-3
61
'''simple docstring''' import unittest from transformers import load_tool from transformers.utils import is_torch_available if is_torch_available(): import torch from transformers.testing_utils import require_torch from .test_tools_common import ToolTesterMixin @require_torch class a_ ( unittest.TestCase , UpperCamelCase_ ): def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" __snake_case : List[str] = load_tool('text-to-speech') self.tool.setup() def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]: """simple docstring""" torch.manual_seed(0) __snake_case : Dict = self.tool('hey') __snake_case : List[Any] = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485]) , )) def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" torch.manual_seed(0) __snake_case : Any = self.tool('hey') __snake_case : Any = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485]) , ))
61
1
'''simple docstring''' import argparse import torch from transformers import RemBertConfig, RemBertModel, load_tf_weights_in_rembert from transformers.utils import logging logging.set_verbosity_info() def _SCREAMING_SNAKE_CASE ( A : Tuple , A : int , A : Any ) -> List[Any]: """simple docstring""" # Initialise PyTorch model __snake_case : Any = RemBertConfig.from_json_file(A ) print('Building PyTorch model from configuration: {}'.format(str(A ) ) ) __snake_case : str = RemBertModel(A ) # Load weights from tf checkpoint load_tf_weights_in_rembert(A , A , A ) # Save pytorch-model print('Save PyTorch model to {}'.format(A ) ) torch.save(model.state_dict() , A ) if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--rembert_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained RemBERT model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) __A = parser.parse_args() convert_rembert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.rembert_config_file, args.pytorch_dump_path)
61
'''simple docstring''' import math class a_ : def __init__(self , __a=0) -> Any: # a graph with Node 0,1,...,N-1 """simple docstring""" __snake_case : List[str] = n __snake_case : Tuple = [ [math.inf for j in range(0 , __a)] for i in range(0 , __a) ] # adjacency matrix for weight __snake_case : Union[str, Any] = [ [math.inf for j in range(0 , __a)] for i in range(0 , __a) ] # dp[i][j] stores minimum distance from i to j def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Tuple: """simple docstring""" __snake_case : Union[str, Any] = w def SCREAMING_SNAKE_CASE__ (self) -> Tuple: """simple docstring""" for k in range(0 , self.n): for i in range(0 , self.n): for j in range(0 , self.n): __snake_case : List[Any] = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j]) def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> Optional[int]: """simple docstring""" return self.dp[u][v] if __name__ == "__main__": __A = Graph(5) graph.add_edge(0, 2, 9) graph.add_edge(0, 4, 1_0) graph.add_edge(1, 3, 5) graph.add_edge(2, 3, 7) graph.add_edge(3, 0, 1_0) graph.add_edge(3, 1, 2) graph.add_edge(3, 2, 1) graph.add_edge(3, 4, 6) graph.add_edge(4, 1, 3) graph.add_edge(4, 2, 4) graph.add_edge(4, 3, 9) graph.floyd_warshall() graph.show_min(1, 4) graph.show_min(0, 3)
61
1
'''simple docstring''' from itertools import permutations def _SCREAMING_SNAKE_CASE ( A : tuple ) -> bool: """simple docstring""" if num[3] % 2 != 0: return False if (num[2] + num[3] + num[4]) % 3 != 0: return False if num[5] % 5 != 0: return False __snake_case : List[str] = [7, 11, 13, 17] for i, test in enumerate(A ): if (num[i + 4] * 1_00 + num[i + 5] * 10 + num[i + 6]) % test != 0: return False return True def _SCREAMING_SNAKE_CASE ( A : int = 10 ) -> int: """simple docstring""" return sum( int(''.join(map(A , A ) ) ) for num in permutations(range(A ) ) if is_substring_divisible(A ) ) if __name__ == "__main__": print(f'''{solution() = }''')
61
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL __A = logging.get_logger(__name__) class a_ ( UpperCamelCase_ ): _snake_case = ["""pixel_values"""] def __init__(self , __a = True , __a = None , __a = None , __a = PILImageResampling.BILINEAR , __a = True , __a = 1 / 2_5_5 , __a = True , __a = None , __a = None , **__a , ) -> None: """simple docstring""" super().__init__(**__a) __snake_case : Tuple = size if size is not None else {'shortest_edge': 3_8_4} __snake_case : List[Any] = get_size_dict(__a , default_to_square=__a) __snake_case : int = do_resize __snake_case : List[str] = size # Default value set here for backwards compatibility where the value in config is None __snake_case : Any = crop_pct if crop_pct is not None else 2_2_4 / 2_5_6 __snake_case : Tuple = resample __snake_case : Dict = do_rescale __snake_case : Any = rescale_factor __snake_case : str = do_normalize __snake_case : Union[str, Any] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __snake_case : Dict = image_std if image_std is not None else IMAGENET_STANDARD_STD def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a , __a = PILImageResampling.BICUBIC , __a = None , **__a , ) -> np.ndarray: """simple docstring""" __snake_case : Dict = get_size_dict(__a , default_to_square=__a) if "shortest_edge" not in size: raise ValueError(F"""Size dictionary must contain 'shortest_edge' key. Got {size.keys()}""") __snake_case : List[str] = size['shortest_edge'] if shortest_edge < 3_8_4: # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct __snake_case : Any = int(shortest_edge / crop_pct) __snake_case : Any = get_resize_output_image_size(__a , size=__a , default_to_square=__a) __snake_case : int = resize(image=__a , size=__a , resample=__a , data_format=__a , **__a) # then crop to (shortest_edge, shortest_edge) return center_crop(image=__a , size=(shortest_edge, shortest_edge) , data_format=__a , **__a) else: # warping (no cropping) when evaluated at 384 or larger return resize( __a , size=(shortest_edge, shortest_edge) , resample=__a , data_format=__a , **__a) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a = None , **__a , ) -> Any: """simple docstring""" return rescale(__a , scale=__a , data_format=__a , **__a) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a , __a = None , **__a , ) -> np.ndarray: """simple docstring""" return normalize(__a , mean=__a , std=__a , data_format=__a , **__a) def SCREAMING_SNAKE_CASE__ (self , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = ChannelDimension.FIRST , **__a , ) -> PIL.Image.Image: """simple docstring""" __snake_case : Optional[int] = do_resize if do_resize is not None else self.do_resize __snake_case : Dict = crop_pct if crop_pct is not None else self.crop_pct __snake_case : Tuple = resample if resample is not None else self.resample __snake_case : Any = do_rescale if do_rescale is not None else self.do_rescale __snake_case : Any = rescale_factor if rescale_factor is not None else self.rescale_factor __snake_case : Union[str, Any] = do_normalize if do_normalize is not None else self.do_normalize __snake_case : Optional[int] = image_mean if image_mean is not None else self.image_mean __snake_case : Optional[Any] = image_std if image_std is not None else self.image_std __snake_case : List[str] = size if size is not None else self.size __snake_case : Any = get_size_dict(__a , default_to_square=__a) __snake_case : Dict = make_list_of_images(__a) if not valid_images(__a): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.') if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.') if do_resize and size["shortest_edge"] < 3_8_4 and crop_pct is None: raise ValueError('crop_pct must be specified if size < 384.') if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.') if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.') # All transformations expect numpy arrays. __snake_case : Tuple = [to_numpy_array(__a) for image in images] if do_resize: __snake_case : Optional[int] = [self.resize(image=__a , size=__a , crop_pct=__a , resample=__a) for image in images] if do_rescale: __snake_case : Optional[int] = [self.rescale(image=__a , scale=__a) for image in images] if do_normalize: __snake_case : Any = [self.normalize(image=__a , mean=__a , std=__a) for image in images] __snake_case : Dict = [to_channel_dimension_format(__a , __a) for image in images] __snake_case : Union[str, Any] = {'pixel_values': images} return BatchFeature(data=__a , tensor_type=__a)
61
1
'''simple docstring''' __A = '''0.18.2''' from .configuration_utils import ConfigMixin from .utils import ( OptionalDependencyNotAvailable, is_flax_available, is_inflect_available, is_invisible_watermark_available, is_k_diffusion_available, is_k_diffusion_version, is_librosa_available, is_note_seq_available, is_onnx_available, is_scipy_available, is_torch_available, is_torchsde_available, is_transformers_available, is_transformers_version, is_unidecode_available, logging, ) try: if not is_onnx_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_onnx_objects import * # noqa F403 else: from .pipelines import OnnxRuntimeModel try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_pt_objects import * # noqa F403 else: from .models import ( AutoencoderKL, ControlNetModel, ModelMixin, PriorTransformer, TaFilmDecoder, TransformeraDModel, UNetaDModel, UNetaDConditionModel, UNetaDModel, UNetaDConditionModel, VQModel, ) from .optimization import ( get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, get_scheduler, ) from .pipelines import ( AudioPipelineOutput, ConsistencyModelPipeline, DanceDiffusionPipeline, DDIMPipeline, DDPMPipeline, DiffusionPipeline, DiTPipeline, ImagePipelineOutput, KarrasVePipeline, LDMPipeline, LDMSuperResolutionPipeline, PNDMPipeline, RePaintPipeline, ScoreSdeVePipeline, ) from .schedulers import ( CMStochasticIterativeScheduler, DDIMInverseScheduler, DDIMParallelScheduler, DDIMScheduler, DDPMParallelScheduler, DDPMScheduler, DEISMultistepScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, HeunDiscreteScheduler, IPNDMScheduler, KarrasVeScheduler, KDPMaAncestralDiscreteScheduler, KDPMaDiscreteScheduler, PNDMScheduler, RePaintScheduler, SchedulerMixin, ScoreSdeVeScheduler, UnCLIPScheduler, UniPCMultistepScheduler, VQDiffusionScheduler, ) from .training_utils import EMAModel try: if not (is_torch_available() and is_scipy_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_scipy_objects import * # noqa F403 else: from .schedulers import LMSDiscreteScheduler try: if not (is_torch_available() and is_torchsde_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_torchsde_objects import * # noqa F403 else: from .schedulers import DPMSolverSDEScheduler try: if not (is_torch_available() and is_transformers_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipelines import ( AltDiffusionImgaImgPipeline, AltDiffusionPipeline, AudioLDMPipeline, CycleDiffusionPipeline, IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ImageTextPipelineOutput, KandinskyImgaImgPipeline, KandinskyInpaintPipeline, KandinskyPipeline, KandinskyPriorPipeline, KandinskyVaaControlnetImgaImgPipeline, KandinskyVaaControlnetPipeline, KandinskyVaaImgaImgPipeline, KandinskyVaaInpaintPipeline, KandinskyVaaPipeline, KandinskyVaaPriorEmbaEmbPipeline, KandinskyVaaPriorPipeline, LDMTextToImagePipeline, PaintByExamplePipeline, SemanticStableDiffusionPipeline, ShapEImgaImgPipeline, ShapEPipeline, StableDiffusionAttendAndExcitePipeline, StableDiffusionControlNetImgaImgPipeline, StableDiffusionControlNetInpaintPipeline, StableDiffusionControlNetPipeline, StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionImageVariationPipeline, StableDiffusionImgaImgPipeline, StableDiffusionInpaintPipeline, StableDiffusionInpaintPipelineLegacy, StableDiffusionInstructPixaPixPipeline, StableDiffusionLatentUpscalePipeline, StableDiffusionLDMaDPipeline, StableDiffusionModelEditingPipeline, StableDiffusionPanoramaPipeline, StableDiffusionParadigmsPipeline, StableDiffusionPipeline, StableDiffusionPipelineSafe, StableDiffusionPixaPixZeroPipeline, StableDiffusionSAGPipeline, StableDiffusionUpscalePipeline, StableUnCLIPImgaImgPipeline, StableUnCLIPPipeline, TextToVideoSDPipeline, TextToVideoZeroPipeline, UnCLIPImageVariationPipeline, UnCLIPPipeline, UniDiffuserModel, UniDiffuserPipeline, UniDiffuserTextDecoder, VersatileDiffusionDualGuidedPipeline, VersatileDiffusionImageVariationPipeline, VersatileDiffusionPipeline, VersatileDiffusionTextToImagePipeline, VideoToVideoSDPipeline, VQDiffusionPipeline, ) try: if not (is_torch_available() and is_transformers_available() and is_invisible_watermark_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_invisible_watermark_objects import * # noqa F403 else: from .pipelines import StableDiffusionXLImgaImgPipeline, StableDiffusionXLPipeline try: if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipelines import StableDiffusionKDiffusionPipeline try: if not (is_torch_available() and is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_onnx_objects import * # noqa F403 else: from .pipelines import ( OnnxStableDiffusionImgaImgPipeline, OnnxStableDiffusionInpaintPipeline, OnnxStableDiffusionInpaintPipelineLegacy, OnnxStableDiffusionPipeline, OnnxStableDiffusionUpscalePipeline, StableDiffusionOnnxPipeline, ) try: if not (is_torch_available() and is_librosa_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_librosa_objects import * # noqa F403 else: from .pipelines import AudioDiffusionPipeline, Mel try: if not (is_transformers_available() and is_torch_available() and is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403 else: from .pipelines import SpectrogramDiffusionPipeline try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_flax_objects import * # noqa F403 else: from .models.controlnet_flax import FlaxControlNetModel from .models.modeling_flax_utils import FlaxModelMixin from .models.unet_ad_condition_flax import FlaxUNetaDConditionModel from .models.vae_flax import FlaxAutoencoderKL from .pipelines import FlaxDiffusionPipeline from .schedulers import ( FlaxDDIMScheduler, FlaxDDPMScheduler, FlaxDPMSolverMultistepScheduler, FlaxKarrasVeScheduler, FlaxLMSDiscreteScheduler, FlaxPNDMScheduler, FlaxSchedulerMixin, FlaxScoreSdeVeScheduler, ) try: if not (is_flax_available() and is_transformers_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_flax_and_transformers_objects import * # noqa F403 else: from .pipelines import ( FlaxStableDiffusionControlNetPipeline, FlaxStableDiffusionImgaImgPipeline, FlaxStableDiffusionInpaintPipeline, FlaxStableDiffusionPipeline, ) try: if not (is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_note_seq_objects import * # noqa F403 else: from .pipelines import MidiProcessor
61
'''simple docstring''' from functools import lru_cache @lru_cache def _SCREAMING_SNAKE_CASE ( A : int ) -> int: """simple docstring""" if num < 0: raise ValueError('Number should not be negative.' ) return 1 if num in (0, 1) else num * factorial(num - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
61
1
'''simple docstring''' class a_ : def __init__(self , __a) -> None: """simple docstring""" __snake_case : List[Any] = set_counts __snake_case : List[str] = max(__a) __snake_case : Optional[Any] = len(__a) __snake_case : str = [1] * num_sets __snake_case : List[Any] = list(range(__a)) def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> bool: """simple docstring""" __snake_case : List[Any] = self.get_parent(__a) __snake_case : Union[str, Any] = self.get_parent(__a) 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] __snake_case : Any = 0 __snake_case : int = dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 __snake_case : Optional[int] = self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] __snake_case : Optional[int] = 0 __snake_case : Dict = src_parent __snake_case : Any = self.set_counts[src_parent] __snake_case : List[Any] = max(self.max_set , __a) return True def SCREAMING_SNAKE_CASE__ (self , __a) -> int: """simple docstring""" if self.parents[disj_set] == disj_set: return disj_set __snake_case : Optional[int] = self.get_parent(self.parents[disj_set]) return self.parents[disj_set]
61
'''simple docstring''' import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class a_ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): _snake_case = VQModel _snake_case = """sample""" @property def SCREAMING_SNAKE_CASE__ (self , __a=(3_2, 3_2)) -> str: """simple docstring""" __snake_case : Dict = 4 __snake_case : Optional[int] = 3 __snake_case : str = floats_tensor((batch_size, num_channels) + sizes).to(__a) return {"sample": image} @property def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" return (3, 3_2, 3_2) @property def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" return (3, 3_2, 3_2) def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" __snake_case : Optional[Any] = { 'block_out_channels': [3_2, 6_4], 'in_channels': 3, 'out_channels': 3, 'down_block_types': ['DownEncoderBlock2D', 'DownEncoderBlock2D'], 'up_block_types': ['UpDecoderBlock2D', 'UpDecoderBlock2D'], 'latent_channels': 3, } __snake_case : List[Any] = self.dummy_input return init_dict, inputs_dict def SCREAMING_SNAKE_CASE__ (self) -> Any: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" __snake_case ,__snake_case : List[Any] = VQModel.from_pretrained('fusing/vqgan-dummy' , output_loading_info=__a) self.assertIsNotNone(__a) self.assertEqual(len(loading_info['missing_keys']) , 0) model.to(__a) __snake_case : Any = model(**self.dummy_input) assert image is not None, "Make sure output is not None" def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" __snake_case : Union[str, Any] = VQModel.from_pretrained('fusing/vqgan-dummy') model.to(__a).eval() torch.manual_seed(0) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0) __snake_case : Tuple = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size) __snake_case : Optional[int] = image.to(__a) with torch.no_grad(): __snake_case : List[Any] = model(__a).sample __snake_case : int = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off __snake_case : int = torch.tensor([-0.0_153, -0.4_044, -0.1_880, -0.5_161, -0.2_418, -0.4_072, -0.1_612, -0.0_633, -0.0_143]) # fmt: on self.assertTrue(torch.allclose(__a , __a , atol=1E-3))
61
1
'''simple docstring''' import numpy class a_ : def __init__(self , __a , __a) -> None: """simple docstring""" __snake_case : Union[str, Any] = input_array # Random initial weights are assigned where first argument is the # number of nodes in previous layer and second argument is the # number of nodes in the next layer. # Random initial weights are assigned. # self.input_array.shape[1] is used to represent number of nodes in input layer. # First hidden layer consists of 4 nodes. __snake_case : Any = numpy.random.rand( self.input_array.shape[1] , 4) # Random initial values for the first hidden layer. # First hidden layer has 4 nodes. # Second hidden layer has 3 nodes. __snake_case : Optional[int] = numpy.random.rand( 4 , 3) # Random initial values for the second hidden layer. # Second hidden layer has 3 nodes. # Output layer has 1 node. __snake_case : Dict = numpy.random.rand(3 , 1) # Real output values provided. __snake_case : Union[str, Any] = output_array # Predicted output values by the neural network. # Predicted_output array initially consists of zeroes. __snake_case : Optional[Any] = numpy.zeros(output_array.shape) def SCREAMING_SNAKE_CASE__ (self) -> numpy.ndarray: """simple docstring""" __snake_case : str = sigmoid( numpy.dot(self.input_array , self.input_layer_and_first_hidden_layer_weights)) # layer_between_first_hidden_layer_and_second_hidden_layer is the layer # connecting the first hidden set of nodes with the second hidden set of nodes. __snake_case : List[str] = sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , )) # layer_between_second_hidden_layer_and_output is the layer connecting # second hidden layer with the output node. __snake_case : str = sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , )) return self.layer_between_second_hidden_layer_and_output def SCREAMING_SNAKE_CASE__ (self) -> None: """simple docstring""" __snake_case : Optional[Any] = numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer.T , 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output) , ) __snake_case : Dict = numpy.dot( self.layer_between_input_and_first_hidden_layer.T , numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output) , self.second_hidden_layer_and_output_layer_weights.T , ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer) , ) __snake_case : Dict = numpy.dot( self.input_array.T , numpy.dot( numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output) , self.second_hidden_layer_and_output_layer_weights.T , ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer) , self.first_hidden_layer_and_second_hidden_layer_weights.T , ) * sigmoid_derivative(self.layer_between_input_and_first_hidden_layer) , ) self.input_layer_and_first_hidden_layer_weights += ( updated_input_layer_and_first_hidden_layer_weights ) self.first_hidden_layer_and_second_hidden_layer_weights += ( updated_first_hidden_layer_and_second_hidden_layer_weights ) self.second_hidden_layer_and_output_layer_weights += ( updated_second_hidden_layer_and_output_layer_weights ) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> None: """simple docstring""" for iteration in range(1 , iterations + 1): __snake_case : Any = self.feedforward() self.back_propagation() if give_loss: __snake_case : Union[str, Any] = numpy.mean(numpy.square(output - self.feedforward())) print(F"""Iteration {iteration} Loss: {loss}""") def SCREAMING_SNAKE_CASE__ (self , __a) -> int: """simple docstring""" __snake_case : List[Any] = input_arr __snake_case : int = sigmoid( numpy.dot(self.array , self.input_layer_and_first_hidden_layer_weights)) __snake_case : List[Any] = sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , )) __snake_case : Optional[Any] = sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , )) return int(self.layer_between_second_hidden_layer_and_output > 0.6) def _SCREAMING_SNAKE_CASE ( A : numpy.ndarray ) -> numpy.ndarray: """simple docstring""" return 1 / (1 + numpy.exp(-value )) def _SCREAMING_SNAKE_CASE ( A : numpy.ndarray ) -> numpy.ndarray: """simple docstring""" return (value) * (1 - (value)) def _SCREAMING_SNAKE_CASE ( ) -> int: """simple docstring""" __snake_case : List[Any] = numpy.array( ( [0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1], ) , dtype=numpy.floataa , ) # True output values for the given input values. __snake_case : str = numpy.array(([0], [1], [1], [0], [1], [0], [0], [1]) , dtype=numpy.floataa ) # Calling neural network class. __snake_case : Optional[Any] = TwoHiddenLayerNeuralNetwork( input_array=A , output_array=A ) # Calling training function. # Set give_loss to True if you want to see loss in every iteration. neural_network.train(output=A , iterations=10 , give_loss=A ) return neural_network.predict(numpy.array(([1, 1, 1]) , dtype=numpy.floataa ) ) if __name__ == "__main__": example()
61
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process __A = logging.getLogger(__name__) @dataclass class a_ : _snake_case = field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} ) _snake_case = field( default=UpperCamelCase_ , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) _snake_case = field( default="""NER""" , metadata={"""help""": """Task type to fine tune in training (e.g. NER, POS, etc)"""} ) _snake_case = field( default=UpperCamelCase_ , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} ) _snake_case = field(default=UpperCamelCase_ , metadata={"""help""": """Set this flag to use fast tokenization."""} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. _snake_case = field( default=UpperCamelCase_ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) @dataclass class a_ : _snake_case = field( metadata={"""help""": """The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."""} ) _snake_case = field( default=UpperCamelCase_ , metadata={"""help""": """Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."""} , ) _snake_case = field( default=128 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) _snake_case = field( default=UpperCamelCase_ , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} ) def _SCREAMING_SNAKE_CASE ( ) -> int: """simple docstring""" # 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. __snake_case : List[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. __snake_case ,__snake_case ,__snake_case : List[str] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __snake_case ,__snake_case ,__snake_case : int = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. Use""" ' --overwrite_output_dir to overcome.' ) __snake_case : List[str] = import_module('tasks' ) try: __snake_case : Any = getattr(A , model_args.task_type ) __snake_case : TokenClassificationTask = token_classification_task_clazz() except AttributeError: raise ValueError( F"""Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. """ F"""Available tasks classes are: {TokenClassificationTask.__subclasses__()}""" ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( 'Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('Training/evaluation parameters %s' , A ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task __snake_case : Optional[Any] = token_classification_task.get_labels(data_args.labels ) __snake_case : Dict[int, str] = dict(enumerate(A ) ) __snake_case : Optional[Any] = len(A ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __snake_case : Any = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=A , idalabel=A , labelaid={label: i for i, label in enumerate(A )} , cache_dir=model_args.cache_dir , ) __snake_case : List[str] = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast , ) __snake_case : Optional[int] = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=A , cache_dir=model_args.cache_dir , ) # Get datasets __snake_case : List[Any] = ( TokenClassificationDataset( token_classification_task=A , data_dir=data_args.data_dir , tokenizer=A , labels=A , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) __snake_case : int = ( TokenClassificationDataset( token_classification_task=A , data_dir=data_args.data_dir , tokenizer=A , labels=A , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def align_predictions(A : np.ndarray , A : np.ndarray ) -> Tuple[List[int], List[int]]: __snake_case : str = np.argmax(A , axis=2 ) __snake_case ,__snake_case : int = preds.shape __snake_case : Dict = [[] for _ in range(A )] __snake_case : Union[str, Any] = [[] for _ in range(A )] for i in range(A ): for j in range(A ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(A : EvalPrediction ) -> Dict: __snake_case ,__snake_case : Any = align_predictions(p.predictions , p.label_ids ) return { "accuracy_score": accuracy_score(A , A ), "precision": precision_score(A , A ), "recall": recall_score(A , A ), "f1": fa_score(A , A ), } # Data collator __snake_case : Optional[int] = DataCollatorWithPadding(A , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer __snake_case : Optional[Any] = Trainer( model=A , args=A , train_dataset=A , eval_dataset=A , compute_metrics=A , data_collator=A , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation __snake_case : List[Any] = {} if training_args.do_eval: logger.info('*** Evaluate ***' ) __snake_case : List[str] = trainer.evaluate() __snake_case : Tuple = os.path.join(training_args.output_dir , 'eval_results.txt' ) if trainer.is_world_process_zero(): with open(A , 'w' ) as writer: logger.info('***** Eval results *****' ) for key, value in result.items(): logger.info(' %s = %s' , A , A ) writer.write('%s = %s\n' % (key, value) ) results.update(A ) # Predict if training_args.do_predict: __snake_case : str = TokenClassificationDataset( token_classification_task=A , data_dir=data_args.data_dir , tokenizer=A , labels=A , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , ) __snake_case ,__snake_case ,__snake_case : str = trainer.predict(A ) __snake_case ,__snake_case : List[str] = align_predictions(A , A ) __snake_case : Optional[int] = os.path.join(training_args.output_dir , 'test_results.txt' ) if trainer.is_world_process_zero(): with open(A , 'w' ) as writer: for key, value in metrics.items(): logger.info(' %s = %s' , A , A ) writer.write('%s = %s\n' % (key, value) ) # Save predictions __snake_case : List[str] = os.path.join(training_args.output_dir , 'test_predictions.txt' ) if trainer.is_world_process_zero(): with open(A , 'w' ) as writer: with open(os.path.join(data_args.data_dir , 'test.txt' ) , 'r' ) as f: token_classification_task.write_predictions_to_file(A , A , A ) return results def _SCREAMING_SNAKE_CASE ( A : int ) -> Any: """simple docstring""" # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
61
1
'''simple docstring''' import unittest from transformers import AlbertTokenizer, AlbertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin __A = get_tests_dir('''fixtures/spiece.model''') @require_sentencepiece @require_tokenizers class a_ ( UpperCamelCase_ , unittest.TestCase ): _snake_case = AlbertTokenizer _snake_case = AlbertTokenizerFast _snake_case = True _snake_case = True _snake_case = True def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __snake_case : List[str] = AlbertTokenizer(__a) tokenizer.save_pretrained(self.tmpdirname) def SCREAMING_SNAKE_CASE__ (self , __a) -> List[Any]: """simple docstring""" __snake_case : Tuple = 'this is a test' __snake_case : List[str] = 'this is a test' return input_text, output_text def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" __snake_case : int = '<pad>' __snake_case : Optional[Any] = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__a) , __a) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__a) , __a) def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : Optional[Any] = list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , '<pad>') self.assertEqual(vocab_keys[1] , '<unk>') self.assertEqual(vocab_keys[-1] , '▁eloquent') self.assertEqual(len(__a) , 3_0_0_0_0) def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 3_0_0_0_0) def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" if not self.test_rust_tokenizer: return __snake_case : Optional[int] = self.get_tokenizer() __snake_case : Optional[Any] = self.get_rust_tokenizer() __snake_case : Union[str, Any] = 'I was born in 92000, and this is falsé.' __snake_case : int = tokenizer.tokenize(__a) __snake_case : List[str] = rust_tokenizer.tokenize(__a) self.assertListEqual(__a , __a) __snake_case : int = tokenizer.encode(__a , add_special_tokens=__a) __snake_case : Optional[Any] = rust_tokenizer.encode(__a , add_special_tokens=__a) self.assertListEqual(__a , __a) __snake_case : Union[str, Any] = self.get_rust_tokenizer() __snake_case : int = tokenizer.encode(__a) __snake_case : List[Any] = rust_tokenizer.encode(__a) self.assertListEqual(__a , __a) def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" __snake_case : Tuple = AlbertTokenizer(__a , keep_accents=__a) __snake_case : List[Any] = tokenizer.tokenize('This is a test') self.assertListEqual(__a , ['▁this', '▁is', '▁a', '▁test']) self.assertListEqual(tokenizer.convert_tokens_to_ids(__a) , [4_8, 2_5, 2_1, 1_2_8_9]) __snake_case : Optional[Any] = tokenizer.tokenize('I was born in 92000, and this is falsé.') self.assertListEqual( __a , ['▁i', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', 'é', '.']) __snake_case : int = tokenizer.convert_tokens_to_ids(__a) self.assertListEqual(__a , [3_1, 2_3, 3_8_6, 1_9, 5_6_1, 3_0_5_0, 1_5, 1_7, 4_8, 2_5, 8_2_5_6, 1_8, 1, 9]) __snake_case : Union[str, Any] = tokenizer.convert_ids_to_tokens(__a) self.assertListEqual( __a , ['▁i', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '.'] , ) def SCREAMING_SNAKE_CASE__ (self) -> Any: """simple docstring""" __snake_case : Union[str, Any] = AlbertTokenizer(__a) __snake_case : Tuple = tokenizer.encode('sequence builders') __snake_case : Any = tokenizer.encode('multi-sequence build') __snake_case : List[str] = tokenizer.build_inputs_with_special_tokens(__a) __snake_case : Optional[Any] = tokenizer.build_inputs_with_special_tokens(__a , __a) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [ tokenizer.sep_token_id ] @slow def SCREAMING_SNAKE_CASE__ (self) -> Tuple: """simple docstring""" __snake_case : int = {'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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'input_ids': [[2, 2_1_9_7_0, 1_3, 5, 6_0_9_2, 1_6_7, 2_8, 7_1_0_3, 2_1_5_3, 6_7_3, 8, 7_0_2_8, 1_2_0_5_1, 1_8, 1_7, 7_1_0_3, 2_1_5_3, 6_7_3, 8, 3_5_1_5, 1_8_6_8_4, 8, 4_4_6_1, 6, 1_9_2_7, 2_9_7, 8, 1_2_0_6_0, 2_6_0_7, 1_8, 1_3, 5, 4_4_6_1, 1_5, 1_0_5_3_8, 3_8, 8, 1_3_5, 1_5, 8_2_2, 5_8, 1_5, 9_9_3, 1_0_3_6_3, 1_5, 1_4_6_0, 8_0_0_5, 4_4_6_1, 1_5, 9_9_3, 2_5_5, 2_3_2_8, 9, 9, 9, 6, 2_6, 1_1_1_2, 8_1_6, 3_2_6_0, 1_3, 5, 1_0_3, 2_3_7_7, 6, 1_7, 1_1_1_2, 8_1_6, 2_7_8_2, 1_3, 5, 1_0_3, 1_0_6_4_1, 6, 2_9, 8_4, 2_5_1_2, 2_4_3_0, 7_8_2, 1_8_6_8_4, 2_7_6_1, 1_9, 8_0_8, 2_4_3_0, 2_5_5_6, 1_7, 8_5_5, 1_4_8_0, 9_4_7_7, 4_0_9_1, 1_2_8, 1_1_7_1_2, 1_5, 7_1_0_3, 2_1_5_3, 6_7_3, 1_7, 2_4_8_8_3, 9_9_9_0, 9, 3], [2, 1_1_5_0_2, 2_5, 1_0_0_6, 2_0, 7_8_2, 8, 1_1_8_0_9, 8_5_5, 1_7_3_2, 1_9_3_9_3, 1_8_6_6_7, 3_7, 3_6_7, 2_1_0_1_8, 6_9, 1_8_5_4, 3_4, 1_1_8_6_0, 1_9_1_2_4, 2_7, 1_5_6, 2_2_5, 1_7, 1_9_3, 4_1_4_1, 1_9, 6_5, 9_1_2_4, 9, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 1_4, 2_2_3_1, 8_8_6, 2_3_8_5, 1_7_6_5_9, 8_4, 1_4, 1_6_7_9_2, 1_9_5_2, 9, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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=__a , model_name='albert-base-v2' , revision='6b6560eaf5ff2e250b00c50f380c5389a9c2d82e' , )
61
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( A : list ) -> list: """simple docstring""" __snake_case : Tuple = False while is_sorted is False: # Until all the indices are traversed keep looping __snake_case : Optional[Any] = True for i in range(0 , len(A ) - 1 , 2 ): # iterating over all even indices if input_list[i] > input_list[i + 1]: __snake_case ,__snake_case : int = input_list[i + 1], input_list[i] # swapping if elements not in order __snake_case : List[Any] = False for i in range(1 , len(A ) - 1 , 2 ): # iterating over all odd indices if input_list[i] > input_list[i + 1]: __snake_case ,__snake_case : Tuple = input_list[i + 1], input_list[i] # swapping if elements not in order __snake_case : Any = False return input_list if __name__ == "__main__": print('''Enter list to be sorted''') __A = [int(x) for x in input().split()] # inputing elements of the list in one line __A = odd_even_sort(input_list) print('''The sorted list is''') print(sorted_list)
61
1
'''simple docstring''' from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING __A = logging.get_logger(__name__) @add_end_docstrings(UpperCamelCase_ ) class a_ ( UpperCamelCase_ ): def __init__(self , **__a) -> Optional[Any]: """simple docstring""" super().__init__(**__a) requires_backends(self , 'vision') requires_backends(self , 'torch') if self.framework != "pt": raise ValueError(F"""The {self.__class__} is only available in PyTorch.""") self.check_model_type(__a) def SCREAMING_SNAKE_CASE__ (self , **__a) -> int: """simple docstring""" __snake_case : List[Any] = {} __snake_case : List[str] = {} __snake_case : int = {} # preprocess args if "points_per_batch" in kwargs: __snake_case : Optional[int] = kwargs['points_per_batch'] if "points_per_crop" in kwargs: __snake_case : Dict = kwargs['points_per_crop'] if "crops_n_layers" in kwargs: __snake_case : Dict = kwargs['crops_n_layers'] if "crop_overlap_ratio" in kwargs: __snake_case : int = kwargs['crop_overlap_ratio'] if "crop_n_points_downscale_factor" in kwargs: __snake_case : int = kwargs['crop_n_points_downscale_factor'] # postprocess args if "pred_iou_thresh" in kwargs: __snake_case : Union[str, Any] = kwargs['pred_iou_thresh'] if "stability_score_offset" in kwargs: __snake_case : str = kwargs['stability_score_offset'] if "mask_threshold" in kwargs: __snake_case : Optional[int] = kwargs['mask_threshold'] if "stability_score_thresh" in kwargs: __snake_case : Dict = kwargs['stability_score_thresh'] if "crops_nms_thresh" in kwargs: __snake_case : List[str] = kwargs['crops_nms_thresh'] if "output_rle_mask" in kwargs: __snake_case : Union[str, Any] = kwargs['output_rle_mask'] if "output_bboxes_mask" in kwargs: __snake_case : List[Any] = kwargs['output_bboxes_mask'] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__(self , __a , *__a , __a=None , __a=None , **__a) -> Dict: """simple docstring""" return super().__call__(__a , *__a , num_workers=__a , batch_size=__a , **__a) def SCREAMING_SNAKE_CASE__ (self , __a , __a=6_4 , __a = 0 , __a = 5_1_2 / 1_5_0_0 , __a = 3_2 , __a = 1 , ) -> List[Any]: """simple docstring""" __snake_case : Tuple = load_image(__a) __snake_case : List[Any] = self.image_processor.size['longest_edge'] __snake_case ,__snake_case ,__snake_case ,__snake_case : List[Any] = self.image_processor.generate_crop_boxes( __a , __a , __a , __a , __a , __a) __snake_case : Union[str, Any] = self.image_processor(images=__a , return_tensors='pt') with self.device_placement(): if self.framework == "pt": __snake_case : List[str] = self.get_inference_context() with inference_context(): __snake_case : List[Any] = self._ensure_tensor_on_device(__a , device=self.device) __snake_case : Optional[int] = self.model.get_image_embeddings(model_inputs.pop('pixel_values')) __snake_case : str = image_embeddings __snake_case : Optional[Any] = grid_points.shape[1] __snake_case : Dict = points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( 'Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. ' 'To return all points at once, set points_per_batch to None') for i in range(0 , __a , __a): __snake_case : Union[str, Any] = grid_points[:, i : i + points_per_batch, :, :] __snake_case : Any = input_labels[:, i : i + points_per_batch] __snake_case : Any = i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def SCREAMING_SNAKE_CASE__ (self , __a , __a=0.88 , __a=0.95 , __a=0 , __a=1 , ) -> Optional[int]: """simple docstring""" __snake_case : List[Any] = model_inputs.pop('input_boxes') __snake_case : str = model_inputs.pop('is_last') __snake_case : int = model_inputs.pop('original_sizes').tolist() __snake_case : str = model_inputs.pop('reshaped_input_sizes').tolist() __snake_case : Tuple = self.model(**__a) # post processing happens here in order to avoid CPU GPU copies of ALL the masks __snake_case : str = model_outputs['pred_masks'] __snake_case : Any = self.image_processor.post_process_masks( __a , __a , __a , __a , binarize=__a) __snake_case : Optional[Any] = model_outputs['iou_scores'] __snake_case ,__snake_case ,__snake_case : Optional[int] = self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , __a , __a , __a , __a , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def SCREAMING_SNAKE_CASE__ (self , __a , __a=False , __a=False , __a=0.7 , ) -> List[str]: """simple docstring""" __snake_case : int = [] __snake_case : Optional[Any] = [] __snake_case : int = [] for model_output in model_outputs: all_scores.append(model_output.pop('iou_scores')) all_masks.extend(model_output.pop('masks')) all_boxes.append(model_output.pop('boxes')) __snake_case : Union[str, Any] = torch.cat(__a) __snake_case : Tuple = torch.cat(__a) __snake_case ,__snake_case ,__snake_case ,__snake_case : List[str] = self.image_processor.post_process_for_mask_generation( __a , __a , __a , __a) __snake_case : Any = defaultdict(__a) for output in model_outputs: for k, v in output.items(): extra[k].append(__a) __snake_case : List[str] = {} if output_rle_mask: __snake_case : Optional[int] = rle_mask if output_bboxes_mask: __snake_case : int = bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
61
'''simple docstring''' import argparse import json from collections import OrderedDict from functools import partial from pathlib import Path import timm import torch from huggingface_hub import hf_hub_download from transformers import LevitConfig, LevitForImageClassificationWithTeacher, LevitImageProcessor from transformers.utils import logging logging.set_verbosity_info() __A = logging.get_logger() def _SCREAMING_SNAKE_CASE ( A : int , A : str , A : LevitConfig , A : Path , A : bool = True ) -> Dict: """simple docstring""" print(F"""Converting {name}...""" ) with torch.no_grad(): if hidden_sizes == 1_28: if name[-1] == "S": __snake_case : Optional[int] = timm.create_model('levit_128s' , pretrained=A ) else: __snake_case : Tuple = timm.create_model('levit_128' , pretrained=A ) if hidden_sizes == 1_92: __snake_case : int = timm.create_model('levit_192' , pretrained=A ) if hidden_sizes == 2_56: __snake_case : List[Any] = timm.create_model('levit_256' , pretrained=A ) if hidden_sizes == 3_84: __snake_case : int = timm.create_model('levit_384' , pretrained=A ) from_model.eval() __snake_case : str = LevitForImageClassificationWithTeacher(A ).eval() __snake_case : int = OrderedDict() __snake_case : Optional[Any] = from_model.state_dict() __snake_case : Tuple = list(from_model.state_dict().keys() ) __snake_case : List[str] = list(our_model.state_dict().keys() ) print(len(A ) , len(A ) ) for i in range(len(A ) ): __snake_case : Optional[int] = weights[og_keys[i]] our_model.load_state_dict(A ) __snake_case : Tuple = torch.randn((2, 3, 2_24, 2_24) ) __snake_case : Union[str, Any] = from_model(A ) __snake_case : List[str] = our_model(A ).logits assert torch.allclose(A , A ), "The model logits don't match the original one." __snake_case : int = name print(A ) if push_to_hub: our_model.save_pretrained(save_directory / checkpoint_name ) __snake_case : int = LevitImageProcessor() image_processor.save_pretrained(save_directory / checkpoint_name ) print(F"""Pushed {checkpoint_name}""" ) def _SCREAMING_SNAKE_CASE ( A : Path , A : str = None , A : bool = True ) -> List[Any]: """simple docstring""" __snake_case : Optional[Any] = 'imagenet-1k-id2label.json' __snake_case : Tuple = 10_00 __snake_case : Dict = (1, num_labels) __snake_case : List[str] = 'huggingface/label-files' __snake_case : Any = num_labels __snake_case : str = json.load(open(hf_hub_download(A , A , repo_type='dataset' ) , 'r' ) ) __snake_case : Any = {int(A ): v for k, v in idalabel.items()} __snake_case : int = idalabel __snake_case : Union[str, Any] = {v: k for k, v in idalabel.items()} __snake_case : Optional[int] = partial(A , num_labels=A , idalabel=A , labelaid=A ) __snake_case : Dict = { 'levit-128S': 1_28, 'levit-128': 1_28, 'levit-192': 1_92, 'levit-256': 2_56, 'levit-384': 3_84, } __snake_case : Union[str, Any] = { 'levit-128S': ImageNetPreTrainedConfig( hidden_sizes=[1_28, 2_56, 3_84] , num_attention_heads=[4, 6, 8] , depths=[2, 3, 4] , key_dim=[16, 16, 16] , drop_path_rate=0 , ), 'levit-128': ImageNetPreTrainedConfig( hidden_sizes=[1_28, 2_56, 3_84] , num_attention_heads=[4, 8, 12] , depths=[4, 4, 4] , key_dim=[16, 16, 16] , drop_path_rate=0 , ), 'levit-192': ImageNetPreTrainedConfig( hidden_sizes=[1_92, 2_88, 3_84] , num_attention_heads=[3, 5, 6] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0 , ), 'levit-256': ImageNetPreTrainedConfig( hidden_sizes=[2_56, 3_84, 5_12] , num_attention_heads=[4, 6, 8] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0 , ), 'levit-384': ImageNetPreTrainedConfig( hidden_sizes=[3_84, 5_12, 7_68] , num_attention_heads=[6, 9, 12] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0.1 , ), } if model_name: convert_weight_and_push( names_to_hidden_sizes[model_name] , A , names_to_config[model_name] , A , A ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(names_to_hidden_sizes[model_name] , A , A , A , A ) return config, expected_shape if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default=None, type=str, help='''The name of the model you wish to convert, it must be one of the supported Levit* architecture,''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default='''levit-dump-folder/''', type=Path, required=False, help='''Path to the output PyTorch model directory.''', ) parser.add_argument('''--push_to_hub''', action='''store_true''', help='''Push model and image processor to the hub''') parser.add_argument( '''--no-push_to_hub''', dest='''push_to_hub''', action='''store_false''', help='''Do not push model and image processor to the hub''', ) __A = parser.parse_args() __A = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
61
1
'''simple docstring''' import argparse import logging import pickle import random import time import numpy as np from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO ) __A = logging.getLogger(__name__) def _SCREAMING_SNAKE_CASE ( ) -> int: """simple docstring""" __snake_case : Any = argparse.ArgumentParser( description='Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids).' ) parser.add_argument('--file_path' , type=A , default='data/dump.txt' , help='The path to the data.' ) parser.add_argument('--tokenizer_type' , type=A , default='bert' , choices=['bert', 'roberta', 'gpt2'] ) parser.add_argument('--tokenizer_name' , type=A , default='bert-base-uncased' , help='The tokenizer to use.' ) parser.add_argument('--dump_file' , type=A , default='data/dump' , help='The dump file prefix.' ) __snake_case : Tuple = parser.parse_args() logger.info(F"""Loading Tokenizer ({args.tokenizer_name})""" ) if args.tokenizer_type == "bert": __snake_case : List[Any] = BertTokenizer.from_pretrained(args.tokenizer_name ) __snake_case : Optional[int] = tokenizer.special_tokens_map['cls_token'] # `[CLS]` __snake_case : Union[str, Any] = tokenizer.special_tokens_map['sep_token'] # `[SEP]` elif args.tokenizer_type == "roberta": __snake_case : str = RobertaTokenizer.from_pretrained(args.tokenizer_name ) __snake_case : Any = tokenizer.special_tokens_map['cls_token'] # `<s>` __snake_case : Optional[Any] = tokenizer.special_tokens_map['sep_token'] # `</s>` elif args.tokenizer_type == "gpt2": __snake_case : Any = GPTaTokenizer.from_pretrained(args.tokenizer_name ) __snake_case : List[str] = tokenizer.special_tokens_map['bos_token'] # `<|endoftext|>` __snake_case : Optional[int] = tokenizer.special_tokens_map['eos_token'] # `<|endoftext|>` logger.info(F"""Loading text from {args.file_path}""" ) with open(args.file_path , 'r' , encoding='utf8' ) as fp: __snake_case : str = fp.readlines() logger.info('Start encoding' ) logger.info(F"""{len(A )} examples to process.""" ) __snake_case : int = [] __snake_case : Union[str, Any] = 0 __snake_case : Dict = 1_00_00 __snake_case : int = time.time() for text in data: __snake_case : Optional[Any] = F"""{bos} {text.strip()} {sep}""" __snake_case : Optional[int] = tokenizer.encode(A , add_special_tokens=A ) rslt.append(A ) iter += 1 if iter % interval == 0: __snake_case : Optional[int] = time.time() logger.info(F"""{iter} examples processed. - {(end-start):.2f}s/{interval}expl""" ) __snake_case : str = time.time() logger.info('Finished binarization' ) logger.info(F"""{len(A )} examples processed.""" ) __snake_case : int = F"""{args.dump_file}.{args.tokenizer_name}.pickle""" __snake_case : Tuple = tokenizer.vocab_size if vocab_size < (1 << 16): __snake_case : Optional[Any] = [np.uintaa(A ) for d in rslt] else: __snake_case : Any = [np.intaa(A ) for d in rslt] random.shuffle(rslt_ ) logger.info(F"""Dump to {dp_file}""" ) with open(A , 'wb' ) as handle: pickle.dump(rslt_ , A , protocol=pickle.HIGHEST_PROTOCOL ) if __name__ == "__main__": main()
61
'''simple docstring''' import inspect import unittest from typing import List import numpy as np from transformers import EfficientFormerConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerModel, ) from transformers.models.efficientformer.modeling_tf_efficientformer import ( TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_vision_available(): from PIL import Image from transformers import EfficientFormerImageProcessor class a_ : def __init__(self , __a , __a = 1_3 , __a = 6_4 , __a = 2 , __a = 3 , __a = 3 , __a = True , __a = True , __a = 1_2_8 , __a=[1_6, 3_2, 6_4, 1_2_8] , __a = 7 , __a = 4 , __a = 3_7 , __a = "gelu" , __a = 0.1 , __a = 0.1 , __a = 1_0 , __a = 0.02 , __a = 2 , __a = 1 , __a = 1_2_8 , __a = [2, 2, 2, 2] , __a = 2 , __a = 2 , ) -> str: """simple docstring""" __snake_case : Optional[Any] = parent __snake_case : Optional[int] = batch_size __snake_case : Optional[Any] = image_size __snake_case : Optional[int] = patch_size __snake_case : Optional[Any] = num_channels __snake_case : Optional[Any] = is_training __snake_case : Tuple = use_labels __snake_case : Optional[int] = hidden_size __snake_case : Any = num_hidden_layers __snake_case : List[str] = num_attention_heads __snake_case : Tuple = intermediate_size __snake_case : List[str] = hidden_act __snake_case : Dict = hidden_dropout_prob __snake_case : Any = attention_probs_dropout_prob __snake_case : Dict = type_sequence_label_size __snake_case : str = initializer_range __snake_case : int = encoder_stride __snake_case : List[str] = num_attention_outputs __snake_case : Optional[Any] = embed_dim __snake_case : Optional[Any] = embed_dim + 1 __snake_case : List[str] = resolution __snake_case : Optional[int] = depths __snake_case : List[Any] = hidden_sizes __snake_case : List[str] = dim __snake_case : Union[str, Any] = mlp_expansion_ratio def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" __snake_case : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) __snake_case : List[str] = None if self.use_labels: __snake_case : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size) __snake_case : Tuple = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" return EfficientFormerConfig( 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=__a , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , resolution=self.resolution , depths=self.depths , hidden_sizes=self.hidden_sizes , dim=self.dim , mlp_expansion_ratio=self.mlp_expansion_ratio , ) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Optional[int]: """simple docstring""" __snake_case : Union[str, Any] = TFEfficientFormerModel(config=__a) __snake_case : int = model(__a , training=__a) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Tuple: """simple docstring""" __snake_case : Dict = self.type_sequence_label_size __snake_case : List[Any] = TFEfficientFormerForImageClassification(__a) __snake_case : Optional[int] = model(__a , labels=__a , training=__a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) # test greyscale images __snake_case : List[Any] = 1 __snake_case : List[Any] = TFEfficientFormerForImageClassification(__a) __snake_case : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) __snake_case : str = model(__a , labels=__a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) def SCREAMING_SNAKE_CASE__ (self) -> Any: """simple docstring""" __snake_case : Union[str, Any] = self.prepare_config_and_inputs() __snake_case ,__snake_case ,__snake_case : Union[str, Any] = config_and_inputs __snake_case : Optional[int] = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class a_ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): _snake_case = ( ( TFEfficientFormerModel, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerForImageClassification, ) if is_tf_available() else () ) _snake_case = ( { """feature-extraction""": TFEfficientFormerModel, """image-classification""": ( TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, ), } if is_tf_available() else {} ) _snake_case = False _snake_case = False _snake_case = False _snake_case = False _snake_case = False def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : Dict = TFEfficientFormerModelTester(self) __snake_case : List[Any] = ConfigTester( self , config_class=__a , has_text_modality=__a , hidden_size=3_7) def SCREAMING_SNAKE_CASE__ (self) -> str: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='EfficientFormer does not use inputs_embeds') def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" pass @unittest.skip(reason='EfficientFormer does not support input and output embeddings') def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self) -> Any: """simple docstring""" __snake_case ,__snake_case : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : Optional[int] = model_class(__a) __snake_case : Union[str, Any] = inspect.signature(model.call) # signature.parameters is an OrderedDict => so arg_names order is deterministic __snake_case : Optional[int] = [*signature.parameters.keys()] __snake_case : Dict = ['pixel_values'] self.assertListEqual(arg_names[:1] , __a) def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" def check_hidden_states_output(__a , __a , __a): __snake_case : str = model_class(__a) __snake_case : List[Any] = model(**self._prepare_for_class(__a , __a) , training=__a) __snake_case : str = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __snake_case : Optional[Any] = getattr( self.model_tester , 'expected_num_hidden_layers' , self.model_tester.num_hidden_layers + 1) self.assertEqual(len(__a) , __a) if hasattr(self.model_tester , 'encoder_seq_length'): __snake_case : List[Any] = self.model_tester.encoder_seq_length if hasattr(self.model_tester , 'chunk_length') and self.model_tester.chunk_length > 1: __snake_case : str = seq_length * self.model_tester.chunk_length else: __snake_case : Optional[int] = self.model_tester.seq_length self.assertListEqual( list(hidden_states[-1].shape[-2:]) , [seq_length, self.model_tester.hidden_size] , ) if config.is_encoder_decoder: __snake_case : List[Any] = outputs.decoder_hidden_states self.asseretIsInstance(__a , (list, tuple)) self.assertEqual(len(__a) , __a) __snake_case : List[str] = getattr(self.model_tester , 'seq_length' , __a) __snake_case : Tuple = getattr(self.model_tester , 'decoder_seq_length' , __a) self.assertListEqual( list(hidden_states[-1].shape[-2:]) , [decoder_seq_length, self.model_tester.hidden_size] , ) __snake_case ,__snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : List[str] = True check_hidden_states_output(__a , __a , __a) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __snake_case : str = True check_hidden_states_output(__a , __a , __a) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a=False) -> int: """simple docstring""" __snake_case : Optional[int] = super()._prepare_for_class(__a , __a , return_labels=__a) if return_labels: if model_class.__name__ == "TFEfficientFormerForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" __snake_case : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a) @unittest.skip(reason='EfficientFormer does not implement masked image modeling yet') def SCREAMING_SNAKE_CASE__ (self) -> Tuple: """simple docstring""" __snake_case : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*__a) def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__a) @slow def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case : Any = TFEfficientFormerModel.from_pretrained(__a) self.assertIsNotNone(__a) def SCREAMING_SNAKE_CASE__ (self) -> Tuple: """simple docstring""" __snake_case ,__snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() __snake_case : Tuple = True __snake_case : Optional[Any] = getattr(self.model_tester , 'seq_length' , __a) __snake_case : List[Any] = getattr(self.model_tester , 'encoder_seq_length' , __a) __snake_case : Tuple = getattr(self.model_tester , 'key_length' , __a) __snake_case : Optional[Any] = getattr(self.model_tester , 'chunk_length' , __a) if chunk_length is not None and hasattr(self.model_tester , 'num_hashes'): __snake_case : str = encoder_seq_length * self.model_tester.num_hashes for model_class in self.all_model_classes: __snake_case : Optional[Any] = True __snake_case : Dict = False __snake_case : Optional[int] = True __snake_case : Dict = model_class(__a) __snake_case : Tuple = model(**self._prepare_for_class(__a , __a) , training=__a) __snake_case : Union[str, Any] = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(__a) , self.model_tester.num_attention_outputs) # check that output_attentions also work using config del inputs_dict["output_attentions"] __snake_case : Dict = True __snake_case : str = model_class(__a) __snake_case : str = model(**self._prepare_for_class(__a , __a) , training=__a) __snake_case : Tuple = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(__a) , self.model_tester.num_attention_outputs) if chunk_length is not None: self.assertListEqual( list(attentions[0].shape[-4:]) , [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length] , ) else: self.assertListEqual( list(attentions[0].shape[-3:]) , [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length] , ) def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case ,__snake_case : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # Prepare our model __snake_case : Tuple = model_class(__a) # These are maximally general inputs for the model, with multiple None dimensions # Hopefully this will catch any conditionals that fail for flexible shapes __snake_case : Optional[Any] = { key: tf.keras.Input(shape=val.shape[1:] , dtype=val.dtype , name=__a) for key, val in model.input_signature.items() if key in model.dummy_inputs } __snake_case : Tuple = model(__a) self.assertTrue(outputs_dict is not None) def _SCREAMING_SNAKE_CASE ( ) -> int: """simple docstring""" __snake_case : Tuple = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class a_ ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" return ( EfficientFormerImageProcessor.from_pretrained('snap-research/efficientformer-l1-300') if is_vision_available() else None ) @slow def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" __snake_case : List[str] = TFEfficientFormerForImageClassification.from_pretrained('snap-research/efficientformer-l1-300') __snake_case : Optional[int] = self.default_image_processor __snake_case : List[Any] = prepare_img() __snake_case : List[Any] = image_processor(images=__a , return_tensors='tf') # forward pass __snake_case : List[str] = model(**__a , training=__a) # verify the logits __snake_case : str = tf.TensorShape((1, 1_0_0_0)) self.assertEqual(outputs.logits.shape , __a) __snake_case : Any = tf.constant([-0.0_555, 0.4_825, -0.0_852]) self.assertTrue(np.allclose(outputs.logits[0, :3] , __a , atol=1E-4)) @slow def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" __snake_case : List[Any] = TFEfficientFormerForImageClassificationWithTeacher.from_pretrained( 'snap-research/efficientformer-l1-300') __snake_case : List[Any] = self.default_image_processor __snake_case : Union[str, Any] = prepare_img() __snake_case : List[Any] = image_processor(images=__a , return_tensors='tf') # forward pass __snake_case : Optional[int] = model(**__a , training=__a) # verify the logits __snake_case : Optional[int] = tf.TensorShape((1, 1_0_0_0)) self.assertEqual(outputs.logits.shape , __a) __snake_case : List[str] = tf.constant([-0.1_312, 0.4_353, -1.0_499]) self.assertTrue(np.allclose(outputs.logits[0, :3] , __a , atol=1E-4))
61
1
'''simple docstring''' from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A = { '''configuration_trajectory_transformer''': [ '''TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TrajectoryTransformerConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ '''TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TrajectoryTransformerModel''', '''TrajectoryTransformerPreTrainedModel''', '''load_tf_weights_in_trajectory_transformer''', ] if TYPE_CHECKING: from .configuration_trajectory_transformer import ( TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TrajectoryTransformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trajectory_transformer import ( TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TrajectoryTransformerModel, TrajectoryTransformerPreTrainedModel, load_tf_weights_in_trajectory_transformer, ) else: import sys __A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
61
'''simple docstring''' __A = {str(digit): digit**5 for digit in range(1_0)} def _SCREAMING_SNAKE_CASE ( A : int ) -> int: """simple docstring""" return sum(DIGITS_FIFTH_POWER[digit] for digit in str(A ) ) def _SCREAMING_SNAKE_CASE ( ) -> int: """simple docstring""" return sum( number for number in range(10_00 , 1_00_00_00 ) if number == digits_fifth_powers_sum(A ) ) if __name__ == "__main__": print(solution())
61
1
'''simple docstring''' import gc import unittest import numpy as np import torch from diffusers import StableDiffusionKDiffusionPipeline from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() @slow @require_torch_gpu class a_ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : str = StableDiffusionKDiffusionPipeline.from_pretrained('CompVis/stable-diffusion-v1-4') __snake_case : Optional[Any] = sd_pipe.to(__a) sd_pipe.set_progress_bar_config(disable=__a) sd_pipe.set_scheduler('sample_euler') __snake_case : List[str] = 'A painting of a squirrel eating a burger' __snake_case : List[str] = torch.manual_seed(0) __snake_case : Union[str, Any] = sd_pipe([prompt] , generator=__a , guidance_scale=9.0 , num_inference_steps=2_0 , output_type='np') __snake_case : int = output.images __snake_case : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __snake_case : Optional[Any] = np.array([0.0_447, 0.0_492, 0.0_468, 0.0_408, 0.0_383, 0.0_408, 0.0_354, 0.0_380, 0.0_339]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2 def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" __snake_case : List[str] = StableDiffusionKDiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base') __snake_case : List[Any] = sd_pipe.to(__a) sd_pipe.set_progress_bar_config(disable=__a) sd_pipe.set_scheduler('sample_euler') __snake_case : Tuple = 'A painting of a squirrel eating a burger' __snake_case : List[str] = torch.manual_seed(0) __snake_case : Union[str, Any] = sd_pipe([prompt] , generator=__a , guidance_scale=9.0 , num_inference_steps=2_0 , output_type='np') __snake_case : Optional[Any] = output.images __snake_case : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __snake_case : str = np.array([0.1_237, 0.1_320, 0.1_438, 0.1_359, 0.1_390, 0.1_132, 0.1_277, 0.1_175, 0.1_112]) assert np.abs(image_slice.flatten() - expected_slice).max() < 5E-1 def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" __snake_case : Optional[Any] = StableDiffusionKDiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base') __snake_case : Optional[Any] = sd_pipe.to(__a) sd_pipe.set_progress_bar_config(disable=__a) sd_pipe.set_scheduler('sample_dpmpp_2m') __snake_case : Dict = 'A painting of a squirrel eating a burger' __snake_case : Optional[Any] = torch.manual_seed(0) __snake_case : Union[str, Any] = sd_pipe( [prompt] , generator=__a , guidance_scale=7.5 , num_inference_steps=1_5 , output_type='np' , use_karras_sigmas=__a , ) __snake_case : Optional[Any] = output.images __snake_case : str = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __snake_case : Dict = np.array( [0.11_381_689, 0.12_112_921, 0.1_389_457, 0.12_549_606, 0.1_244_964, 0.10_831_517, 0.11_562_866, 0.10_867_816, 0.10_499_048]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2
61
'''simple docstring''' from __future__ import annotations from collections import deque from collections.abc import Sequence from dataclasses import dataclass from typing import Any @dataclass class a_ : _snake_case = 42 _snake_case = None _snake_case = None def _SCREAMING_SNAKE_CASE ( ) -> Node | None: """simple docstring""" __snake_case : str = Node(1 ) __snake_case : Tuple = Node(2 ) __snake_case : Optional[int] = Node(3 ) __snake_case : List[str] = Node(4 ) __snake_case : List[str] = Node(5 ) return tree def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> list[int]: """simple docstring""" return [root.data, *preorder(root.left ), *preorder(root.right )] if root else [] def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> list[int]: """simple docstring""" return postorder(root.left ) + postorder(root.right ) + [root.data] if root else [] def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> list[int]: """simple docstring""" return [*inorder(root.left ), root.data, *inorder(root.right )] if root else [] def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> int: """simple docstring""" return (max(height(root.left ) , height(root.right ) ) + 1) if root else 0 def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> Sequence[Node | None]: """simple docstring""" __snake_case : list[Any] = [] if root is None: return output __snake_case : Optional[int] = deque([root] ) while process_queue: __snake_case : List[str] = process_queue.popleft() output.append(node.data ) if node.left: process_queue.append(node.left ) if node.right: process_queue.append(node.right ) return output def _SCREAMING_SNAKE_CASE ( A : Node | None , A : int ) -> Sequence[Node | None]: """simple docstring""" __snake_case : list[Any] = [] def populate_output(A : Node | None , A : int ) -> None: if not root: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.left , level - 1 ) populate_output(root.right , level - 1 ) populate_output(A , A ) return output def _SCREAMING_SNAKE_CASE ( A : Node | None , A : int ) -> Sequence[Node | None]: """simple docstring""" __snake_case : list[Any] = [] def populate_output(A : Node | None , A : int ) -> None: if root is None: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.right , level - 1 ) populate_output(root.left , level - 1 ) populate_output(A , A ) return output def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> Sequence[Node | None] | list[Any]: """simple docstring""" if root is None: return [] __snake_case : list[Sequence[Node | None]] = [] __snake_case : List[Any] = 0 __snake_case : int = height(A ) for h in range(1 , height_tree + 1 ): if not flag: output.append(get_nodes_from_left_to_right(A , A ) ) __snake_case : int = 1 else: output.append(get_nodes_from_right_to_left(A , A ) ) __snake_case : Tuple = 0 return output def _SCREAMING_SNAKE_CASE ( ) -> None: # Main function for testing. """simple docstring""" __snake_case : Optional[int] = make_tree() print(F"""In-order Traversal: {inorder(A )}""" ) print(F"""Pre-order Traversal: {preorder(A )}""" ) print(F"""Post-order Traversal: {postorder(A )}""" , '\n' ) print(F"""Height of Tree: {height(A )}""" , '\n' ) print('Complete Level Order Traversal: ' ) print(level_order(A ) , '\n' ) print('Level-wise order Traversal: ' ) for level in range(1 , height(A ) + 1 ): print(F"""Level {level}:""" , get_nodes_from_left_to_right(A , level=A ) ) print('\nZigZag order Traversal: ' ) print(zigzag(A ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
61
1
'''simple docstring''' import argparse import os import shutil from pathlib import Path import onnx import torch from packaging import version from torch.onnx import export from diffusers import OnnxRuntimeModel, OnnxStableDiffusionPipeline, StableDiffusionPipeline __A = version.parse(version.parse(torch.__version__).base_version) < version.parse('''1.11''') def _SCREAMING_SNAKE_CASE ( A : int , A : tuple , A : Path , A : List[Any] , A : List[str] , A : List[str] , A : Dict , A : Any=False , ) -> Dict: """simple docstring""" output_path.parent.mkdir(parents=A , exist_ok=A ) # PyTorch deprecated the `enable_onnx_checker` and `use_external_data_format` arguments in v1.11, # so we check the torch version for backwards compatibility if is_torch_less_than_1_11: export( A , A , f=output_path.as_posix() , input_names=A , output_names=A , dynamic_axes=A , do_constant_folding=A , use_external_data_format=A , enable_onnx_checker=A , opset_version=A , ) else: export( A , A , f=output_path.as_posix() , input_names=A , output_names=A , dynamic_axes=A , do_constant_folding=A , opset_version=A , ) @torch.no_grad() def _SCREAMING_SNAKE_CASE ( A : str , A : str , A : int , A : bool = False ) -> int: """simple docstring""" __snake_case : Optional[Any] = torch.floataa if fpaa else torch.floataa if fpaa and torch.cuda.is_available(): __snake_case : Union[str, Any] = 'cuda' elif fpaa and not torch.cuda.is_available(): raise ValueError('`float16` model export is only supported on GPUs with CUDA' ) else: __snake_case : int = 'cpu' __snake_case : Any = StableDiffusionPipeline.from_pretrained(A , torch_dtype=A ).to(A ) __snake_case : Optional[int] = Path(A ) # TEXT ENCODER __snake_case : Any = pipeline.text_encoder.config.max_position_embeddings __snake_case : Tuple = pipeline.text_encoder.config.hidden_size __snake_case : str = pipeline.tokenizer( 'A sample prompt' , padding='max_length' , max_length=pipeline.tokenizer.model_max_length , truncation=A , return_tensors='pt' , ) onnx_export( pipeline.text_encoder , model_args=(text_input.input_ids.to(device=A , dtype=torch.intaa )) , output_path=output_path / 'text_encoder' / 'model.onnx' , ordered_input_names=['input_ids'] , output_names=['last_hidden_state', 'pooler_output'] , dynamic_axes={ 'input_ids': {0: 'batch', 1: 'sequence'}, } , opset=A , ) del pipeline.text_encoder # UNET __snake_case : List[str] = pipeline.unet.config.in_channels __snake_case : str = pipeline.unet.config.sample_size __snake_case : List[str] = output_path / 'unet' / 'model.onnx' onnx_export( pipeline.unet , model_args=( torch.randn(2 , A , A , A ).to(device=A , dtype=A ), torch.randn(2 ).to(device=A , dtype=A ), torch.randn(2 , A , A ).to(device=A , dtype=A ), False, ) , output_path=A , ordered_input_names=['sample', 'timestep', 'encoder_hidden_states', 'return_dict'] , output_names=['out_sample'] , dynamic_axes={ 'sample': {0: 'batch', 1: 'channels', 2: 'height', 3: 'width'}, 'timestep': {0: 'batch'}, 'encoder_hidden_states': {0: 'batch', 1: 'sequence'}, } , opset=A , use_external_data_format=A , ) __snake_case : Optional[int] = str(unet_path.absolute().as_posix() ) __snake_case : List[Any] = os.path.dirname(A ) __snake_case : List[str] = onnx.load(A ) # clean up existing tensor files shutil.rmtree(A ) os.mkdir(A ) # collate external tensor files into one onnx.save_model( A , A , save_as_external_data=A , all_tensors_to_one_file=A , location='weights.pb' , convert_attribute=A , ) del pipeline.unet # VAE ENCODER __snake_case : Any = pipeline.vae __snake_case : Optional[Any] = vae_encoder.config.in_channels __snake_case : List[Any] = vae_encoder.config.sample_size # need to get the raw tensor output (sample) from the encoder __snake_case : Dict = lambda A , A : vae_encoder.encode(A , A )[0].sample() onnx_export( A , model_args=( torch.randn(1 , A , A , A ).to(device=A , dtype=A ), False, ) , output_path=output_path / 'vae_encoder' / 'model.onnx' , ordered_input_names=['sample', 'return_dict'] , output_names=['latent_sample'] , dynamic_axes={ 'sample': {0: 'batch', 1: 'channels', 2: 'height', 3: 'width'}, } , opset=A , ) # VAE DECODER __snake_case : List[str] = pipeline.vae __snake_case : Any = vae_decoder.config.latent_channels __snake_case : Optional[Any] = vae_decoder.config.out_channels # forward only through the decoder part __snake_case : List[str] = vae_encoder.decode onnx_export( A , model_args=( torch.randn(1 , A , A , A ).to(device=A , dtype=A ), False, ) , output_path=output_path / 'vae_decoder' / 'model.onnx' , ordered_input_names=['latent_sample', 'return_dict'] , output_names=['sample'] , dynamic_axes={ 'latent_sample': {0: 'batch', 1: 'channels', 2: 'height', 3: 'width'}, } , opset=A , ) del pipeline.vae # SAFETY CHECKER if pipeline.safety_checker is not None: __snake_case : int = pipeline.safety_checker __snake_case : List[str] = safety_checker.config.vision_config.num_channels __snake_case : str = safety_checker.config.vision_config.image_size __snake_case : Tuple = safety_checker.forward_onnx onnx_export( pipeline.safety_checker , model_args=( torch.randn( 1 , A , A , A , ).to(device=A , dtype=A ), torch.randn(1 , A , A , A ).to(device=A , dtype=A ), ) , output_path=output_path / 'safety_checker' / 'model.onnx' , ordered_input_names=['clip_input', 'images'] , output_names=['out_images', 'has_nsfw_concepts'] , dynamic_axes={ 'clip_input': {0: 'batch', 1: 'channels', 2: 'height', 3: 'width'}, 'images': {0: 'batch', 1: 'height', 2: 'width', 3: 'channels'}, } , opset=A , ) del pipeline.safety_checker __snake_case : Any = OnnxRuntimeModel.from_pretrained(output_path / 'safety_checker' ) __snake_case : Optional[Any] = pipeline.feature_extractor else: __snake_case : List[str] = None __snake_case : List[str] = None __snake_case : Dict = OnnxStableDiffusionPipeline( vae_encoder=OnnxRuntimeModel.from_pretrained(output_path / 'vae_encoder' ) , vae_decoder=OnnxRuntimeModel.from_pretrained(output_path / 'vae_decoder' ) , text_encoder=OnnxRuntimeModel.from_pretrained(output_path / 'text_encoder' ) , tokenizer=pipeline.tokenizer , unet=OnnxRuntimeModel.from_pretrained(output_path / 'unet' ) , scheduler=pipeline.scheduler , safety_checker=A , feature_extractor=A , requires_safety_checker=safety_checker is not None , ) onnx_pipeline.save_pretrained(A ) print('ONNX pipeline saved to' , A ) del pipeline del onnx_pipeline __snake_case : Any = OnnxStableDiffusionPipeline.from_pretrained(A , provider='CPUExecutionProvider' ) print('ONNX pipeline is loadable' ) if __name__ == "__main__": __A = argparse.ArgumentParser() parser.add_argument( '''--model_path''', type=str, required=True, help='''Path to the `diffusers` checkpoint to convert (either a local directory or on the Hub).''', ) parser.add_argument('''--output_path''', type=str, required=True, help='''Path to the output model.''') parser.add_argument( '''--opset''', default=1_4, type=int, help='''The version of the ONNX operator set to use.''', ) parser.add_argument('''--fp16''', action='''store_true''', default=False, help='''Export the models in `float16` mode''') __A = parser.parse_args() convert_models(args.model_path, args.output_path, args.opset, args.fpaa)
61
'''simple docstring''' from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class a_ : def __init__(self , __a = None) -> None: """simple docstring""" if components is None: __snake_case : List[str] = [] __snake_case : Optional[int] = list(__a) def __len__(self) -> int: """simple docstring""" return len(self.__components) def __str__(self) -> str: """simple docstring""" return "(" + ",".join(map(__a , self.__components)) + ")" def __add__(self , __a) -> Vector: """simple docstring""" __snake_case : Optional[Any] = len(self) if size == len(__a): __snake_case : Optional[int] = [self.__components[i] + other.component(__a) for i in range(__a)] return Vector(__a) else: raise Exception('must have the same size') def __sub__(self , __a) -> Vector: """simple docstring""" __snake_case : Optional[Any] = len(self) if size == len(__a): __snake_case : Optional[int] = [self.__components[i] - other.component(__a) for i in range(__a)] return Vector(__a) else: # error case raise Exception('must have the same size') @overload def __mul__(self , __a) -> Vector: """simple docstring""" ... @overload def __mul__(self , __a) -> float: """simple docstring""" ... def __mul__(self , __a) -> float | Vector: """simple docstring""" if isinstance(__a , (float, int)): __snake_case : str = [c * other for c in self.__components] return Vector(__a) elif isinstance(__a , __a) and len(self) == len(__a): __snake_case : List[Any] = len(self) __snake_case : Dict = [self.__components[i] * other.component(__a) for i in range(__a)] return sum(__a) else: # error case raise Exception('invalid operand!') def SCREAMING_SNAKE_CASE__ (self) -> Vector: """simple docstring""" return Vector(self.__components) def SCREAMING_SNAKE_CASE__ (self , __a) -> float: """simple docstring""" if isinstance(__a , __a) and -len(self.__components) <= i < len(self.__components): return self.__components[i] else: raise Exception('index out of range') def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> None: """simple docstring""" assert -len(self.__components) <= pos < len(self.__components) __snake_case : int = value def SCREAMING_SNAKE_CASE__ (self) -> float: """simple docstring""" if len(self.__components) == 0: raise Exception('Vector is empty') __snake_case : Tuple = [c**2 for c in self.__components] return math.sqrt(sum(__a)) def SCREAMING_SNAKE_CASE__ (self , __a , __a = False) -> float: """simple docstring""" __snake_case : Tuple = self * other __snake_case : Optional[int] = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den)) else: return math.acos(num / den) def _SCREAMING_SNAKE_CASE ( A : int ) -> Vector: """simple docstring""" assert isinstance(A , A ) return Vector([0] * dimension ) def _SCREAMING_SNAKE_CASE ( A : int , A : int ) -> Vector: """simple docstring""" assert isinstance(A , A ) and (isinstance(A , A )) __snake_case : Any = [0] * dimension __snake_case : int = 1 return Vector(A ) def _SCREAMING_SNAKE_CASE ( A : float , A : Vector , A : Vector ) -> Vector: """simple docstring""" assert ( isinstance(A , A ) and isinstance(A , A ) and (isinstance(A , (int, float) )) ) return x * scalar + y def _SCREAMING_SNAKE_CASE ( A : int , A : int , A : int ) -> Vector: """simple docstring""" random.seed(A ) __snake_case : List[Any] = [random.randint(A , A ) for _ in range(A )] return Vector(A ) class a_ : def __init__(self , __a , __a , __a) -> None: """simple docstring""" __snake_case : Union[str, Any] = matrix __snake_case : int = w __snake_case : str = h def __str__(self) -> str: """simple docstring""" __snake_case : Dict = '' for i in range(self.__height): ans += "|" for j in range(self.__width): if j < self.__width - 1: ans += str(self.__matrix[i][j]) + "," else: ans += str(self.__matrix[i][j]) + "|\n" return ans def __add__(self , __a) -> Matrix: """simple docstring""" if self.__width == other.width() and self.__height == other.height(): __snake_case : Tuple = [] for i in range(self.__height): __snake_case : List[Any] = [ self.__matrix[i][j] + other.component(__a , __a) for j in range(self.__width) ] matrix.append(__a) return Matrix(__a , self.__width , self.__height) else: raise Exception('matrix must have the same dimension!') def __sub__(self , __a) -> Matrix: """simple docstring""" if self.__width == other.width() and self.__height == other.height(): __snake_case : str = [] for i in range(self.__height): __snake_case : List[str] = [ self.__matrix[i][j] - other.component(__a , __a) for j in range(self.__width) ] matrix.append(__a) return Matrix(__a , self.__width , self.__height) else: raise Exception('matrices must have the same dimension!') @overload def __mul__(self , __a) -> Matrix: """simple docstring""" ... @overload def __mul__(self , __a) -> Vector: """simple docstring""" ... def __mul__(self , __a) -> Vector | Matrix: """simple docstring""" if isinstance(__a , __a): # matrix-vector if len(__a) == self.__width: __snake_case : Tuple = zero_vector(self.__height) for i in range(self.__height): __snake_case : Union[str, Any] = [ self.__matrix[i][j] * other.component(__a) for j in range(self.__width) ] ans.change_component(__a , sum(__a)) return ans else: raise Exception( 'vector must have the same size as the ' 'number of columns of the matrix!') elif isinstance(__a , (int, float)): # matrix-scalar __snake_case : str = [ [self.__matrix[i][j] * other for j in range(self.__width)] for i in range(self.__height) ] return Matrix(__a , self.__width , self.__height) return None def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" return self.__height def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" return self.__width def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> float: """simple docstring""" if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception('change_component: indices out of bounds') def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> None: """simple docstring""" if 0 <= x < self.__height and 0 <= y < self.__width: __snake_case : List[Any] = value else: raise Exception('change_component: indices out of bounds') def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> float: """simple docstring""" if self.__height != self.__width: raise Exception('Matrix is not square') __snake_case : List[Any] = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(__a)): __snake_case : Tuple = minor[i][:y] + minor[i][y + 1 :] return Matrix(__a , self.__width - 1 , self.__height - 1).determinant() def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> float: """simple docstring""" if self.__height != self.__width: raise Exception('Matrix is not square') if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(__a , __a) else: raise Exception('Indices out of bounds') def SCREAMING_SNAKE_CASE__ (self) -> float: """simple docstring""" if self.__height != self.__width: raise Exception('Matrix is not square') if self.__height < 1: raise Exception('Matrix has no element') elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: __snake_case : Any = [ self.__matrix[0][y] * self.cofactor(0 , __a) for y in range(self.__width) ] return sum(__a) def _SCREAMING_SNAKE_CASE ( A : int ) -> Matrix: """simple docstring""" __snake_case : list[list[float]] = [[0] * n for _ in range(A )] return Matrix(A , A , A ) def _SCREAMING_SNAKE_CASE ( A : int , A : int , A : int , A : int ) -> Matrix: """simple docstring""" random.seed(A ) __snake_case : list[list[float]] = [ [random.randint(A , A ) for _ in range(A )] for _ in range(A ) ] return Matrix(A , A , A )
61
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __A = { '''configuration_biogpt''': ['''BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BioGptConfig'''], '''tokenization_biogpt''': ['''BioGptTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ '''BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BioGptForCausalLM''', '''BioGptForTokenClassification''', '''BioGptForSequenceClassification''', '''BioGptModel''', '''BioGptPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
61
'''simple docstring''' import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification if is_tf_available(): from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification if is_flax_available(): from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification __A = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co __A = '''main''' # Default branch name __A = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2''' # One particular commit (not the top of `main`) __A = '''aaaaaaa''' # This commit does not exist, so we should 404. __A = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684''' # Sha-1 of config.json on the top of `main`, for checking purposes __A = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3''' @contextlib.contextmanager def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: """simple docstring""" print('Welcome!' ) yield print('Bye!' ) @contextlib.contextmanager def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]: """simple docstring""" print('Bonjour!' ) yield print('Au revoir!' ) class a_ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" assert transformers.__spec__ is not None assert importlib.util.find_spec('transformers') is not None class a_ ( unittest.TestCase ): @unittest.mock.patch('sys.stdout' , new_callable=io.StringIO) def SCREAMING_SNAKE_CASE__ (self , __a) -> int: """simple docstring""" with ContextManagers([]): print('Transformers are awesome!') # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue() , 'Transformers are awesome!\n') @unittest.mock.patch('sys.stdout' , new_callable=io.StringIO) def SCREAMING_SNAKE_CASE__ (self , __a) -> List[str]: """simple docstring""" with ContextManagers([context_en()]): print('Transformers are awesome!') # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue() , 'Welcome!\nTransformers are awesome!\nBye!\n') @unittest.mock.patch('sys.stdout' , new_callable=io.StringIO) def SCREAMING_SNAKE_CASE__ (self , __a) -> Tuple: """simple docstring""" with ContextManagers([context_fr(), context_en()]): print('Transformers are awesome!') # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue() , 'Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n') @require_torch def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" self.assertEqual(find_labels(__a) , ['labels']) self.assertEqual(find_labels(__a) , ['labels', 'next_sentence_label']) self.assertEqual(find_labels(__a) , ['start_positions', 'end_positions']) class a_ ( UpperCamelCase_ ): pass self.assertEqual(find_labels(__a) , ['labels']) @require_tf def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" self.assertEqual(find_labels(__a) , ['labels']) self.assertEqual(find_labels(__a) , ['labels', 'next_sentence_label']) self.assertEqual(find_labels(__a) , ['start_positions', 'end_positions']) class a_ ( UpperCamelCase_ ): pass self.assertEqual(find_labels(__a) , ['labels']) @require_flax def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" self.assertEqual(find_labels(__a) , []) self.assertEqual(find_labels(__a) , []) self.assertEqual(find_labels(__a) , []) class a_ ( UpperCamelCase_ ): pass self.assertEqual(find_labels(__a) , [])
61
1
'''simple docstring''' import json import os import shutil import warnings from argparse import ArgumentParser, Namespace from pathlib import Path from typing import List from ..utils import logging from . import BaseTransformersCLICommand try: from cookiecutter.main import cookiecutter __A = True except ImportError: __A = False __A = logging.get_logger(__name__) # pylint: disable=invalid-name def _SCREAMING_SNAKE_CASE ( A : Namespace ) -> str: """simple docstring""" return AddNewModelCommand(args.testing , args.testing_file , path=args.path ) class a_ ( UpperCamelCase_ ): @staticmethod def SCREAMING_SNAKE_CASE__ (__a) -> Union[str, Any]: """simple docstring""" __snake_case : Optional[Any] = parser.add_parser('add-new-model') add_new_model_parser.add_argument('--testing' , action='store_true' , help='If in testing mode.') add_new_model_parser.add_argument('--testing_file' , type=__a , help='Configuration file on which to run.') add_new_model_parser.add_argument( '--path' , type=__a , help='Path to cookiecutter. Should only be used for testing purposes.') add_new_model_parser.set_defaults(func=__a) def __init__(self , __a , __a , __a=None , *__a) -> int: """simple docstring""" __snake_case : Optional[int] = testing __snake_case : List[str] = testing_file __snake_case : Optional[Any] = path def SCREAMING_SNAKE_CASE__ (self) -> Any: """simple docstring""" warnings.warn( 'The command `transformers-cli add-new-model` is deprecated and will be removed in v5 of Transformers. ' 'It is not actively maintained anymore, so might give a result that won\'t pass all tests and quality ' 'checks, you should use `transformers-cli add-new-model-like` instead.') if not _has_cookiecutter: raise ImportError( 'Model creation dependencies are required to use the `add_new_model` command. Install them by running ' 'the following at the root of your `transformers` clone:\n\n\t$ pip install -e .[modelcreation]\n') # Ensure that there is no other `cookiecutter-template-xxx` directory in the current working directory __snake_case : Any = [directory for directory in os.listdir() if 'cookiecutter-template-' == directory[:2_2]] if len(__a) > 0: raise ValueError( 'Several directories starting with `cookiecutter-template-` in current working directory. ' 'Please clean your directory by removing all folders starting with `cookiecutter-template-` or ' 'change your working directory.') __snake_case : Union[str, Any] = ( Path(__a).parent.parent.parent.parent if self._path is None else Path(self._path).parent.parent ) __snake_case : str = path_to_transformer_root / 'templates' / 'adding_a_new_model' # Execute cookiecutter if not self._testing: cookiecutter(str(__a)) else: with open(self._testing_file , 'r') as configuration_file: __snake_case : List[Any] = json.load(__a) cookiecutter( str(path_to_cookiecutter if self._path is None else self._path) , no_input=__a , extra_context=__a , ) __snake_case : Union[str, Any] = [directory for directory in os.listdir() if 'cookiecutter-template-' in directory[:2_2]][0] # Retrieve configuration with open(directory + '/configuration.json' , 'r') as configuration_file: __snake_case : List[str] = json.load(__a) __snake_case : Optional[Any] = configuration['lowercase_modelname'] __snake_case : List[Any] = configuration['generate_tensorflow_pytorch_and_flax'] os.remove(F"""{directory}/configuration.json""") __snake_case : str = 'PyTorch' in generate_tensorflow_pytorch_and_flax __snake_case : str = 'TensorFlow' in generate_tensorflow_pytorch_and_flax __snake_case : Any = 'Flax' in generate_tensorflow_pytorch_and_flax __snake_case : Optional[Any] = F"""{path_to_transformer_root}/src/transformers/models/{lowercase_model_name}""" os.makedirs(__a , exist_ok=__a) os.makedirs(F"""{path_to_transformer_root}/tests/models/{lowercase_model_name}""" , exist_ok=__a) # Tests require submodules as they have parent imports with open(F"""{path_to_transformer_root}/tests/models/{lowercase_model_name}/__init__.py""" , 'w'): pass shutil.move( F"""{directory}/__init__.py""" , F"""{model_dir}/__init__.py""" , ) shutil.move( F"""{directory}/configuration_{lowercase_model_name}.py""" , F"""{model_dir}/configuration_{lowercase_model_name}.py""" , ) def remove_copy_lines(__a): with open(__a , 'r') as f: __snake_case : Optional[int] = f.readlines() with open(__a , 'w') as f: for line in lines: if "# Copied from transformers." not in line: f.write(__a) if output_pytorch: if not self._testing: remove_copy_lines(F"""{directory}/modeling_{lowercase_model_name}.py""") shutil.move( F"""{directory}/modeling_{lowercase_model_name}.py""" , F"""{model_dir}/modeling_{lowercase_model_name}.py""" , ) shutil.move( F"""{directory}/test_modeling_{lowercase_model_name}.py""" , F"""{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_{lowercase_model_name}.py""" , ) else: os.remove(F"""{directory}/modeling_{lowercase_model_name}.py""") os.remove(F"""{directory}/test_modeling_{lowercase_model_name}.py""") if output_tensorflow: if not self._testing: remove_copy_lines(F"""{directory}/modeling_tf_{lowercase_model_name}.py""") shutil.move( F"""{directory}/modeling_tf_{lowercase_model_name}.py""" , F"""{model_dir}/modeling_tf_{lowercase_model_name}.py""" , ) shutil.move( F"""{directory}/test_modeling_tf_{lowercase_model_name}.py""" , F"""{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_tf_{lowercase_model_name}.py""" , ) else: os.remove(F"""{directory}/modeling_tf_{lowercase_model_name}.py""") os.remove(F"""{directory}/test_modeling_tf_{lowercase_model_name}.py""") if output_flax: if not self._testing: remove_copy_lines(F"""{directory}/modeling_flax_{lowercase_model_name}.py""") shutil.move( F"""{directory}/modeling_flax_{lowercase_model_name}.py""" , F"""{model_dir}/modeling_flax_{lowercase_model_name}.py""" , ) shutil.move( F"""{directory}/test_modeling_flax_{lowercase_model_name}.py""" , F"""{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_flax_{lowercase_model_name}.py""" , ) else: os.remove(F"""{directory}/modeling_flax_{lowercase_model_name}.py""") os.remove(F"""{directory}/test_modeling_flax_{lowercase_model_name}.py""") shutil.move( F"""{directory}/{lowercase_model_name}.md""" , F"""{path_to_transformer_root}/docs/source/en/model_doc/{lowercase_model_name}.md""" , ) shutil.move( F"""{directory}/tokenization_{lowercase_model_name}.py""" , F"""{model_dir}/tokenization_{lowercase_model_name}.py""" , ) shutil.move( F"""{directory}/tokenization_fast_{lowercase_model_name}.py""" , F"""{model_dir}/tokenization_{lowercase_model_name}_fast.py""" , ) from os import fdopen, remove from shutil import copymode, move from tempfile import mkstemp def replace(__a , __a , __a): # Create temp file __snake_case ,__snake_case : Any = mkstemp() __snake_case : Any = False with fdopen(__a , 'w') as new_file: with open(__a) as old_file: for line in old_file: new_file.write(__a) if line_to_copy_below in line: __snake_case : Union[str, Any] = True for line_to_copy in lines_to_copy: new_file.write(__a) if not line_found: raise ValueError(F"""Line {line_to_copy_below} was not found in file.""") # Copy the file permissions from the old file to the new file copymode(__a , __a) # Remove original file remove(__a) # Move new file move(__a , __a) def skip_units(__a): return ( ("generating PyTorch" in line and not output_pytorch) or ("generating TensorFlow" in line and not output_tensorflow) or ("generating Flax" in line and not output_flax) ) def replace_in_files(__a): with open(__a) as datafile: __snake_case : Optional[Any] = [] __snake_case : Optional[int] = False __snake_case : List[Any] = False for line in datafile: if "# To replace in: " in line and "##" not in line: __snake_case : Optional[int] = line.split('"')[1] __snake_case : Dict = skip_units(__a) elif "# Below: " in line and "##" not in line: __snake_case : Optional[Any] = line.split('"')[1] __snake_case : Union[str, Any] = skip_units(__a) elif "# End." in line and "##" not in line: if not skip_file and not skip_snippet: replace(__a , __a , __a) __snake_case : List[Any] = [] elif "# Replace with" in line and "##" not in line: __snake_case : List[str] = [] elif "##" not in line: lines_to_copy.append(__a) remove(__a) replace_in_files(F"""{directory}/to_replace_{lowercase_model_name}.py""") os.rmdir(__a)
61
'''simple docstring''' # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A = {'''configuration_timm_backbone''': ['''TimmBackboneConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ['''TimmBackbone'''] if TYPE_CHECKING: from .configuration_timm_backbone import TimmBackboneConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timm_backbone import TimmBackbone else: import sys __A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
61
1
'''simple docstring''' import unittest import torch from torch import nn from accelerate.test_utils import require_cuda from accelerate.utils.memory import find_executable_batch_size, release_memory def _SCREAMING_SNAKE_CASE ( ) -> Any: """simple docstring""" raise RuntimeError('CUDA out of memory.' ) class a_ ( nn.Module ): def __init__(self) -> int: """simple docstring""" super().__init__() __snake_case : Any = nn.Linear(3 , 4) __snake_case : List[str] = nn.BatchNormad(4) __snake_case : Any = nn.Linear(4 , 5) def SCREAMING_SNAKE_CASE__ (self , __a) -> List[Any]: """simple docstring""" return self.lineara(self.batchnorm(self.lineara(__a))) class a_ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ (self) -> str: """simple docstring""" __snake_case : List[str] = [] @find_executable_batch_size(starting_batch_size=1_2_8) def mock_training_loop_function(__a): nonlocal batch_sizes batch_sizes.append(__a) if batch_size != 8: raise_fake_out_of_memory() mock_training_loop_function() self.assertListEqual(__a , [1_2_8, 6_4, 3_2, 1_6, 8]) def SCREAMING_SNAKE_CASE__ (self) -> Any: """simple docstring""" __snake_case : Tuple = [] @find_executable_batch_size(starting_batch_size=1_2_8) def mock_training_loop_function(__a , __a): nonlocal batch_sizes batch_sizes.append(__a) if batch_size != 8: raise_fake_out_of_memory() return batch_size, arga __snake_case ,__snake_case : List[str] = mock_training_loop_function('hello') self.assertListEqual(__a , [1_2_8, 6_4, 3_2, 1_6, 8]) self.assertListEqual([bs, arga] , [8, 'hello']) def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" @find_executable_batch_size(starting_batch_size=0) def mock_training_loop_function(__a): pass with self.assertRaises(__a) as cm: mock_training_loop_function() self.assertIn('No executable batch size found, reached zero.' , cm.exception.args[0]) def SCREAMING_SNAKE_CASE__ (self) -> Any: """simple docstring""" @find_executable_batch_size(starting_batch_size=1_6) def mock_training_loop_function(__a): if batch_size > 0: raise_fake_out_of_memory() pass with self.assertRaises(__a) as cm: mock_training_loop_function() self.assertIn('No executable batch size found, reached zero.' , cm.exception.args[0]) def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" @find_executable_batch_size(starting_batch_size=1_2_8) def mock_training_loop_function(__a , __a , __a): if batch_size != 8: raise raise_fake_out_of_memory() with self.assertRaises(__a) as cm: mock_training_loop_function(1_2_8 , 'hello' , 'world') self.assertIn('Batch size was passed into `f`' , cm.exception.args[0]) self.assertIn('`f(arg1=\'hello\', arg2=\'world\')' , cm.exception.args[0]) def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" @find_executable_batch_size(starting_batch_size=1_6) def mock_training_loop_function(__a): raise ValueError('Oops, we had an error!') with self.assertRaises(__a) as cm: mock_training_loop_function() self.assertIn('Oops, we had an error!' , cm.exception.args[0]) @require_cuda def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : Any = torch.cuda.memory_allocated() __snake_case : List[str] = ModelForTest() model.cuda() self.assertGreater(torch.cuda.memory_allocated() , __a) __snake_case : List[str] = release_memory(__a) self.assertEqual(torch.cuda.memory_allocated() , __a)
61
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( A : int ) -> int: """simple docstring""" __snake_case : str = 1 for i in range(1 , num + 1 ): fact *= i return fact def _SCREAMING_SNAKE_CASE ( A : int ) -> int: """simple docstring""" __snake_case : Union[str, Any] = 0 while number > 0: __snake_case : Dict = number % 10 sum_of_digits += last_digit __snake_case : Union[str, Any] = number // 10 # Removing the last_digit from the given number return sum_of_digits def _SCREAMING_SNAKE_CASE ( A : int = 1_00 ) -> int: """simple docstring""" __snake_case : List[Any] = factorial(A ) __snake_case : Dict = split_and_add(A ) return result if __name__ == "__main__": print(solution(int(input('''Enter the Number: ''').strip())))
61
1
'''simple docstring''' import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask __A = logging.getLogger(__name__) class a_ ( UpperCamelCase_ ): def __init__(self , __a=-1) -> Dict: """simple docstring""" __snake_case : List[Any] = label_idx def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> List[InputExample]: """simple docstring""" if isinstance(__a , __a): __snake_case : Dict = mode.value __snake_case : Tuple = os.path.join(__a , F"""{mode}.txt""") __snake_case : Any = 1 __snake_case : int = [] with open(__a , encoding='utf-8') as f: __snake_case : int = [] __snake_case : int = [] for line in f: if line.startswith('-DOCSTART-') or line == "" or line == "\n": if words: examples.append(InputExample(guid=F"""{mode}-{guid_index}""" , words=__a , labels=__a)) guid_index += 1 __snake_case : Optional[Any] = [] __snake_case : int = [] else: __snake_case : List[Any] = line.split(' ') words.append(splits[0]) if len(__a) > 1: labels.append(splits[self.label_idx].replace('\n' , '')) else: # Examples could have no label for mode = "test" labels.append('O') if words: examples.append(InputExample(guid=F"""{mode}-{guid_index}""" , words=__a , labels=__a)) return examples def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Any: """simple docstring""" __snake_case : List[Any] = 0 for line in test_input_reader: if line.startswith('-DOCSTART-') or line == "" or line == "\n": writer.write(__a) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: __snake_case : List[Any] = line.split()[0] + ' ' + preds_list[example_id].pop(0) + '\n' writer.write(__a) else: logger.warning('Maximum sequence length exceeded: No prediction for \'%s\'.' , line.split()[0]) def SCREAMING_SNAKE_CASE__ (self , __a) -> List[str]: """simple docstring""" if path: with open(__a , 'r') as f: __snake_case : Tuple = f.read().splitlines() if "O" not in labels: __snake_case : Union[str, Any] = ['O'] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class a_ ( UpperCamelCase_ ): def __init__(self) -> str: """simple docstring""" super().__init__(label_idx=-2) def SCREAMING_SNAKE_CASE__ (self , __a) -> List[str]: """simple docstring""" if path: with open(__a , 'r') as f: __snake_case : Any = f.read().splitlines() if "O" not in labels: __snake_case : List[Any] = ['O'] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class a_ ( UpperCamelCase_ ): def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> List[InputExample]: """simple docstring""" if isinstance(__a , __a): __snake_case : List[Any] = mode.value __snake_case : Dict = os.path.join(__a , F"""{mode}.txt""") __snake_case : Union[str, Any] = 1 __snake_case : Union[str, Any] = [] with open(__a , encoding='utf-8') as f: for sentence in parse_incr(__a): __snake_case : Any = [] __snake_case : Dict = [] for token in sentence: words.append(token['form']) labels.append(token['upos']) assert len(__a) == len(__a) if words: examples.append(InputExample(guid=F"""{mode}-{guid_index}""" , words=__a , labels=__a)) guid_index += 1 return examples def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> List[Any]: """simple docstring""" __snake_case : int = 0 for sentence in parse_incr(__a): __snake_case : Optional[Any] = preds_list[example_id] __snake_case : Any = '' for token in sentence: out += F"""{token["form"]} ({token["upos"]}|{s_p.pop(0)}) """ out += "\n" writer.write(__a) example_id += 1 def SCREAMING_SNAKE_CASE__ (self , __a) -> List[str]: """simple docstring""" if path: with open(__a , 'r') as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
61
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor class a_ ( unittest.TestCase ): def __init__(self , __a , __a=7 , __a=3 , __a=1_8 , __a=3_0 , __a=4_0_0 , __a=True , __a=None , __a=True , __a=None , __a=True , __a=[0.48_145_466, 0.4_578_275, 0.40_821_073] , __a=[0.26_862_954, 0.26_130_258, 0.27_577_711] , __a=True , ) -> List[Any]: """simple docstring""" __snake_case : Tuple = size if size is not None else {'height': 2_2_4, 'width': 2_2_4} __snake_case : Any = crop_size if crop_size is not None else {'height': 1_8, 'width': 1_8} __snake_case : Optional[int] = parent __snake_case : Dict = batch_size __snake_case : str = num_channels __snake_case : Optional[Any] = image_size __snake_case : Optional[int] = min_resolution __snake_case : Tuple = max_resolution __snake_case : Optional[int] = do_resize __snake_case : Optional[int] = size __snake_case : Union[str, Any] = do_center_crop __snake_case : List[Any] = crop_size __snake_case : int = do_normalize __snake_case : Optional[Any] = image_mean __snake_case : str = image_std __snake_case : Optional[Any] = do_convert_rgb def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def SCREAMING_SNAKE_CASE__ (self , __a=False , __a=False , __a=False) -> List[str]: """simple docstring""" assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" if equal_resolution: __snake_case : Optional[int] = [] for i in range(self.batch_size): image_inputs.append( np.random.randint( 2_5_5 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta)) else: __snake_case : Dict = [] for i in range(self.batch_size): __snake_case ,__snake_case : Optional[Any] = np.random.choice(np.arange(self.min_resolution , self.max_resolution) , 2) image_inputs.append(np.random.randint(2_5_5 , size=(self.num_channels, width, height) , dtype=np.uinta)) if not numpify and not torchify: # PIL expects the channel dimension as last dimension __snake_case : int = [Image.fromarray(np.moveaxis(__a , 0 , -1)) for x in image_inputs] if torchify: __snake_case : List[Any] = [torch.from_numpy(__a) for x in image_inputs] return image_inputs @require_torch @require_vision class a_ ( UpperCamelCase_ , unittest.TestCase ): _snake_case = ChineseCLIPImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : Union[str, Any] = ChineseCLIPImageProcessingTester(self , do_center_crop=__a) @property def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : int = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(__a , 'do_resize')) self.assertTrue(hasattr(__a , 'size')) self.assertTrue(hasattr(__a , 'do_center_crop')) self.assertTrue(hasattr(__a , 'center_crop')) self.assertTrue(hasattr(__a , 'do_normalize')) self.assertTrue(hasattr(__a , 'image_mean')) self.assertTrue(hasattr(__a , 'image_std')) self.assertTrue(hasattr(__a , 'do_convert_rgb')) def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size , {'height': 2_2_4, 'width': 2_2_4}) self.assertEqual(image_processor.crop_size , {'height': 1_8, 'width': 1_8}) __snake_case : List[str] = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 , crop_size=8_4) self.assertEqual(image_processor.size , {'shortest_edge': 4_2}) self.assertEqual(image_processor.crop_size , {'height': 8_4, 'width': 8_4}) def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" __snake_case : List[Any] = self.image_processing_class(**self.image_processor_dict) # create random PIL images __snake_case : Optional[Any] = self.image_processor_tester.prepare_inputs(equal_resolution=__a) for image in image_inputs: self.assertIsInstance(__a , Image.Image) # Test not batched input __snake_case : 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __snake_case : List[Any] = image_processing(__a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" __snake_case : Union[str, Any] = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors __snake_case : Optional[int] = self.image_processor_tester.prepare_inputs(equal_resolution=__a , numpify=__a) for image in image_inputs: self.assertIsInstance(__a , np.ndarray) # Test not batched input __snake_case : List[Any] = image_processing(image_inputs[0] , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __snake_case : int = image_processing(__a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : Any = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors __snake_case : Tuple = self.image_processor_tester.prepare_inputs(equal_resolution=__a , torchify=__a) for image in image_inputs: self.assertIsInstance(__a , torch.Tensor) # Test not batched input __snake_case : Any = image_processing(image_inputs[0] , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __snake_case : Union[str, Any] = image_processing(__a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) @require_torch @require_vision class a_ ( UpperCamelCase_ , unittest.TestCase ): _snake_case = ChineseCLIPImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" __snake_case : Optional[Any] = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=__a) __snake_case : List[Any] = 3 @property def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : Any = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(__a , 'do_resize')) self.assertTrue(hasattr(__a , 'size')) self.assertTrue(hasattr(__a , 'do_center_crop')) self.assertTrue(hasattr(__a , 'center_crop')) self.assertTrue(hasattr(__a , 'do_normalize')) self.assertTrue(hasattr(__a , 'image_mean')) self.assertTrue(hasattr(__a , 'image_std')) self.assertTrue(hasattr(__a , 'do_convert_rgb')) def SCREAMING_SNAKE_CASE__ (self) -> Tuple: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : List[Any] = self.image_processing_class(**self.image_processor_dict) # create random PIL images __snake_case : Union[str, Any] = self.image_processor_tester.prepare_inputs(equal_resolution=__a) for image in image_inputs: self.assertIsInstance(__a , Image.Image) # Test not batched input __snake_case : Optional[int] = image_processing(image_inputs[0] , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __snake_case : Optional[int] = image_processing(__a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , )
61
1
'''simple docstring''' __A = range(2, 2_0 + 1) __A = [1_0**k for k in range(ks[-1] + 1)] __A = {} def _SCREAMING_SNAKE_CASE ( A : Optional[Any] , A : List[str] , A : Union[str, Any] , A : Any ) -> List[Any]: """simple docstring""" __snake_case : Any = sum(a_i[j] for j in range(A , len(A ) ) ) __snake_case : List[str] = sum(a_i[j] * base[j] for j in range(min(len(A ) , A ) ) ) __snake_case ,__snake_case : int = 0, 0 __snake_case : List[Any] = n - i __snake_case : Optional[int] = memo.get(A ) if sub_memo is not None: __snake_case : List[str] = sub_memo.get(A ) if jumps is not None and len(A ) > 0: # find and make the largest jump without going over __snake_case : List[str] = -1 for _k in range(len(A ) - 1 , -1 , -1 ): if jumps[_k][2] <= k and jumps[_k][1] <= max_dn: __snake_case : Union[str, Any] = _k break if max_jump >= 0: __snake_case ,__snake_case ,__snake_case : List[str] = jumps[max_jump] # since the difference between jumps is cached, add c __snake_case : List[Any] = diff + c for j in range(min(A , len(A ) ) ): __snake_case ,__snake_case : Tuple = divmod(A , 10 ) if new_c > 0: add(A , A , A ) else: __snake_case : Optional[int] = [] else: __snake_case : List[Any] = {c: []} __snake_case : Tuple = sub_memo if dn >= max_dn or c + diff >= base[k]: return diff, dn if k > ks[0]: while True: # keep doing smaller jumps __snake_case ,__snake_case : Optional[int] = next_term(A , k - 1 , i + dn , A ) diff += _diff dn += terms_jumped if dn >= max_dn or c + diff >= base[k]: break else: # would be too small a jump, just compute sequential terms instead __snake_case ,__snake_case : Union[str, Any] = compute(A , A , i + dn , A ) diff += _diff dn += terms_jumped __snake_case : int = sub_memo[c] # keep jumps sorted by # of terms skipped __snake_case : Union[str, Any] = 0 while j < len(A ): if jumps[j][1] > dn: break j += 1 # cache the jump for this value digitsum(b) and c sub_memo[c].insert(A , (diff, dn, k) ) return (diff, dn) def _SCREAMING_SNAKE_CASE ( A : List[Any] , A : Dict , A : Tuple , A : int ) -> List[Any]: """simple docstring""" if i >= n: return 0, i if k > len(A ): a_i.extend([0 for _ in range(k - len(A ) )] ) # note: a_i -> b * 10^k + c # ds_b -> digitsum(b) # ds_c -> digitsum(c) __snake_case : Tuple = i __snake_case ,__snake_case ,__snake_case : Optional[int] = 0, 0, 0 for j in range(len(A ) ): if j >= k: ds_b += a_i[j] else: ds_c += a_i[j] while i < n: i += 1 __snake_case : Tuple = ds_c + ds_b diff += addend __snake_case : int = 0 for j in range(A ): __snake_case : Tuple = a_i[j] + addend __snake_case ,__snake_case : Union[str, Any] = divmod(A , 10 ) ds_c += a_i[j] if addend > 0: break if addend > 0: add(A , A , A ) return diff, i - start_i def _SCREAMING_SNAKE_CASE ( A : Tuple , A : Union[str, Any] , A : Dict ) -> Tuple: """simple docstring""" for j in range(A , len(A ) ): __snake_case : Any = digits[j] + addend if s >= 10: __snake_case ,__snake_case : Tuple = divmod(A , 10 ) __snake_case : Tuple = addend // 10 + quotient else: __snake_case : Dict = s __snake_case : List[str] = addend // 10 if addend == 0: break while addend > 0: __snake_case ,__snake_case : Optional[int] = divmod(A , 10 ) digits.append(A ) def _SCREAMING_SNAKE_CASE ( A : int = 10**15 ) -> int: """simple docstring""" __snake_case : Optional[int] = [1] __snake_case : List[str] = 1 __snake_case : Tuple = 0 while True: __snake_case ,__snake_case : Tuple = next_term(A , 20 , i + dn , A ) dn += terms_jumped if dn == n - i: break __snake_case : Union[str, Any] = 0 for j in range(len(A ) ): a_n += digits[j] * 10**j return a_n if __name__ == "__main__": print(f'''{solution() = }''')
61
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { '''sayakpaul/vit-msn-base''': '''https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json''', # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class a_ ( UpperCamelCase_ ): _snake_case = """vit_msn""" def __init__(self , __a=7_6_8 , __a=1_2 , __a=1_2 , __a=3_0_7_2 , __a="gelu" , __a=0.0 , __a=0.0 , __a=0.02 , __a=1E-06 , __a=2_2_4 , __a=1_6 , __a=3 , __a=True , **__a , ) -> Any: """simple docstring""" super().__init__(**__a) __snake_case : List[str] = hidden_size __snake_case : Optional[int] = num_hidden_layers __snake_case : Optional[Any] = num_attention_heads __snake_case : str = intermediate_size __snake_case : List[str] = hidden_act __snake_case : List[Any] = hidden_dropout_prob __snake_case : Tuple = attention_probs_dropout_prob __snake_case : List[str] = initializer_range __snake_case : Optional[int] = layer_norm_eps __snake_case : Dict = image_size __snake_case : int = patch_size __snake_case : Dict = num_channels __snake_case : Tuple = qkv_bias
61
1
'''simple docstring''' from __future__ import annotations from math import pi # Define the Reduced Planck Constant ℏ (H bar), speed of light C, value of # Pi and the function __A = 1.054_571_817E-34 # unit of ℏ : J * s __A = 3E8 # unit of c : m * s^-1 def _SCREAMING_SNAKE_CASE ( A : float , A : float , A : float ) -> dict[str, float]: """simple docstring""" if (force, area, distance).count(0 ) != 1: raise ValueError('One and only one argument must be 0' ) if force < 0: raise ValueError('Magnitude of force can not be negative' ) if distance < 0: raise ValueError('Distance can not be negative' ) if area < 0: raise ValueError('Area can not be negative' ) if force == 0: __snake_case : int = (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / ( 2_40 * (distance) ** 4 ) return {"force": force} elif area == 0: __snake_case : Tuple = (2_40 * force * (distance) ** 4) / ( REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 ) return {"area": area} elif distance == 0: __snake_case : List[str] = ( (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / (2_40 * force) ) ** (1 / 4) return {"distance": distance} raise ValueError('One and only one argument must be 0' ) # Run doctest if __name__ == "__main__": import doctest doctest.testmod()
61
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( A : float , A : list[float] ) -> float: """simple docstring""" if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) __snake_case : List[str] = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(A ) ) return round(A , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
61
1
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( A : Any ) -> int: """simple docstring""" __snake_case : Any = [0] * len(A ) __snake_case : List[str] = [] __snake_case : List[str] = [1] * len(A ) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(A ) ): if indegree[i] == 0: queue.append(A ) while queue: __snake_case : Optional[Any] = queue.pop(0 ) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: __snake_case : int = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(A ) print(max(A ) ) # Adjacency list of Graph __A = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
61
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __A = { '''configuration_distilbert''': [ '''DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DistilBertConfig''', '''DistilBertOnnxConfig''', ], '''tokenization_distilbert''': ['''DistilBertTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ['''DistilBertTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ '''DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''DistilBertForMaskedLM''', '''DistilBertForMultipleChoice''', '''DistilBertForQuestionAnswering''', '''DistilBertForSequenceClassification''', '''DistilBertForTokenClassification''', '''DistilBertModel''', '''DistilBertPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ '''TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFDistilBertForMaskedLM''', '''TFDistilBertForMultipleChoice''', '''TFDistilBertForQuestionAnswering''', '''TFDistilBertForSequenceClassification''', '''TFDistilBertForTokenClassification''', '''TFDistilBertMainLayer''', '''TFDistilBertModel''', '''TFDistilBertPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ '''FlaxDistilBertForMaskedLM''', '''FlaxDistilBertForMultipleChoice''', '''FlaxDistilBertForQuestionAnswering''', '''FlaxDistilBertForSequenceClassification''', '''FlaxDistilBertForTokenClassification''', '''FlaxDistilBertModel''', '''FlaxDistilBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_distilbert import ( DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DistilBertConfig, DistilBertOnnxConfig, ) from .tokenization_distilbert import DistilBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_distilbert_fast import DistilBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_distilbert import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, DistilBertPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertMainLayer, TFDistilBertModel, TFDistilBertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, FlaxDistilBertPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
61
1
'''simple docstring''' from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class a_ : def __init__(self , __a = None) -> None: """simple docstring""" if components is None: __snake_case : List[str] = [] __snake_case : Optional[int] = list(__a) def __len__(self) -> int: """simple docstring""" return len(self.__components) def __str__(self) -> str: """simple docstring""" return "(" + ",".join(map(__a , self.__components)) + ")" def __add__(self , __a) -> Vector: """simple docstring""" __snake_case : Optional[Any] = len(self) if size == len(__a): __snake_case : Optional[int] = [self.__components[i] + other.component(__a) for i in range(__a)] return Vector(__a) else: raise Exception('must have the same size') def __sub__(self , __a) -> Vector: """simple docstring""" __snake_case : Optional[Any] = len(self) if size == len(__a): __snake_case : Optional[int] = [self.__components[i] - other.component(__a) for i in range(__a)] return Vector(__a) else: # error case raise Exception('must have the same size') @overload def __mul__(self , __a) -> Vector: """simple docstring""" ... @overload def __mul__(self , __a) -> float: """simple docstring""" ... def __mul__(self , __a) -> float | Vector: """simple docstring""" if isinstance(__a , (float, int)): __snake_case : str = [c * other for c in self.__components] return Vector(__a) elif isinstance(__a , __a) and len(self) == len(__a): __snake_case : List[Any] = len(self) __snake_case : Dict = [self.__components[i] * other.component(__a) for i in range(__a)] return sum(__a) else: # error case raise Exception('invalid operand!') def SCREAMING_SNAKE_CASE__ (self) -> Vector: """simple docstring""" return Vector(self.__components) def SCREAMING_SNAKE_CASE__ (self , __a) -> float: """simple docstring""" if isinstance(__a , __a) and -len(self.__components) <= i < len(self.__components): return self.__components[i] else: raise Exception('index out of range') def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> None: """simple docstring""" assert -len(self.__components) <= pos < len(self.__components) __snake_case : int = value def SCREAMING_SNAKE_CASE__ (self) -> float: """simple docstring""" if len(self.__components) == 0: raise Exception('Vector is empty') __snake_case : Tuple = [c**2 for c in self.__components] return math.sqrt(sum(__a)) def SCREAMING_SNAKE_CASE__ (self , __a , __a = False) -> float: """simple docstring""" __snake_case : Tuple = self * other __snake_case : Optional[int] = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den)) else: return math.acos(num / den) def _SCREAMING_SNAKE_CASE ( A : int ) -> Vector: """simple docstring""" assert isinstance(A , A ) return Vector([0] * dimension ) def _SCREAMING_SNAKE_CASE ( A : int , A : int ) -> Vector: """simple docstring""" assert isinstance(A , A ) and (isinstance(A , A )) __snake_case : Any = [0] * dimension __snake_case : int = 1 return Vector(A ) def _SCREAMING_SNAKE_CASE ( A : float , A : Vector , A : Vector ) -> Vector: """simple docstring""" assert ( isinstance(A , A ) and isinstance(A , A ) and (isinstance(A , (int, float) )) ) return x * scalar + y def _SCREAMING_SNAKE_CASE ( A : int , A : int , A : int ) -> Vector: """simple docstring""" random.seed(A ) __snake_case : List[Any] = [random.randint(A , A ) for _ in range(A )] return Vector(A ) class a_ : def __init__(self , __a , __a , __a) -> None: """simple docstring""" __snake_case : Union[str, Any] = matrix __snake_case : int = w __snake_case : str = h def __str__(self) -> str: """simple docstring""" __snake_case : Dict = '' for i in range(self.__height): ans += "|" for j in range(self.__width): if j < self.__width - 1: ans += str(self.__matrix[i][j]) + "," else: ans += str(self.__matrix[i][j]) + "|\n" return ans def __add__(self , __a) -> Matrix: """simple docstring""" if self.__width == other.width() and self.__height == other.height(): __snake_case : Tuple = [] for i in range(self.__height): __snake_case : List[Any] = [ self.__matrix[i][j] + other.component(__a , __a) for j in range(self.__width) ] matrix.append(__a) return Matrix(__a , self.__width , self.__height) else: raise Exception('matrix must have the same dimension!') def __sub__(self , __a) -> Matrix: """simple docstring""" if self.__width == other.width() and self.__height == other.height(): __snake_case : str = [] for i in range(self.__height): __snake_case : List[str] = [ self.__matrix[i][j] - other.component(__a , __a) for j in range(self.__width) ] matrix.append(__a) return Matrix(__a , self.__width , self.__height) else: raise Exception('matrices must have the same dimension!') @overload def __mul__(self , __a) -> Matrix: """simple docstring""" ... @overload def __mul__(self , __a) -> Vector: """simple docstring""" ... def __mul__(self , __a) -> Vector | Matrix: """simple docstring""" if isinstance(__a , __a): # matrix-vector if len(__a) == self.__width: __snake_case : Tuple = zero_vector(self.__height) for i in range(self.__height): __snake_case : Union[str, Any] = [ self.__matrix[i][j] * other.component(__a) for j in range(self.__width) ] ans.change_component(__a , sum(__a)) return ans else: raise Exception( 'vector must have the same size as the ' 'number of columns of the matrix!') elif isinstance(__a , (int, float)): # matrix-scalar __snake_case : str = [ [self.__matrix[i][j] * other for j in range(self.__width)] for i in range(self.__height) ] return Matrix(__a , self.__width , self.__height) return None def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" return self.__height def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" return self.__width def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> float: """simple docstring""" if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception('change_component: indices out of bounds') def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> None: """simple docstring""" if 0 <= x < self.__height and 0 <= y < self.__width: __snake_case : List[Any] = value else: raise Exception('change_component: indices out of bounds') def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> float: """simple docstring""" if self.__height != self.__width: raise Exception('Matrix is not square') __snake_case : List[Any] = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(__a)): __snake_case : Tuple = minor[i][:y] + minor[i][y + 1 :] return Matrix(__a , self.__width - 1 , self.__height - 1).determinant() def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> float: """simple docstring""" if self.__height != self.__width: raise Exception('Matrix is not square') if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(__a , __a) else: raise Exception('Indices out of bounds') def SCREAMING_SNAKE_CASE__ (self) -> float: """simple docstring""" if self.__height != self.__width: raise Exception('Matrix is not square') if self.__height < 1: raise Exception('Matrix has no element') elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: __snake_case : Any = [ self.__matrix[0][y] * self.cofactor(0 , __a) for y in range(self.__width) ] return sum(__a) def _SCREAMING_SNAKE_CASE ( A : int ) -> Matrix: """simple docstring""" __snake_case : list[list[float]] = [[0] * n for _ in range(A )] return Matrix(A , A , A ) def _SCREAMING_SNAKE_CASE ( A : int , A : int , A : int , A : int ) -> Matrix: """simple docstring""" random.seed(A ) __snake_case : list[list[float]] = [ [random.randint(A , A ) for _ in range(A )] for _ in range(A ) ] return Matrix(A , A , A )
61
'''simple docstring''' # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. __A = abspath(join(dirname(dirname(__file__)), '''src''')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='''ignore''', category=FutureWarning) def _SCREAMING_SNAKE_CASE ( A : Tuple ) -> str: """simple docstring""" from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(A ) def _SCREAMING_SNAKE_CASE ( A : int ) -> Optional[int]: """simple docstring""" from diffusers.utils.testing_utils import pytest_terminal_summary_main __snake_case : Any = terminalreporter.config.getoption('--make-reports' ) if make_reports: pytest_terminal_summary_main(A , id=A )
61
1
'''simple docstring''' import os import re from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __A = logging.get_logger(__name__) __A = {'''vocab_file''': '''spiece.model'''} __A = { '''vocab_file''': { '''google/bigbird-roberta-base''': '''https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model''', '''google/bigbird-roberta-large''': ( '''https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model''' ), '''google/bigbird-base-trivia-itc''': ( '''https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model''' ), } } __A = { '''google/bigbird-roberta-base''': 4_0_9_6, '''google/bigbird-roberta-large''': 4_0_9_6, '''google/bigbird-base-trivia-itc''': 4_0_9_6, } class a_ ( UpperCamelCase_ ): _snake_case = VOCAB_FILES_NAMES _snake_case = PRETRAINED_VOCAB_FILES_MAP _snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _snake_case = ["""input_ids""", """attention_mask"""] _snake_case = [] def __init__(self , __a , __a="<unk>" , __a="<s>" , __a="</s>" , __a="<pad>" , __a="[SEP]" , __a="[MASK]" , __a="[CLS]" , __a = None , **__a , ) -> None: """simple docstring""" __snake_case : Tuple = AddedToken(__a , lstrip=__a , rstrip=__a) if isinstance(__a , __a) else bos_token __snake_case : List[str] = AddedToken(__a , lstrip=__a , rstrip=__a) if isinstance(__a , __a) else eos_token __snake_case : Optional[int] = AddedToken(__a , lstrip=__a , rstrip=__a) if isinstance(__a , __a) else unk_token __snake_case : List[str] = AddedToken(__a , lstrip=__a , rstrip=__a) if isinstance(__a , __a) else pad_token __snake_case : Tuple = AddedToken(__a , lstrip=__a , rstrip=__a) if isinstance(__a , __a) else cls_token __snake_case : Tuple = AddedToken(__a , lstrip=__a , rstrip=__a) if isinstance(__a , __a) else sep_token # Mask token behave like a normal word, i.e. include the space before it __snake_case : Tuple = AddedToken(__a , lstrip=__a , rstrip=__a) if isinstance(__a , __a) else mask_token __snake_case : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__a , eos_token=__a , unk_token=__a , pad_token=__a , sep_token=__a , mask_token=__a , cls_token=__a , sp_model_kwargs=self.sp_model_kwargs , **__a , ) __snake_case : Optional[int] = vocab_file __snake_case : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(__a) @property def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" return self.sp_model.get_piece_size() def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : Union[str, Any] = {self.convert_ids_to_tokens(__a): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__(self) -> Tuple: """simple docstring""" __snake_case : str = self.__dict__.copy() __snake_case : Optional[Any] = None return state def __setstate__(self , __a) -> Tuple: """simple docstring""" __snake_case : int = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs'): __snake_case : int = {} __snake_case : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def SCREAMING_SNAKE_CASE__ (self , __a) -> List[str]: """simple docstring""" return self.sp_model.encode(__a , out_type=__a) def SCREAMING_SNAKE_CASE__ (self , __a) -> List[str]: """simple docstring""" return self.sp_model.piece_to_id(__a) def SCREAMING_SNAKE_CASE__ (self , __a) -> List[Any]: """simple docstring""" __snake_case : Optional[int] = self.sp_model.IdToPiece(__a) return token def SCREAMING_SNAKE_CASE__ (self , __a) -> Optional[int]: """simple docstring""" __snake_case : str = [] __snake_case : Dict = '' __snake_case : Union[str, Any] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__a) + token __snake_case : int = True __snake_case : str = [] else: current_sub_tokens.append(__a) __snake_case : Any = False out_string += self.sp_model.decode(__a) return out_string.strip() def SCREAMING_SNAKE_CASE__ (self , __a , __a = False , __a = None , __a = True , **__a , ) -> str: """simple docstring""" __snake_case : Optional[Any] = kwargs.pop('use_source_tokenizer' , __a) __snake_case : List[Any] = self.convert_ids_to_tokens(__a , skip_special_tokens=__a) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 __snake_case : Tuple = [] __snake_case : str = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(__a)) __snake_case : Optional[int] = [] sub_texts.append(__a) else: current_sub_text.append(__a) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(__a)) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: __snake_case : List[str] = re.sub(R' (\[(MASK|SEP)\])' , R'\1' , ' '.join(__a)) else: __snake_case : Optional[Any] = ''.join(__a) __snake_case : Optional[int] = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: __snake_case : Union[str, Any] = self.clean_up_tokenization(__a) return clean_text else: return text def SCREAMING_SNAKE_CASE__ (self , __a , __a = None) -> Tuple[str]: """simple docstring""" if not os.path.isdir(__a): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""") return __snake_case : Any = os.path.join( __a , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(__a) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file , __a) elif not os.path.isfile(self.vocab_file): with open(__a , 'wb') as fi: __snake_case : int = self.sp_model.serialized_model_proto() fi.write(__a) return (out_vocab_file,) def SCREAMING_SNAKE_CASE__ (self , __a , __a = None) -> List[int]: """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __snake_case : Any = [self.cls_token_id] __snake_case : int = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE__ (self , __a , __a = None , __a = False) -> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__a , token_ids_a=__a , already_has_special_tokens=__a) if token_ids_a is None: return [1] + ([0] * len(__a)) + [1] return [1] + ([0] * len(__a)) + [1] + ([0] * len(__a)) + [1] def SCREAMING_SNAKE_CASE__ (self , __a , __a = None) -> List[int]: """simple docstring""" __snake_case : Dict = [self.sep_token_id] __snake_case : Union[str, 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]
61
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __A = { '''configuration_biogpt''': ['''BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BioGptConfig'''], '''tokenization_biogpt''': ['''BioGptTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ '''BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BioGptForCausalLM''', '''BioGptForTokenClassification''', '''BioGptForSequenceClassification''', '''BioGptModel''', '''BioGptPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
61
1
'''simple docstring''' import argparse import re import torch from CLAP import create_model from transformers import AutoFeatureExtractor, ClapConfig, ClapModel __A = { '''text_branch''': '''text_model''', '''audio_branch''': '''audio_model.audio_encoder''', '''attn''': '''attention.self''', '''self.proj''': '''output.dense''', '''attention.self_mask''': '''attn_mask''', '''mlp.fc1''': '''intermediate.dense''', '''mlp.fc2''': '''output.dense''', '''norm1''': '''layernorm_before''', '''norm2''': '''layernorm_after''', '''bn0''': '''batch_norm''', } __A = AutoFeatureExtractor.from_pretrained('''laion/clap-htsat-unfused''', truncation='''rand_trunc''') def _SCREAMING_SNAKE_CASE ( A : int , A : Optional[int]=False ) -> List[Any]: """simple docstring""" __snake_case ,__snake_case : Union[str, Any] = create_model( 'HTSAT-tiny' , 'roberta' , A , precision='fp32' , device='cuda:0' if torch.cuda.is_available() else 'cpu' , enable_fusion=A , fusion_type='aff_2d' if enable_fusion else None , ) return model, model_cfg def _SCREAMING_SNAKE_CASE ( A : str ) -> Optional[int]: """simple docstring""" __snake_case : int = {} __snake_case : str = R'.*sequential.(\d+).*' __snake_case : Dict = R'.*_projection.(\d+).*' for key, value in state_dict.items(): # check if any key needs to be modified for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items(): if key_to_modify in key: __snake_case : List[Any] = key.replace(A , A ) if re.match(A , A ): # replace sequential layers with list __snake_case : Dict = re.match(A , A ).group(1 ) __snake_case : str = key.replace(F"""sequential.{sequential_layer}.""" , F"""layers.{int(A )//3}.linear.""" ) elif re.match(A , A ): __snake_case : str = int(re.match(A , A ).group(1 ) ) # Because in CLAP they use `nn.Sequential`... __snake_case : Any = 1 if projecton_layer == 0 else 2 __snake_case : Optional[Any] = key.replace(F"""_projection.{projecton_layer}.""" , F"""_projection.linear{transformers_projection_layer}.""" ) if "audio" and "qkv" in key: # split qkv into query key and value __snake_case : str = value __snake_case : int = mixed_qkv.size(0 ) // 3 __snake_case : Union[str, Any] = mixed_qkv[:qkv_dim] __snake_case : Dict = mixed_qkv[qkv_dim : qkv_dim * 2] __snake_case : str = mixed_qkv[qkv_dim * 2 :] __snake_case : Optional[int] = query_layer __snake_case : List[str] = key_layer __snake_case : Dict = value_layer else: __snake_case : Union[str, Any] = value return model_state_dict def _SCREAMING_SNAKE_CASE ( A : Union[str, Any] , A : Union[str, Any] , A : Tuple , A : Tuple=False ) -> str: """simple docstring""" __snake_case ,__snake_case : Any = init_clap(A , enable_fusion=A ) clap_model.eval() __snake_case : List[str] = clap_model.state_dict() __snake_case : Tuple = rename_state_dict(A ) __snake_case : int = ClapConfig() __snake_case : Tuple = enable_fusion __snake_case : List[str] = ClapModel(A ) # ignore the spectrogram embedding layer model.load_state_dict(A , strict=A ) model.save_pretrained(A ) transformers_config.save_pretrained(A ) if __name__ == "__main__": __A = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument('''--enable_fusion''', action='''store_true''', help='''Whether to enable fusion or not''') __A = parser.parse_args() convert_clap_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.enable_fusion)
61
'''simple docstring''' from packaging import version from .import_utils import is_accelerate_available if is_accelerate_available(): import accelerate def _SCREAMING_SNAKE_CASE ( A : Optional[Any] ) -> int: """simple docstring""" if not is_accelerate_available(): return method __snake_case : Optional[Any] = version.parse(accelerate.__version__ ).base_version if version.parse(A ) < version.parse('0.17.0' ): return method def wrapper(self : Optional[Any] , *A : Optional[Any] , **A : Optional[int] ): if hasattr(self , '_hf_hook' ) and hasattr(self._hf_hook , 'pre_forward' ): self._hf_hook.pre_forward(self ) return method(self , *A , **A ) return wrapper
61
1
'''simple docstring''' import argparse import json import os import torch from torch import nn from transformers import NllbMoeConfig, NllbMoeModel from transformers.modeling_utils import dtype_byte_size from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME def _SCREAMING_SNAKE_CASE ( A : str ) -> Tuple: """simple docstring""" __snake_case : Dict = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', 'decoder.output_projection.weight', '_float_tensor', 'encoder.embed_positions._float_tensor', 'decoder.embed_positions._float_tensor', ] for k in ignore_keys: state_dict.pop(A , A ) def _SCREAMING_SNAKE_CASE ( A : int ) -> int: """simple docstring""" __snake_case ,__snake_case : Optional[int] = emb.weight.shape __snake_case : str = nn.Linear(A , A , bias=A ) __snake_case : int = emb.weight.data return lin_layer def _SCREAMING_SNAKE_CASE ( A : int , A : Dict=None ) -> List[str]: """simple docstring""" __snake_case : Optional[Any] = {} for old_key in state_dict.keys(): __snake_case : Optional[int] = old_key if "moe_layer.experts." in key: if expert_idx is not None: __snake_case : Any = key.replace('moe_layer.experts.0' , F"""ffn.experts.expert_{expert_idx}""" ) else: __snake_case : Union[str, Any] = key.replace('moe_layer.experts.' , 'ffn.experts.expert_' ) if "gate" in key: __snake_case : List[Any] = key.replace('.moe_layer.gate.wg' , '.ffn.router.classifier' ) if "fc2" and "experts" not in key: __snake_case : List[Any] = key.replace('.fc2.' , '.ffn.fc2.' ) if "fc1" and "experts" not in key: __snake_case : Dict = key.replace('.fc1.' , '.ffn.fc1.' ) if ".encoder_attn." in key: __snake_case : Union[str, Any] = key.replace('.encoder_attn.' , '.cross_attention.' ) if "encoder_attn_layer_norm" in key: __snake_case : Tuple = key.replace('encoder_attn_layer_norm' , 'cross_attention_layer_norm' ) if "final_layer_norm" in key: __snake_case : Tuple = key.replace('final_layer_norm' , 'ff_layer_norm' ) __snake_case : Tuple = state_dict[old_key] return new_dict def _SCREAMING_SNAKE_CASE ( A : Optional[Any] , A : Any , A : List[str] , A : str , A : str = WEIGHTS_NAME ) -> Dict: """simple docstring""" __snake_case : Any = [] __snake_case : Optional[int] = 0 os.makedirs(A , exist_ok=A ) for expert in range(A ): __snake_case : int = switch_checkpoint_path + F"""-rank-{expert}.pt""" if os.path.isfile(A ): __snake_case : List[str] = torch.load(A )['model'] remove_ignore_keys_(A ) __snake_case : Optional[Any] = rename_fairseq_keys(A , A ) __snake_case : Union[str, Any] = os.path.join( A , weights_name.replace('.bin' , F"""-{len(A )+1:05d}-of-???.bin""" ) ) torch.save(A , A ) sharded_state_dicts.append(expert_state.keys() ) total_size += sum([value.numel() for key, value in expert_state.items()] ) * dtype_byte_size( expert_state[list(A )[0]].dtype ) # Add the last block __snake_case : Dict = os.path.join(A , weights_name.replace('.bin' , F"""-{len(A )+1:05d}-of-???.bin""" ) ) __snake_case : List[str] = torch.load(switch_checkpoint_path + '-shared.pt' )['model'] remove_ignore_keys_(A ) __snake_case : Optional[int] = rename_fairseq_keys(A , A ) __snake_case : Optional[int] = shared_weights['decoder.embed_tokens.weight'] sharded_state_dicts.append(shared_weights.keys() ) # If we only have the shared weights (dummy model/experts saved on the same file) if len(A ) == 1: __snake_case : List[str] = os.path.join(A , A ) torch.save(A , A ) return {weights_name: sharded_state_dicts[0]}, None else: torch.save(A , A ) # Otherwise, let's build the index __snake_case : Union[str, Any] = {} for idx, shard in enumerate(A ): __snake_case : Tuple = weights_name.replace('.bin' , F"""-{idx+1:05d}-of-{len(A ):05d}.bin""" ) __snake_case : Dict = os.path.join(A , weights_name.replace('.bin' , F"""-{idx+1:05d}-of-???.bin""" ) ) os.rename(A , os.path.join(A , A ) ) for key in shard: __snake_case : Optional[Any] = shard_file # Add the metadata __snake_case : Tuple = {'total_size': total_size} __snake_case : Dict = {'metadata': metadata, 'weight_map': weight_map} with open(os.path.join(A , A ) , 'w' , encoding='utf-8' ) as f: __snake_case : int = json.dumps(A , indent=2 , sort_keys=A ) + '\n' f.write(A ) return metadata, index if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--nllb_moe_checkpoint_path''', default='''/home/arthur_huggingface_co/fairseq/weights/checkpoints/model_moe_54b/checkpoint_2_300000''', type=str, required=False, help='''Path to a directory containing a folder per layer. Follows the original Google format.''', ) parser.add_argument('''--dtype''', default='''float32''', type=str, required=False, help='''dtype of the saved model''') parser.add_argument( '''--pytorch_dump_folder_path''', default='''/home/arthur_huggingface_co/fairseq/weights/checkpoints/hf-converted-moe-54b''', type=str, required=False, help='''Path to the output pytorch model.''', ) __A = parser.parse_args() __A , __A = shard_on_the_fly( args.nllb_moe_checkpoint_path, args.pytorch_dump_folder_path, 1_2_8, args.dtype, ) __A = NllbMoeConfig.from_pretrained( '''facebook/nllb-200-3.3B''', encoder_sparse_step=4, decoder_sparse_step=4, num_experts=1_2_8 ) config.save_pretrained(args.pytorch_dump_folder_path) __A = NllbMoeModel.from_pretrained(args.pytorch_dump_folder_path) print('''Done''') model.save_pretrained(args.pytorch_dump_folder_path)
61
'''simple docstring''' import unittest from transformers import load_tool from transformers.utils import is_torch_available if is_torch_available(): import torch from transformers.testing_utils import require_torch from .test_tools_common import ToolTesterMixin @require_torch class a_ ( unittest.TestCase , UpperCamelCase_ ): def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" __snake_case : List[str] = load_tool('text-to-speech') self.tool.setup() def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]: """simple docstring""" torch.manual_seed(0) __snake_case : Dict = self.tool('hey') __snake_case : List[Any] = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485]) , )) def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" torch.manual_seed(0) __snake_case : Any = self.tool('hey') __snake_case : Any = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485]) , ))
61
1
'''simple docstring''' import warnings from ...utils import logging from .image_processing_perceiver import PerceiverImageProcessor __A = logging.get_logger(__name__) class a_ ( UpperCamelCase_ ): def __init__(self , *__a , **__a) -> None: """simple docstring""" warnings.warn( 'The class PerceiverFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use PerceiverImageProcessor instead.' , __a , ) super().__init__(*__a , **__a)
61
'''simple docstring''' import math class a_ : def __init__(self , __a=0) -> Any: # a graph with Node 0,1,...,N-1 """simple docstring""" __snake_case : List[str] = n __snake_case : Tuple = [ [math.inf for j in range(0 , __a)] for i in range(0 , __a) ] # adjacency matrix for weight __snake_case : Union[str, Any] = [ [math.inf for j in range(0 , __a)] for i in range(0 , __a) ] # dp[i][j] stores minimum distance from i to j def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Tuple: """simple docstring""" __snake_case : Union[str, Any] = w def SCREAMING_SNAKE_CASE__ (self) -> Tuple: """simple docstring""" for k in range(0 , self.n): for i in range(0 , self.n): for j in range(0 , self.n): __snake_case : List[Any] = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j]) def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> Optional[int]: """simple docstring""" return self.dp[u][v] if __name__ == "__main__": __A = Graph(5) graph.add_edge(0, 2, 9) graph.add_edge(0, 4, 1_0) graph.add_edge(1, 3, 5) graph.add_edge(2, 3, 7) graph.add_edge(3, 0, 1_0) graph.add_edge(3, 1, 2) graph.add_edge(3, 2, 1) graph.add_edge(3, 4, 6) graph.add_edge(4, 1, 3) graph.add_edge(4, 2, 4) graph.add_edge(4, 3, 9) graph.floyd_warshall() graph.show_min(1, 4) graph.show_min(0, 3)
61
1
'''simple docstring''' from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, ) @flax.struct.dataclass class a_ ( UpperCamelCase_ ): _snake_case = 42 _snake_case = 42 class a_ ( nn.Module ): _snake_case = 42 _snake_case = (16, 32, 96, 256) _snake_case = jnp.floataa def SCREAMING_SNAKE_CASE__ (self) -> str: """simple docstring""" __snake_case : List[Any] = nn.Conv( self.block_out_channels[0] , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) __snake_case : Union[str, Any] = [] for i in range(len(self.block_out_channels) - 1): __snake_case : str = self.block_out_channels[i] __snake_case : Optional[Any] = self.block_out_channels[i + 1] __snake_case : Tuple = nn.Conv( __a , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(__a) __snake_case : Tuple = nn.Conv( __a , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(__a) __snake_case : Optional[Any] = blocks __snake_case : Optional[Any] = nn.Conv( self.conditioning_embedding_channels , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__(self , __a) -> Dict: """simple docstring""" __snake_case : Tuple = self.conv_in(__a) __snake_case : Dict = nn.silu(__a) for block in self.blocks: __snake_case : Optional[Any] = block(__a) __snake_case : Any = nn.silu(__a) __snake_case : List[Any] = self.conv_out(__a) return embedding @flax_register_to_config class a_ ( nn.Module , UpperCamelCase_ , UpperCamelCase_ ): _snake_case = 32 _snake_case = 4 _snake_case = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) _snake_case = False _snake_case = (320, 640, 1280, 1280) _snake_case = 2 _snake_case = 8 _snake_case = None _snake_case = 1280 _snake_case = 0.0 _snake_case = False _snake_case = jnp.floataa _snake_case = True _snake_case = 0 _snake_case = "rgb" _snake_case = (16, 32, 96, 256) def SCREAMING_SNAKE_CASE__ (self , __a) -> FrozenDict: """simple docstring""" __snake_case : Dict = (1, self.in_channels, self.sample_size, self.sample_size) __snake_case : str = jnp.zeros(__a , dtype=jnp.floataa) __snake_case : Union[str, Any] = jnp.ones((1,) , dtype=jnp.intaa) __snake_case : Tuple = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa) __snake_case : Dict = (1, 3, self.sample_size * 8, self.sample_size * 8) __snake_case : int = jnp.zeros(__a , dtype=jnp.floataa) __snake_case ,__snake_case : int = jax.random.split(__a) __snake_case : Optional[Any] = {'params': params_rng, 'dropout': dropout_rng} return self.init(__a , __a , __a , __a , __a)["params"] def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" __snake_case : int = self.block_out_channels __snake_case : List[Any] = block_out_channels[0] * 4 # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. __snake_case : Union[str, Any] = self.num_attention_heads or self.attention_head_dim # input __snake_case : List[Any] = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time __snake_case : List[str] = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift) __snake_case : Union[str, Any] = FlaxTimestepEmbedding(__a , dtype=self.dtype) __snake_case : int = FlaxControlNetConditioningEmbedding( conditioning_embedding_channels=block_out_channels[0] , block_out_channels=self.conditioning_embedding_out_channels , ) __snake_case : Any = self.only_cross_attention if isinstance(__a , __a): __snake_case : List[str] = (only_cross_attention,) * len(self.down_block_types) if isinstance(__a , __a): __snake_case : Any = (num_attention_heads,) * len(self.down_block_types) # down __snake_case : List[Any] = [] __snake_case : List[Any] = [] __snake_case : Optional[Any] = block_out_channels[0] __snake_case : Optional[int] = nn.Conv( __a , kernel_size=(1, 1) , padding='VALID' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(__a) for i, down_block_type in enumerate(self.down_block_types): __snake_case : Optional[int] = output_channel __snake_case : Dict = block_out_channels[i] __snake_case : Optional[Any] = i == len(__a) - 1 if down_block_type == "CrossAttnDownBlock2D": __snake_case : List[str] = FlaxCrossAttnDownBlockaD( in_channels=__a , out_channels=__a , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , dtype=self.dtype , ) else: __snake_case : Tuple = FlaxDownBlockaD( in_channels=__a , out_channels=__a , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(__a) for _ in range(self.layers_per_block): __snake_case : Tuple = nn.Conv( __a , kernel_size=(1, 1) , padding='VALID' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(__a) if not is_final_block: __snake_case : int = nn.Conv( __a , kernel_size=(1, 1) , padding='VALID' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(__a) __snake_case : Optional[int] = down_blocks __snake_case : str = controlnet_down_blocks # mid __snake_case : Union[str, Any] = block_out_channels[-1] __snake_case : Union[str, Any] = FlaxUNetMidBlockaDCrossAttn( in_channels=__a , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , dtype=self.dtype , ) __snake_case : Tuple = nn.Conv( __a , kernel_size=(1, 1) , padding='VALID' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__(self , __a , __a , __a , __a , __a = 1.0 , __a = True , __a = False , ) -> Union[FlaxControlNetOutput, Tuple]: """simple docstring""" __snake_case : str = self.controlnet_conditioning_channel_order if channel_order == "bgr": __snake_case : Tuple = jnp.flip(__a , axis=1) # 1. time if not isinstance(__a , jnp.ndarray): __snake_case : Optional[Any] = jnp.array([timesteps] , dtype=jnp.intaa) elif isinstance(__a , jnp.ndarray) and len(timesteps.shape) == 0: __snake_case : Optional[int] = timesteps.astype(dtype=jnp.floataa) __snake_case : Optional[Any] = jnp.expand_dims(__a , 0) __snake_case : int = self.time_proj(__a) __snake_case : List[Any] = self.time_embedding(__a) # 2. pre-process __snake_case : Any = jnp.transpose(__a , (0, 2, 3, 1)) __snake_case : int = self.conv_in(__a) __snake_case : Union[str, Any] = jnp.transpose(__a , (0, 2, 3, 1)) __snake_case : Any = self.controlnet_cond_embedding(__a) sample += controlnet_cond # 3. down __snake_case : str = (sample,) for down_block in self.down_blocks: if isinstance(__a , __a): __snake_case ,__snake_case : str = down_block(__a , __a , __a , deterministic=not train) else: __snake_case ,__snake_case : int = down_block(__a , __a , deterministic=not train) down_block_res_samples += res_samples # 4. mid __snake_case : str = self.mid_block(__a , __a , __a , deterministic=not train) # 5. contronet blocks __snake_case : Optional[int] = () for down_block_res_sample, controlnet_block in zip(__a , self.controlnet_down_blocks): __snake_case : int = controlnet_block(__a) controlnet_down_block_res_samples += (down_block_res_sample,) __snake_case : Union[str, Any] = controlnet_down_block_res_samples __snake_case : Dict = self.controlnet_mid_block(__a) # 6. scaling __snake_case : Union[str, Any] = [sample * conditioning_scale for sample in down_block_res_samples] mid_block_res_sample *= conditioning_scale if not return_dict: return (down_block_res_samples, mid_block_res_sample) return FlaxControlNetOutput( down_block_res_samples=__a , mid_block_res_sample=__a)
61
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL __A = logging.get_logger(__name__) class a_ ( UpperCamelCase_ ): _snake_case = ["""pixel_values"""] def __init__(self , __a = True , __a = None , __a = None , __a = PILImageResampling.BILINEAR , __a = True , __a = 1 / 2_5_5 , __a = True , __a = None , __a = None , **__a , ) -> None: """simple docstring""" super().__init__(**__a) __snake_case : Tuple = size if size is not None else {'shortest_edge': 3_8_4} __snake_case : List[Any] = get_size_dict(__a , default_to_square=__a) __snake_case : int = do_resize __snake_case : List[str] = size # Default value set here for backwards compatibility where the value in config is None __snake_case : Any = crop_pct if crop_pct is not None else 2_2_4 / 2_5_6 __snake_case : Tuple = resample __snake_case : Dict = do_rescale __snake_case : Any = rescale_factor __snake_case : str = do_normalize __snake_case : Union[str, Any] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __snake_case : Dict = image_std if image_std is not None else IMAGENET_STANDARD_STD def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a , __a = PILImageResampling.BICUBIC , __a = None , **__a , ) -> np.ndarray: """simple docstring""" __snake_case : Dict = get_size_dict(__a , default_to_square=__a) if "shortest_edge" not in size: raise ValueError(F"""Size dictionary must contain 'shortest_edge' key. Got {size.keys()}""") __snake_case : List[str] = size['shortest_edge'] if shortest_edge < 3_8_4: # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct __snake_case : Any = int(shortest_edge / crop_pct) __snake_case : Any = get_resize_output_image_size(__a , size=__a , default_to_square=__a) __snake_case : int = resize(image=__a , size=__a , resample=__a , data_format=__a , **__a) # then crop to (shortest_edge, shortest_edge) return center_crop(image=__a , size=(shortest_edge, shortest_edge) , data_format=__a , **__a) else: # warping (no cropping) when evaluated at 384 or larger return resize( __a , size=(shortest_edge, shortest_edge) , resample=__a , data_format=__a , **__a) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a = None , **__a , ) -> Any: """simple docstring""" return rescale(__a , scale=__a , data_format=__a , **__a) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a , __a = None , **__a , ) -> np.ndarray: """simple docstring""" return normalize(__a , mean=__a , std=__a , data_format=__a , **__a) def SCREAMING_SNAKE_CASE__ (self , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = ChannelDimension.FIRST , **__a , ) -> PIL.Image.Image: """simple docstring""" __snake_case : Optional[int] = do_resize if do_resize is not None else self.do_resize __snake_case : Dict = crop_pct if crop_pct is not None else self.crop_pct __snake_case : Tuple = resample if resample is not None else self.resample __snake_case : Any = do_rescale if do_rescale is not None else self.do_rescale __snake_case : Any = rescale_factor if rescale_factor is not None else self.rescale_factor __snake_case : Union[str, Any] = do_normalize if do_normalize is not None else self.do_normalize __snake_case : Optional[int] = image_mean if image_mean is not None else self.image_mean __snake_case : Optional[Any] = image_std if image_std is not None else self.image_std __snake_case : List[str] = size if size is not None else self.size __snake_case : Any = get_size_dict(__a , default_to_square=__a) __snake_case : Dict = make_list_of_images(__a) if not valid_images(__a): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.') if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.') if do_resize and size["shortest_edge"] < 3_8_4 and crop_pct is None: raise ValueError('crop_pct must be specified if size < 384.') if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.') if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.') # All transformations expect numpy arrays. __snake_case : Tuple = [to_numpy_array(__a) for image in images] if do_resize: __snake_case : Optional[int] = [self.resize(image=__a , size=__a , crop_pct=__a , resample=__a) for image in images] if do_rescale: __snake_case : Optional[int] = [self.rescale(image=__a , scale=__a) for image in images] if do_normalize: __snake_case : Any = [self.normalize(image=__a , mean=__a , std=__a) for image in images] __snake_case : Dict = [to_channel_dimension_format(__a , __a) for image in images] __snake_case : Union[str, Any] = {'pixel_values': images} return BatchFeature(data=__a , tensor_type=__a)
61
1
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( A : int ) -> str: """simple docstring""" if isinstance(A , A ): raise TypeError('\'float\' object cannot be interpreted as an integer' ) if isinstance(A , A ): raise TypeError('\'str\' object cannot be interpreted as an integer' ) if num == 0: return "0b0" __snake_case : Optional[int] = False if num < 0: __snake_case : Optional[Any] = True __snake_case : List[Any] = -num __snake_case : list[int] = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(A ) for e in binary ) return "0b" + "".join(str(A ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
61
'''simple docstring''' from functools import lru_cache @lru_cache def _SCREAMING_SNAKE_CASE ( A : int ) -> int: """simple docstring""" if num < 0: raise ValueError('Number should not be negative.' ) return 1 if num in (0, 1) else num * factorial(num - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
61
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, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging __A = logging.get_logger(__name__) if is_vision_available(): import PIL class a_ ( UpperCamelCase_ ): _snake_case = ["""pixel_values"""] def __init__(self , __a = True , __a = None , __a = PILImageResampling.BICUBIC , __a = True , __a = None , __a = True , __a = 1 / 2_5_5 , __a = True , __a = None , __a = None , __a = True , **__a , ) -> None: """simple docstring""" super().__init__(**__a) __snake_case : Dict = size if size is not None else {'shortest_edge': 2_2_4} __snake_case : Dict = get_size_dict(__a , default_to_square=__a) __snake_case : Optional[Any] = crop_size if crop_size is not None else {'height': 2_2_4, 'width': 2_2_4} __snake_case : Union[str, Any] = get_size_dict(__a , default_to_square=__a , param_name='crop_size') __snake_case : List[str] = do_resize __snake_case : Dict = size __snake_case : int = resample __snake_case : List[Any] = do_center_crop __snake_case : Optional[int] = crop_size __snake_case : Any = do_rescale __snake_case : List[Any] = rescale_factor __snake_case : Optional[Any] = do_normalize __snake_case : Optional[Any] = image_mean if image_mean is not None else OPENAI_CLIP_MEAN __snake_case : Tuple = image_std if image_std is not None else OPENAI_CLIP_STD __snake_case : Optional[int] = do_convert_rgb def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a = PILImageResampling.BICUBIC , __a = None , **__a , ) -> np.ndarray: """simple docstring""" __snake_case : Tuple = get_size_dict(__a , default_to_square=__a) if "shortest_edge" not in size: raise ValueError(F"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}""") __snake_case : int = get_resize_output_image_size(__a , size=size['shortest_edge'] , default_to_square=__a) return resize(__a , size=__a , resample=__a , data_format=__a , **__a) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a = None , **__a , ) -> np.ndarray: """simple docstring""" __snake_case : int = get_size_dict(__a) if "height" not in size or "width" not in size: raise ValueError(F"""The `size` parameter must contain the keys (height, width). Got {size.keys()}""") return center_crop(__a , size=(size['height'], size['width']) , data_format=__a , **__a) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a = None , **__a , ) -> Union[str, Any]: """simple docstring""" return rescale(__a , scale=__a , data_format=__a , **__a) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a , __a = None , **__a , ) -> np.ndarray: """simple docstring""" return normalize(__a , mean=__a , std=__a , data_format=__a , **__a) def SCREAMING_SNAKE_CASE__ (self , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = ChannelDimension.FIRST , **__a , ) -> PIL.Image.Image: """simple docstring""" __snake_case : List[str] = do_resize if do_resize is not None else self.do_resize __snake_case : int = size if size is not None else self.size __snake_case : Union[str, Any] = get_size_dict(__a , param_name='size' , default_to_square=__a) __snake_case : Any = resample if resample is not None else self.resample __snake_case : Optional[Any] = do_center_crop if do_center_crop is not None else self.do_center_crop __snake_case : str = crop_size if crop_size is not None else self.crop_size __snake_case : int = get_size_dict(__a , param_name='crop_size' , default_to_square=__a) __snake_case : str = do_rescale if do_rescale is not None else self.do_rescale __snake_case : Optional[int] = rescale_factor if rescale_factor is not None else self.rescale_factor __snake_case : str = do_normalize if do_normalize is not None else self.do_normalize __snake_case : Union[str, Any] = image_mean if image_mean is not None else self.image_mean __snake_case : List[Any] = image_std if image_std is not None else self.image_std __snake_case : int = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __snake_case : List[Any] = make_list_of_images(__a) if not valid_images(__a): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.') if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.') if do_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.') # PIL RGBA images are converted to RGB if do_convert_rgb: __snake_case : Dict = [convert_to_rgb(__a) for image in images] # All transformations expect numpy arrays. __snake_case : List[str] = [to_numpy_array(__a) for image in images] if do_resize: __snake_case : Any = [self.resize(image=__a , size=__a , resample=__a) for image in images] if do_center_crop: __snake_case : Union[str, Any] = [self.center_crop(image=__a , size=__a) for image in images] if do_rescale: __snake_case : Any = [self.rescale(image=__a , scale=__a) for image in images] if do_normalize: __snake_case : Optional[int] = [self.normalize(image=__a , mean=__a , std=__a) for image in images] __snake_case : Optional[Any] = [to_channel_dimension_format(__a , __a) for image in images] __snake_case : Tuple = {'pixel_values': images} return BatchFeature(data=__a , tensor_type=__a)
61
'''simple docstring''' import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class a_ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): _snake_case = VQModel _snake_case = """sample""" @property def SCREAMING_SNAKE_CASE__ (self , __a=(3_2, 3_2)) -> str: """simple docstring""" __snake_case : Dict = 4 __snake_case : Optional[int] = 3 __snake_case : str = floats_tensor((batch_size, num_channels) + sizes).to(__a) return {"sample": image} @property def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" return (3, 3_2, 3_2) @property def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" return (3, 3_2, 3_2) def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" __snake_case : Optional[Any] = { 'block_out_channels': [3_2, 6_4], 'in_channels': 3, 'out_channels': 3, 'down_block_types': ['DownEncoderBlock2D', 'DownEncoderBlock2D'], 'up_block_types': ['UpDecoderBlock2D', 'UpDecoderBlock2D'], 'latent_channels': 3, } __snake_case : List[Any] = self.dummy_input return init_dict, inputs_dict def SCREAMING_SNAKE_CASE__ (self) -> Any: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" __snake_case ,__snake_case : List[Any] = VQModel.from_pretrained('fusing/vqgan-dummy' , output_loading_info=__a) self.assertIsNotNone(__a) self.assertEqual(len(loading_info['missing_keys']) , 0) model.to(__a) __snake_case : Any = model(**self.dummy_input) assert image is not None, "Make sure output is not None" def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" __snake_case : Union[str, Any] = VQModel.from_pretrained('fusing/vqgan-dummy') model.to(__a).eval() torch.manual_seed(0) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0) __snake_case : Tuple = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size) __snake_case : Optional[int] = image.to(__a) with torch.no_grad(): __snake_case : List[Any] = model(__a).sample __snake_case : int = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off __snake_case : int = torch.tensor([-0.0_153, -0.4_044, -0.1_880, -0.5_161, -0.2_418, -0.4_072, -0.1_612, -0.0_633, -0.0_143]) # fmt: on self.assertTrue(torch.allclose(__a , __a , atol=1E-3))
61
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) class a_ ( UpperCamelCase_ ): _snake_case = """timm_backbone""" def __init__(self , __a=None , __a=3 , __a=True , __a=True , __a=None , **__a , ) -> Union[str, Any]: """simple docstring""" super().__init__(**__a) __snake_case : List[str] = backbone __snake_case : Dict = num_channels __snake_case : List[Any] = features_only __snake_case : str = use_pretrained_backbone __snake_case : Optional[int] = True __snake_case : List[str] = out_indices if out_indices is not None else (-1,)
61
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process __A = logging.getLogger(__name__) @dataclass class a_ : _snake_case = field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} ) _snake_case = field( default=UpperCamelCase_ , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) _snake_case = field( default="""NER""" , metadata={"""help""": """Task type to fine tune in training (e.g. NER, POS, etc)"""} ) _snake_case = field( default=UpperCamelCase_ , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} ) _snake_case = field(default=UpperCamelCase_ , metadata={"""help""": """Set this flag to use fast tokenization."""} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. _snake_case = field( default=UpperCamelCase_ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) @dataclass class a_ : _snake_case = field( metadata={"""help""": """The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."""} ) _snake_case = field( default=UpperCamelCase_ , metadata={"""help""": """Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."""} , ) _snake_case = field( default=128 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) _snake_case = field( default=UpperCamelCase_ , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} ) def _SCREAMING_SNAKE_CASE ( ) -> int: """simple docstring""" # 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. __snake_case : List[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. __snake_case ,__snake_case ,__snake_case : List[str] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __snake_case ,__snake_case ,__snake_case : int = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. Use""" ' --overwrite_output_dir to overcome.' ) __snake_case : List[str] = import_module('tasks' ) try: __snake_case : Any = getattr(A , model_args.task_type ) __snake_case : TokenClassificationTask = token_classification_task_clazz() except AttributeError: raise ValueError( F"""Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. """ F"""Available tasks classes are: {TokenClassificationTask.__subclasses__()}""" ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( 'Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('Training/evaluation parameters %s' , A ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task __snake_case : Optional[Any] = token_classification_task.get_labels(data_args.labels ) __snake_case : Dict[int, str] = dict(enumerate(A ) ) __snake_case : Optional[Any] = len(A ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __snake_case : Any = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=A , idalabel=A , labelaid={label: i for i, label in enumerate(A )} , cache_dir=model_args.cache_dir , ) __snake_case : List[str] = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast , ) __snake_case : Optional[int] = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=A , cache_dir=model_args.cache_dir , ) # Get datasets __snake_case : List[Any] = ( TokenClassificationDataset( token_classification_task=A , data_dir=data_args.data_dir , tokenizer=A , labels=A , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) __snake_case : int = ( TokenClassificationDataset( token_classification_task=A , data_dir=data_args.data_dir , tokenizer=A , labels=A , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def align_predictions(A : np.ndarray , A : np.ndarray ) -> Tuple[List[int], List[int]]: __snake_case : str = np.argmax(A , axis=2 ) __snake_case ,__snake_case : int = preds.shape __snake_case : Dict = [[] for _ in range(A )] __snake_case : Union[str, Any] = [[] for _ in range(A )] for i in range(A ): for j in range(A ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(A : EvalPrediction ) -> Dict: __snake_case ,__snake_case : Any = align_predictions(p.predictions , p.label_ids ) return { "accuracy_score": accuracy_score(A , A ), "precision": precision_score(A , A ), "recall": recall_score(A , A ), "f1": fa_score(A , A ), } # Data collator __snake_case : Optional[int] = DataCollatorWithPadding(A , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer __snake_case : Optional[Any] = Trainer( model=A , args=A , train_dataset=A , eval_dataset=A , compute_metrics=A , data_collator=A , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation __snake_case : List[Any] = {} if training_args.do_eval: logger.info('*** Evaluate ***' ) __snake_case : List[str] = trainer.evaluate() __snake_case : Tuple = os.path.join(training_args.output_dir , 'eval_results.txt' ) if trainer.is_world_process_zero(): with open(A , 'w' ) as writer: logger.info('***** Eval results *****' ) for key, value in result.items(): logger.info(' %s = %s' , A , A ) writer.write('%s = %s\n' % (key, value) ) results.update(A ) # Predict if training_args.do_predict: __snake_case : str = TokenClassificationDataset( token_classification_task=A , data_dir=data_args.data_dir , tokenizer=A , labels=A , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , ) __snake_case ,__snake_case ,__snake_case : str = trainer.predict(A ) __snake_case ,__snake_case : List[str] = align_predictions(A , A ) __snake_case : Optional[int] = os.path.join(training_args.output_dir , 'test_results.txt' ) if trainer.is_world_process_zero(): with open(A , 'w' ) as writer: for key, value in metrics.items(): logger.info(' %s = %s' , A , A ) writer.write('%s = %s\n' % (key, value) ) # Save predictions __snake_case : List[str] = os.path.join(training_args.output_dir , 'test_predictions.txt' ) if trainer.is_world_process_zero(): with open(A , 'w' ) as writer: with open(os.path.join(data_args.data_dir , 'test.txt' ) , 'r' ) as f: token_classification_task.write_predictions_to_file(A , A , A ) return results def _SCREAMING_SNAKE_CASE ( A : int ) -> Any: """simple docstring""" # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
61
1
'''simple docstring''' __A = {str(digit): digit**5 for digit in range(1_0)} def _SCREAMING_SNAKE_CASE ( A : int ) -> int: """simple docstring""" return sum(DIGITS_FIFTH_POWER[digit] for digit in str(A ) ) def _SCREAMING_SNAKE_CASE ( ) -> int: """simple docstring""" return sum( number for number in range(10_00 , 1_00_00_00 ) if number == digits_fifth_powers_sum(A ) ) if __name__ == "__main__": print(solution())
61
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( A : list ) -> list: """simple docstring""" __snake_case : Tuple = False while is_sorted is False: # Until all the indices are traversed keep looping __snake_case : Optional[Any] = True for i in range(0 , len(A ) - 1 , 2 ): # iterating over all even indices if input_list[i] > input_list[i + 1]: __snake_case ,__snake_case : int = input_list[i + 1], input_list[i] # swapping if elements not in order __snake_case : List[Any] = False for i in range(1 , len(A ) - 1 , 2 ): # iterating over all odd indices if input_list[i] > input_list[i + 1]: __snake_case ,__snake_case : Tuple = input_list[i + 1], input_list[i] # swapping if elements not in order __snake_case : Any = False return input_list if __name__ == "__main__": print('''Enter list to be sorted''') __A = [int(x) for x in input().split()] # inputing elements of the list in one line __A = odd_even_sort(input_list) print('''The sorted list is''') print(sorted_list)
61
1
'''simple docstring''' from unittest.mock import Mock, patch from file_transfer.send_file import send_file @patch('socket.socket' ) @patch('builtins.open' ) def _SCREAMING_SNAKE_CASE ( A : Tuple , A : Tuple ) -> Union[str, Any]: """simple docstring""" # ===== initialization ===== __snake_case : List[str] = Mock() __snake_case : int = conn, Mock() __snake_case : List[Any] = iter([1, None] ) __snake_case : int = lambda A : next(A ) # ===== invoke ===== send_file(filename='mytext.txt' , testing=A ) # ===== ensurance ===== sock.assert_called_once() sock.return_value.bind.assert_called_once() sock.return_value.listen.assert_called_once() sock.return_value.accept.assert_called_once() conn.recv.assert_called_once() file.return_value.__enter__.assert_called_once() file.return_value.__enter__.return_value.read.assert_called() conn.send.assert_called_once() conn.close.assert_called_once() sock.return_value.shutdown.assert_called_once() sock.return_value.close.assert_called_once()
61
'''simple docstring''' import argparse import json from collections import OrderedDict from functools import partial from pathlib import Path import timm import torch from huggingface_hub import hf_hub_download from transformers import LevitConfig, LevitForImageClassificationWithTeacher, LevitImageProcessor from transformers.utils import logging logging.set_verbosity_info() __A = logging.get_logger() def _SCREAMING_SNAKE_CASE ( A : int , A : str , A : LevitConfig , A : Path , A : bool = True ) -> Dict: """simple docstring""" print(F"""Converting {name}...""" ) with torch.no_grad(): if hidden_sizes == 1_28: if name[-1] == "S": __snake_case : Optional[int] = timm.create_model('levit_128s' , pretrained=A ) else: __snake_case : Tuple = timm.create_model('levit_128' , pretrained=A ) if hidden_sizes == 1_92: __snake_case : int = timm.create_model('levit_192' , pretrained=A ) if hidden_sizes == 2_56: __snake_case : List[Any] = timm.create_model('levit_256' , pretrained=A ) if hidden_sizes == 3_84: __snake_case : int = timm.create_model('levit_384' , pretrained=A ) from_model.eval() __snake_case : str = LevitForImageClassificationWithTeacher(A ).eval() __snake_case : int = OrderedDict() __snake_case : Optional[Any] = from_model.state_dict() __snake_case : Tuple = list(from_model.state_dict().keys() ) __snake_case : List[str] = list(our_model.state_dict().keys() ) print(len(A ) , len(A ) ) for i in range(len(A ) ): __snake_case : Optional[int] = weights[og_keys[i]] our_model.load_state_dict(A ) __snake_case : Tuple = torch.randn((2, 3, 2_24, 2_24) ) __snake_case : Union[str, Any] = from_model(A ) __snake_case : List[str] = our_model(A ).logits assert torch.allclose(A , A ), "The model logits don't match the original one." __snake_case : int = name print(A ) if push_to_hub: our_model.save_pretrained(save_directory / checkpoint_name ) __snake_case : int = LevitImageProcessor() image_processor.save_pretrained(save_directory / checkpoint_name ) print(F"""Pushed {checkpoint_name}""" ) def _SCREAMING_SNAKE_CASE ( A : Path , A : str = None , A : bool = True ) -> List[Any]: """simple docstring""" __snake_case : Optional[Any] = 'imagenet-1k-id2label.json' __snake_case : Tuple = 10_00 __snake_case : Dict = (1, num_labels) __snake_case : List[str] = 'huggingface/label-files' __snake_case : Any = num_labels __snake_case : str = json.load(open(hf_hub_download(A , A , repo_type='dataset' ) , 'r' ) ) __snake_case : Any = {int(A ): v for k, v in idalabel.items()} __snake_case : int = idalabel __snake_case : Union[str, Any] = {v: k for k, v in idalabel.items()} __snake_case : Optional[int] = partial(A , num_labels=A , idalabel=A , labelaid=A ) __snake_case : Dict = { 'levit-128S': 1_28, 'levit-128': 1_28, 'levit-192': 1_92, 'levit-256': 2_56, 'levit-384': 3_84, } __snake_case : Union[str, Any] = { 'levit-128S': ImageNetPreTrainedConfig( hidden_sizes=[1_28, 2_56, 3_84] , num_attention_heads=[4, 6, 8] , depths=[2, 3, 4] , key_dim=[16, 16, 16] , drop_path_rate=0 , ), 'levit-128': ImageNetPreTrainedConfig( hidden_sizes=[1_28, 2_56, 3_84] , num_attention_heads=[4, 8, 12] , depths=[4, 4, 4] , key_dim=[16, 16, 16] , drop_path_rate=0 , ), 'levit-192': ImageNetPreTrainedConfig( hidden_sizes=[1_92, 2_88, 3_84] , num_attention_heads=[3, 5, 6] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0 , ), 'levit-256': ImageNetPreTrainedConfig( hidden_sizes=[2_56, 3_84, 5_12] , num_attention_heads=[4, 6, 8] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0 , ), 'levit-384': ImageNetPreTrainedConfig( hidden_sizes=[3_84, 5_12, 7_68] , num_attention_heads=[6, 9, 12] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0.1 , ), } if model_name: convert_weight_and_push( names_to_hidden_sizes[model_name] , A , names_to_config[model_name] , A , A ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(names_to_hidden_sizes[model_name] , A , A , A , A ) return config, expected_shape if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default=None, type=str, help='''The name of the model you wish to convert, it must be one of the supported Levit* architecture,''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default='''levit-dump-folder/''', type=Path, required=False, help='''Path to the output PyTorch model directory.''', ) parser.add_argument('''--push_to_hub''', action='''store_true''', help='''Push model and image processor to the hub''') parser.add_argument( '''--no-push_to_hub''', dest='''push_to_hub''', action='''store_false''', help='''Do not push model and image processor to the hub''', ) __A = parser.parse_args() __A = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
61
1
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor class a_ ( unittest.TestCase ): def __init__(self , __a , __a=7 , __a=3 , __a=1_8 , __a=3_0 , __a=4_0_0 , __a=True , __a=None , __a=True , __a=None , __a=True , __a=[0.48_145_466, 0.4_578_275, 0.40_821_073] , __a=[0.26_862_954, 0.26_130_258, 0.27_577_711] , __a=True , ) -> List[Any]: """simple docstring""" __snake_case : Tuple = size if size is not None else {'height': 2_2_4, 'width': 2_2_4} __snake_case : Any = crop_size if crop_size is not None else {'height': 1_8, 'width': 1_8} __snake_case : Optional[int] = parent __snake_case : Dict = batch_size __snake_case : str = num_channels __snake_case : Optional[Any] = image_size __snake_case : Optional[int] = min_resolution __snake_case : Tuple = max_resolution __snake_case : Optional[int] = do_resize __snake_case : Optional[int] = size __snake_case : Union[str, Any] = do_center_crop __snake_case : List[Any] = crop_size __snake_case : int = do_normalize __snake_case : Optional[Any] = image_mean __snake_case : str = image_std __snake_case : Optional[Any] = do_convert_rgb def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def SCREAMING_SNAKE_CASE__ (self , __a=False , __a=False , __a=False) -> List[str]: """simple docstring""" assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" if equal_resolution: __snake_case : Optional[int] = [] for i in range(self.batch_size): image_inputs.append( np.random.randint( 2_5_5 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta)) else: __snake_case : Dict = [] for i in range(self.batch_size): __snake_case ,__snake_case : Optional[Any] = np.random.choice(np.arange(self.min_resolution , self.max_resolution) , 2) image_inputs.append(np.random.randint(2_5_5 , size=(self.num_channels, width, height) , dtype=np.uinta)) if not numpify and not torchify: # PIL expects the channel dimension as last dimension __snake_case : int = [Image.fromarray(np.moveaxis(__a , 0 , -1)) for x in image_inputs] if torchify: __snake_case : List[Any] = [torch.from_numpy(__a) for x in image_inputs] return image_inputs @require_torch @require_vision class a_ ( UpperCamelCase_ , unittest.TestCase ): _snake_case = ChineseCLIPImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : Union[str, Any] = ChineseCLIPImageProcessingTester(self , do_center_crop=__a) @property def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : int = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(__a , 'do_resize')) self.assertTrue(hasattr(__a , 'size')) self.assertTrue(hasattr(__a , 'do_center_crop')) self.assertTrue(hasattr(__a , 'center_crop')) self.assertTrue(hasattr(__a , 'do_normalize')) self.assertTrue(hasattr(__a , 'image_mean')) self.assertTrue(hasattr(__a , 'image_std')) self.assertTrue(hasattr(__a , 'do_convert_rgb')) def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size , {'height': 2_2_4, 'width': 2_2_4}) self.assertEqual(image_processor.crop_size , {'height': 1_8, 'width': 1_8}) __snake_case : List[str] = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 , crop_size=8_4) self.assertEqual(image_processor.size , {'shortest_edge': 4_2}) self.assertEqual(image_processor.crop_size , {'height': 8_4, 'width': 8_4}) def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" __snake_case : List[Any] = self.image_processing_class(**self.image_processor_dict) # create random PIL images __snake_case : Optional[Any] = self.image_processor_tester.prepare_inputs(equal_resolution=__a) for image in image_inputs: self.assertIsInstance(__a , Image.Image) # Test not batched input __snake_case : 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __snake_case : List[Any] = image_processing(__a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" __snake_case : Union[str, Any] = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors __snake_case : Optional[int] = self.image_processor_tester.prepare_inputs(equal_resolution=__a , numpify=__a) for image in image_inputs: self.assertIsInstance(__a , np.ndarray) # Test not batched input __snake_case : List[Any] = image_processing(image_inputs[0] , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __snake_case : int = image_processing(__a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : Any = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors __snake_case : Tuple = self.image_processor_tester.prepare_inputs(equal_resolution=__a , torchify=__a) for image in image_inputs: self.assertIsInstance(__a , torch.Tensor) # Test not batched input __snake_case : Any = image_processing(image_inputs[0] , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __snake_case : Union[str, Any] = image_processing(__a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) @require_torch @require_vision class a_ ( UpperCamelCase_ , unittest.TestCase ): _snake_case = ChineseCLIPImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" __snake_case : Optional[Any] = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=__a) __snake_case : List[Any] = 3 @property def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : Any = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(__a , 'do_resize')) self.assertTrue(hasattr(__a , 'size')) self.assertTrue(hasattr(__a , 'do_center_crop')) self.assertTrue(hasattr(__a , 'center_crop')) self.assertTrue(hasattr(__a , 'do_normalize')) self.assertTrue(hasattr(__a , 'image_mean')) self.assertTrue(hasattr(__a , 'image_std')) self.assertTrue(hasattr(__a , 'do_convert_rgb')) def SCREAMING_SNAKE_CASE__ (self) -> Tuple: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : List[Any] = self.image_processing_class(**self.image_processor_dict) # create random PIL images __snake_case : Union[str, Any] = self.image_processor_tester.prepare_inputs(equal_resolution=__a) for image in image_inputs: self.assertIsInstance(__a , Image.Image) # Test not batched input __snake_case : Optional[int] = image_processing(image_inputs[0] , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __snake_case : Optional[int] = image_processing(__a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , )
61
'''simple docstring''' import inspect import unittest from typing import List import numpy as np from transformers import EfficientFormerConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerModel, ) from transformers.models.efficientformer.modeling_tf_efficientformer import ( TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_vision_available(): from PIL import Image from transformers import EfficientFormerImageProcessor class a_ : def __init__(self , __a , __a = 1_3 , __a = 6_4 , __a = 2 , __a = 3 , __a = 3 , __a = True , __a = True , __a = 1_2_8 , __a=[1_6, 3_2, 6_4, 1_2_8] , __a = 7 , __a = 4 , __a = 3_7 , __a = "gelu" , __a = 0.1 , __a = 0.1 , __a = 1_0 , __a = 0.02 , __a = 2 , __a = 1 , __a = 1_2_8 , __a = [2, 2, 2, 2] , __a = 2 , __a = 2 , ) -> str: """simple docstring""" __snake_case : Optional[Any] = parent __snake_case : Optional[int] = batch_size __snake_case : Optional[Any] = image_size __snake_case : Optional[int] = patch_size __snake_case : Optional[Any] = num_channels __snake_case : Optional[Any] = is_training __snake_case : Tuple = use_labels __snake_case : Optional[int] = hidden_size __snake_case : Any = num_hidden_layers __snake_case : List[str] = num_attention_heads __snake_case : Tuple = intermediate_size __snake_case : List[str] = hidden_act __snake_case : Dict = hidden_dropout_prob __snake_case : Any = attention_probs_dropout_prob __snake_case : Dict = type_sequence_label_size __snake_case : str = initializer_range __snake_case : int = encoder_stride __snake_case : List[str] = num_attention_outputs __snake_case : Optional[Any] = embed_dim __snake_case : Optional[Any] = embed_dim + 1 __snake_case : List[str] = resolution __snake_case : Optional[int] = depths __snake_case : List[Any] = hidden_sizes __snake_case : List[str] = dim __snake_case : Union[str, Any] = mlp_expansion_ratio def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" __snake_case : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) __snake_case : List[str] = None if self.use_labels: __snake_case : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size) __snake_case : Tuple = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" return EfficientFormerConfig( 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=__a , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , resolution=self.resolution , depths=self.depths , hidden_sizes=self.hidden_sizes , dim=self.dim , mlp_expansion_ratio=self.mlp_expansion_ratio , ) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Optional[int]: """simple docstring""" __snake_case : Union[str, Any] = TFEfficientFormerModel(config=__a) __snake_case : int = model(__a , training=__a) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Tuple: """simple docstring""" __snake_case : Dict = self.type_sequence_label_size __snake_case : List[Any] = TFEfficientFormerForImageClassification(__a) __snake_case : Optional[int] = model(__a , labels=__a , training=__a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) # test greyscale images __snake_case : List[Any] = 1 __snake_case : List[Any] = TFEfficientFormerForImageClassification(__a) __snake_case : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) __snake_case : str = model(__a , labels=__a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) def SCREAMING_SNAKE_CASE__ (self) -> Any: """simple docstring""" __snake_case : Union[str, Any] = self.prepare_config_and_inputs() __snake_case ,__snake_case ,__snake_case : Union[str, Any] = config_and_inputs __snake_case : Optional[int] = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class a_ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): _snake_case = ( ( TFEfficientFormerModel, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerForImageClassification, ) if is_tf_available() else () ) _snake_case = ( { """feature-extraction""": TFEfficientFormerModel, """image-classification""": ( TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, ), } if is_tf_available() else {} ) _snake_case = False _snake_case = False _snake_case = False _snake_case = False _snake_case = False def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : Dict = TFEfficientFormerModelTester(self) __snake_case : List[Any] = ConfigTester( self , config_class=__a , has_text_modality=__a , hidden_size=3_7) def SCREAMING_SNAKE_CASE__ (self) -> str: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='EfficientFormer does not use inputs_embeds') def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" pass @unittest.skip(reason='EfficientFormer does not support input and output embeddings') def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self) -> Any: """simple docstring""" __snake_case ,__snake_case : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : Optional[int] = model_class(__a) __snake_case : Union[str, Any] = inspect.signature(model.call) # signature.parameters is an OrderedDict => so arg_names order is deterministic __snake_case : Optional[int] = [*signature.parameters.keys()] __snake_case : Dict = ['pixel_values'] self.assertListEqual(arg_names[:1] , __a) def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" def check_hidden_states_output(__a , __a , __a): __snake_case : str = model_class(__a) __snake_case : List[Any] = model(**self._prepare_for_class(__a , __a) , training=__a) __snake_case : str = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __snake_case : Optional[Any] = getattr( self.model_tester , 'expected_num_hidden_layers' , self.model_tester.num_hidden_layers + 1) self.assertEqual(len(__a) , __a) if hasattr(self.model_tester , 'encoder_seq_length'): __snake_case : List[Any] = self.model_tester.encoder_seq_length if hasattr(self.model_tester , 'chunk_length') and self.model_tester.chunk_length > 1: __snake_case : str = seq_length * self.model_tester.chunk_length else: __snake_case : Optional[int] = self.model_tester.seq_length self.assertListEqual( list(hidden_states[-1].shape[-2:]) , [seq_length, self.model_tester.hidden_size] , ) if config.is_encoder_decoder: __snake_case : List[Any] = outputs.decoder_hidden_states self.asseretIsInstance(__a , (list, tuple)) self.assertEqual(len(__a) , __a) __snake_case : List[str] = getattr(self.model_tester , 'seq_length' , __a) __snake_case : Tuple = getattr(self.model_tester , 'decoder_seq_length' , __a) self.assertListEqual( list(hidden_states[-1].shape[-2:]) , [decoder_seq_length, self.model_tester.hidden_size] , ) __snake_case ,__snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : List[str] = True check_hidden_states_output(__a , __a , __a) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __snake_case : str = True check_hidden_states_output(__a , __a , __a) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a=False) -> int: """simple docstring""" __snake_case : Optional[int] = super()._prepare_for_class(__a , __a , return_labels=__a) if return_labels: if model_class.__name__ == "TFEfficientFormerForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" __snake_case : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a) @unittest.skip(reason='EfficientFormer does not implement masked image modeling yet') def SCREAMING_SNAKE_CASE__ (self) -> Tuple: """simple docstring""" __snake_case : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*__a) def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__a) @slow def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case : Any = TFEfficientFormerModel.from_pretrained(__a) self.assertIsNotNone(__a) def SCREAMING_SNAKE_CASE__ (self) -> Tuple: """simple docstring""" __snake_case ,__snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() __snake_case : Tuple = True __snake_case : Optional[Any] = getattr(self.model_tester , 'seq_length' , __a) __snake_case : List[Any] = getattr(self.model_tester , 'encoder_seq_length' , __a) __snake_case : Tuple = getattr(self.model_tester , 'key_length' , __a) __snake_case : Optional[Any] = getattr(self.model_tester , 'chunk_length' , __a) if chunk_length is not None and hasattr(self.model_tester , 'num_hashes'): __snake_case : str = encoder_seq_length * self.model_tester.num_hashes for model_class in self.all_model_classes: __snake_case : Optional[Any] = True __snake_case : Dict = False __snake_case : Optional[int] = True __snake_case : Dict = model_class(__a) __snake_case : Tuple = model(**self._prepare_for_class(__a , __a) , training=__a) __snake_case : Union[str, Any] = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(__a) , self.model_tester.num_attention_outputs) # check that output_attentions also work using config del inputs_dict["output_attentions"] __snake_case : Dict = True __snake_case : str = model_class(__a) __snake_case : str = model(**self._prepare_for_class(__a , __a) , training=__a) __snake_case : Tuple = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(__a) , self.model_tester.num_attention_outputs) if chunk_length is not None: self.assertListEqual( list(attentions[0].shape[-4:]) , [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length] , ) else: self.assertListEqual( list(attentions[0].shape[-3:]) , [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length] , ) def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case ,__snake_case : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # Prepare our model __snake_case : Tuple = model_class(__a) # These are maximally general inputs for the model, with multiple None dimensions # Hopefully this will catch any conditionals that fail for flexible shapes __snake_case : Optional[Any] = { key: tf.keras.Input(shape=val.shape[1:] , dtype=val.dtype , name=__a) for key, val in model.input_signature.items() if key in model.dummy_inputs } __snake_case : Tuple = model(__a) self.assertTrue(outputs_dict is not None) def _SCREAMING_SNAKE_CASE ( ) -> int: """simple docstring""" __snake_case : Tuple = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class a_ ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" return ( EfficientFormerImageProcessor.from_pretrained('snap-research/efficientformer-l1-300') if is_vision_available() else None ) @slow def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" __snake_case : List[str] = TFEfficientFormerForImageClassification.from_pretrained('snap-research/efficientformer-l1-300') __snake_case : Optional[int] = self.default_image_processor __snake_case : List[Any] = prepare_img() __snake_case : List[Any] = image_processor(images=__a , return_tensors='tf') # forward pass __snake_case : List[str] = model(**__a , training=__a) # verify the logits __snake_case : str = tf.TensorShape((1, 1_0_0_0)) self.assertEqual(outputs.logits.shape , __a) __snake_case : Any = tf.constant([-0.0_555, 0.4_825, -0.0_852]) self.assertTrue(np.allclose(outputs.logits[0, :3] , __a , atol=1E-4)) @slow def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" __snake_case : List[Any] = TFEfficientFormerForImageClassificationWithTeacher.from_pretrained( 'snap-research/efficientformer-l1-300') __snake_case : List[Any] = self.default_image_processor __snake_case : Union[str, Any] = prepare_img() __snake_case : List[Any] = image_processor(images=__a , return_tensors='tf') # forward pass __snake_case : Optional[int] = model(**__a , training=__a) # verify the logits __snake_case : Optional[int] = tf.TensorShape((1, 1_0_0_0)) self.assertEqual(outputs.logits.shape , __a) __snake_case : List[str] = tf.constant([-0.1_312, 0.4_353, -1.0_499]) self.assertTrue(np.allclose(outputs.logits[0, :3] , __a , atol=1E-4))
61
1
'''simple docstring''' import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class a_ ( UpperCamelCase_ ): _snake_case = ["""image_processor""", """tokenizer"""] _snake_case = """LayoutLMv2ImageProcessor""" _snake_case = ("""LayoutXLMTokenizer""", """LayoutXLMTokenizerFast""") def __init__(self , __a=None , __a=None , **__a) -> Tuple: """simple docstring""" if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , __a , ) __snake_case : List[str] = kwargs.pop('feature_extractor') __snake_case : Tuple = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.') if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.') super().__init__(__a , __a) def __call__(self , __a , __a = None , __a = None , __a = None , __a = None , __a = True , __a = False , __a = None , __a = None , __a = 0 , __a = None , __a = None , __a = None , __a = False , __a = False , __a = False , __a = False , __a = True , __a = None , **__a , ) -> BatchEncoding: """simple docstring""" if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( 'You cannot provide bounding boxes ' 'if you initialized the image processor with apply_ocr set to True.') if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( 'You cannot provide word labels if you initialized the image processor with apply_ocr set to True.') if return_overflowing_tokens is True and return_offsets_mapping is False: raise ValueError('You cannot return overflowing tokens without returning the offsets mapping.') # first, apply the image processor __snake_case : str = self.image_processor(images=__a , return_tensors=__a) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(__a , __a): __snake_case : Optional[int] = [text] # add batch dimension (as the image processor always adds a batch dimension) __snake_case : str = features['words'] __snake_case : Union[str, Any] = self.tokenizer( text=text if text is not None else features['words'] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features['boxes'] , word_labels=__a , add_special_tokens=__a , padding=__a , truncation=__a , max_length=__a , stride=__a , pad_to_multiple_of=__a , return_token_type_ids=__a , return_attention_mask=__a , return_overflowing_tokens=__a , return_special_tokens_mask=__a , return_offsets_mapping=__a , return_length=__a , verbose=__a , return_tensors=__a , **__a , ) # add pixel values __snake_case : Any = features.pop('pixel_values') if return_overflowing_tokens is True: __snake_case : str = self.get_overflowing_images(__a , encoded_inputs['overflow_to_sample_mapping']) __snake_case : str = images return encoded_inputs def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> str: """simple docstring""" __snake_case : Union[str, Any] = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx]) if len(__a) != len(__a): raise ValueError( 'Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got' F""" {len(__a)} and {len(__a)}""") return images_with_overflow def SCREAMING_SNAKE_CASE__ (self , *__a , **__a) -> List[str]: """simple docstring""" return self.tokenizer.batch_decode(*__a , **__a) def SCREAMING_SNAKE_CASE__ (self , *__a , **__a) -> Any: """simple docstring""" return self.tokenizer.decode(*__a , **__a) @property def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" return ["input_ids", "bbox", "attention_mask", "image"] @property def SCREAMING_SNAKE_CASE__ (self) -> str: """simple docstring""" warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , __a , ) return self.image_processor_class @property def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , __a , ) return self.image_processor
61
'''simple docstring''' __A = {str(digit): digit**5 for digit in range(1_0)} def _SCREAMING_SNAKE_CASE ( A : int ) -> int: """simple docstring""" return sum(DIGITS_FIFTH_POWER[digit] for digit in str(A ) ) def _SCREAMING_SNAKE_CASE ( ) -> int: """simple docstring""" return sum( number for number in range(10_00 , 1_00_00_00 ) if number == digits_fifth_powers_sum(A ) ) if __name__ == "__main__": print(solution())
61
1
'''simple docstring''' from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast from ...utils import logging __A = logging.get_logger(__name__) __A = { '''EleutherAI/gpt-neo-1.3B''': '''https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json''', # See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo } class a_ ( UpperCamelCase_ ): _snake_case = """gpt_neo""" _snake_case = ["""past_key_values"""] _snake_case = {"""num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers"""} def __init__(self , __a=5_0_2_5_7 , __a=2_0_4_8 , __a=2_0_4_8 , __a=2_4 , __a=[[["global", "local"], 1_2]] , __a=1_6 , __a=None , __a=2_5_6 , __a="gelu_new" , __a=0.0 , __a=0.0 , __a=0.0 , __a=0.1 , __a=1E-5 , __a=0.02 , __a=True , __a=5_0_2_5_6 , __a=5_0_2_5_6 , **__a , ) -> Dict: """simple docstring""" __snake_case : Tuple = vocab_size __snake_case : Tuple = max_position_embeddings __snake_case : List[Any] = hidden_size __snake_case : int = num_layers __snake_case : Dict = num_heads __snake_case : Optional[int] = intermediate_size __snake_case : List[Any] = window_size __snake_case : Optional[Any] = activation_function __snake_case : str = resid_dropout __snake_case : str = embed_dropout __snake_case : Union[str, Any] = attention_dropout __snake_case : Any = classifier_dropout __snake_case : Tuple = layer_norm_epsilon __snake_case : Any = initializer_range __snake_case : Optional[int] = use_cache __snake_case : List[str] = bos_token_id __snake_case : int = eos_token_id __snake_case : Any = attention_types __snake_case : Tuple = self.expand_attention_types_params(__a) if len(self.attention_layers) != self.num_layers: raise ValueError( 'Configuration for convolutional module is incorrect. ' 'It is required that `len(config.attention_layers)` == `config.num_layers` ' F"""but is `len(config.attention_layers) = {len(self.attention_layers)}`, """ F"""`config.num_layers = {self.num_layers}`. """ '`config.attention_layers` is prepared using `config.attention_types`. ' 'Please verify the value of `config.attention_types` argument.') super().__init__(bos_token_id=__a , eos_token_id=__a , **__a) @staticmethod def SCREAMING_SNAKE_CASE__ (__a) -> Tuple: """simple docstring""" __snake_case : List[str] = [] for item in attention_types: for _ in range(item[1]): attentions.extend(item[0]) return attentions def _SCREAMING_SNAKE_CASE ( A : Any , A : Tuple , A : Dict , A : List[str] ) -> Optional[int]: """simple docstring""" import torch __snake_case : str = input.size() __snake_case : str = len(A ) __snake_case : List[Any] = shape[dimension] __snake_case : int = torch.arange(0 , A , A ) __snake_case : List[Any] = torch.div(sizedim - size , A , rounding_mode='floor' ) + 1 __snake_case : Dict = torch.arange(A ) + low_indices[:min_length][:, None] __snake_case : int = [slice(A )] * rank __snake_case : Dict = indices __snake_case : List[str] = input[s] __snake_case : Tuple = list(range(0 , rank + 1 ) ) perm.append(perm.pop(dimension + 1 ) ) return sliced.permute(A ) def _SCREAMING_SNAKE_CASE ( A : Tuple , A : List[Any] ) -> Union[str, Any]: """simple docstring""" import torch __snake_case : Tuple = torch.arange(1 , A ) __snake_case : Tuple = torch.remainder(A , A ) __snake_case : Optional[Any] = remainders == 0 __snake_case : Optional[int] = candidates[divisor_indices] __snake_case : Tuple = torch.max(A ) return largest_divisor, torch.div(A , A , rounding_mode='floor' ) class a_ ( UpperCamelCase_ ): @property def SCREAMING_SNAKE_CASE__ (self) -> Mapping[str, Mapping[int, str]]: """simple docstring""" __snake_case : str = OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}}) if self.use_past: self.fill_with_past_key_values_(__a , direction='inputs') __snake_case : List[str] = {0: 'batch', 1: 'past_sequence + sequence'} else: __snake_case : Dict = {0: 'batch', 1: 'sequence'} return common_inputs @property def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" return self._config.num_heads def SCREAMING_SNAKE_CASE__ (self , __a , __a = -1 , __a = -1 , __a = False , __a = None , ) -> Mapping[str, Any]: """simple docstring""" __snake_case : int = super(__a , self).generate_dummy_inputs( __a , batch_size=__a , seq_length=__a , is_pair=__a , framework=__a) # We need to order the input in the way they appears in the forward() __snake_case : str = OrderedDict({'input_ids': common_inputs['input_ids']}) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.') else: import torch __snake_case ,__snake_case : Optional[Any] = common_inputs['input_ids'].shape # Not using the same length for past_key_values __snake_case : Optional[Any] = seqlen + 2 __snake_case : str = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) __snake_case : List[Any] = [ (torch.zeros(__a), torch.zeros(__a)) for _ in range(self.num_layers) ] __snake_case : Any = common_inputs['attention_mask'] if self.use_past: __snake_case : Any = ordered_inputs['attention_mask'].dtype __snake_case : Optional[Any] = torch.cat( [ordered_inputs['attention_mask'], torch.ones(__a , __a , dtype=__a)] , dim=1) return ordered_inputs @property def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" return 1_3
61
'''simple docstring''' from __future__ import annotations from collections import deque from collections.abc import Sequence from dataclasses import dataclass from typing import Any @dataclass class a_ : _snake_case = 42 _snake_case = None _snake_case = None def _SCREAMING_SNAKE_CASE ( ) -> Node | None: """simple docstring""" __snake_case : str = Node(1 ) __snake_case : Tuple = Node(2 ) __snake_case : Optional[int] = Node(3 ) __snake_case : List[str] = Node(4 ) __snake_case : List[str] = Node(5 ) return tree def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> list[int]: """simple docstring""" return [root.data, *preorder(root.left ), *preorder(root.right )] if root else [] def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> list[int]: """simple docstring""" return postorder(root.left ) + postorder(root.right ) + [root.data] if root else [] def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> list[int]: """simple docstring""" return [*inorder(root.left ), root.data, *inorder(root.right )] if root else [] def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> int: """simple docstring""" return (max(height(root.left ) , height(root.right ) ) + 1) if root else 0 def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> Sequence[Node | None]: """simple docstring""" __snake_case : list[Any] = [] if root is None: return output __snake_case : Optional[int] = deque([root] ) while process_queue: __snake_case : List[str] = process_queue.popleft() output.append(node.data ) if node.left: process_queue.append(node.left ) if node.right: process_queue.append(node.right ) return output def _SCREAMING_SNAKE_CASE ( A : Node | None , A : int ) -> Sequence[Node | None]: """simple docstring""" __snake_case : list[Any] = [] def populate_output(A : Node | None , A : int ) -> None: if not root: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.left , level - 1 ) populate_output(root.right , level - 1 ) populate_output(A , A ) return output def _SCREAMING_SNAKE_CASE ( A : Node | None , A : int ) -> Sequence[Node | None]: """simple docstring""" __snake_case : list[Any] = [] def populate_output(A : Node | None , A : int ) -> None: if root is None: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.right , level - 1 ) populate_output(root.left , level - 1 ) populate_output(A , A ) return output def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> Sequence[Node | None] | list[Any]: """simple docstring""" if root is None: return [] __snake_case : list[Sequence[Node | None]] = [] __snake_case : List[Any] = 0 __snake_case : int = height(A ) for h in range(1 , height_tree + 1 ): if not flag: output.append(get_nodes_from_left_to_right(A , A ) ) __snake_case : int = 1 else: output.append(get_nodes_from_right_to_left(A , A ) ) __snake_case : Tuple = 0 return output def _SCREAMING_SNAKE_CASE ( ) -> None: # Main function for testing. """simple docstring""" __snake_case : Optional[int] = make_tree() print(F"""In-order Traversal: {inorder(A )}""" ) print(F"""Pre-order Traversal: {preorder(A )}""" ) print(F"""Post-order Traversal: {postorder(A )}""" , '\n' ) print(F"""Height of Tree: {height(A )}""" , '\n' ) print('Complete Level Order Traversal: ' ) print(level_order(A ) , '\n' ) print('Level-wise order Traversal: ' ) for level in range(1 , height(A ) + 1 ): print(F"""Level {level}:""" , get_nodes_from_left_to_right(A , level=A ) ) print('\nZigZag order Traversal: ' ) print(zigzag(A ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
61
1
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool __A = { '''Acehnese Arabic''': '''ace_Arab''', '''Acehnese Latin''': '''ace_Latn''', '''Mesopotamian Arabic''': '''acm_Arab''', '''Ta\'izzi-Adeni Arabic''': '''acq_Arab''', '''Tunisian Arabic''': '''aeb_Arab''', '''Afrikaans''': '''afr_Latn''', '''South Levantine Arabic''': '''ajp_Arab''', '''Akan''': '''aka_Latn''', '''Amharic''': '''amh_Ethi''', '''North Levantine Arabic''': '''apc_Arab''', '''Modern Standard Arabic''': '''arb_Arab''', '''Modern Standard Arabic Romanized''': '''arb_Latn''', '''Najdi Arabic''': '''ars_Arab''', '''Moroccan Arabic''': '''ary_Arab''', '''Egyptian Arabic''': '''arz_Arab''', '''Assamese''': '''asm_Beng''', '''Asturian''': '''ast_Latn''', '''Awadhi''': '''awa_Deva''', '''Central Aymara''': '''ayr_Latn''', '''South Azerbaijani''': '''azb_Arab''', '''North Azerbaijani''': '''azj_Latn''', '''Bashkir''': '''bak_Cyrl''', '''Bambara''': '''bam_Latn''', '''Balinese''': '''ban_Latn''', '''Belarusian''': '''bel_Cyrl''', '''Bemba''': '''bem_Latn''', '''Bengali''': '''ben_Beng''', '''Bhojpuri''': '''bho_Deva''', '''Banjar Arabic''': '''bjn_Arab''', '''Banjar Latin''': '''bjn_Latn''', '''Standard Tibetan''': '''bod_Tibt''', '''Bosnian''': '''bos_Latn''', '''Buginese''': '''bug_Latn''', '''Bulgarian''': '''bul_Cyrl''', '''Catalan''': '''cat_Latn''', '''Cebuano''': '''ceb_Latn''', '''Czech''': '''ces_Latn''', '''Chokwe''': '''cjk_Latn''', '''Central Kurdish''': '''ckb_Arab''', '''Crimean Tatar''': '''crh_Latn''', '''Welsh''': '''cym_Latn''', '''Danish''': '''dan_Latn''', '''German''': '''deu_Latn''', '''Southwestern Dinka''': '''dik_Latn''', '''Dyula''': '''dyu_Latn''', '''Dzongkha''': '''dzo_Tibt''', '''Greek''': '''ell_Grek''', '''English''': '''eng_Latn''', '''Esperanto''': '''epo_Latn''', '''Estonian''': '''est_Latn''', '''Basque''': '''eus_Latn''', '''Ewe''': '''ewe_Latn''', '''Faroese''': '''fao_Latn''', '''Fijian''': '''fij_Latn''', '''Finnish''': '''fin_Latn''', '''Fon''': '''fon_Latn''', '''French''': '''fra_Latn''', '''Friulian''': '''fur_Latn''', '''Nigerian Fulfulde''': '''fuv_Latn''', '''Scottish Gaelic''': '''gla_Latn''', '''Irish''': '''gle_Latn''', '''Galician''': '''glg_Latn''', '''Guarani''': '''grn_Latn''', '''Gujarati''': '''guj_Gujr''', '''Haitian Creole''': '''hat_Latn''', '''Hausa''': '''hau_Latn''', '''Hebrew''': '''heb_Hebr''', '''Hindi''': '''hin_Deva''', '''Chhattisgarhi''': '''hne_Deva''', '''Croatian''': '''hrv_Latn''', '''Hungarian''': '''hun_Latn''', '''Armenian''': '''hye_Armn''', '''Igbo''': '''ibo_Latn''', '''Ilocano''': '''ilo_Latn''', '''Indonesian''': '''ind_Latn''', '''Icelandic''': '''isl_Latn''', '''Italian''': '''ita_Latn''', '''Javanese''': '''jav_Latn''', '''Japanese''': '''jpn_Jpan''', '''Kabyle''': '''kab_Latn''', '''Jingpho''': '''kac_Latn''', '''Kamba''': '''kam_Latn''', '''Kannada''': '''kan_Knda''', '''Kashmiri Arabic''': '''kas_Arab''', '''Kashmiri Devanagari''': '''kas_Deva''', '''Georgian''': '''kat_Geor''', '''Central Kanuri Arabic''': '''knc_Arab''', '''Central Kanuri Latin''': '''knc_Latn''', '''Kazakh''': '''kaz_Cyrl''', '''Kabiyè''': '''kbp_Latn''', '''Kabuverdianu''': '''kea_Latn''', '''Khmer''': '''khm_Khmr''', '''Kikuyu''': '''kik_Latn''', '''Kinyarwanda''': '''kin_Latn''', '''Kyrgyz''': '''kir_Cyrl''', '''Kimbundu''': '''kmb_Latn''', '''Northern Kurdish''': '''kmr_Latn''', '''Kikongo''': '''kon_Latn''', '''Korean''': '''kor_Hang''', '''Lao''': '''lao_Laoo''', '''Ligurian''': '''lij_Latn''', '''Limburgish''': '''lim_Latn''', '''Lingala''': '''lin_Latn''', '''Lithuanian''': '''lit_Latn''', '''Lombard''': '''lmo_Latn''', '''Latgalian''': '''ltg_Latn''', '''Luxembourgish''': '''ltz_Latn''', '''Luba-Kasai''': '''lua_Latn''', '''Ganda''': '''lug_Latn''', '''Luo''': '''luo_Latn''', '''Mizo''': '''lus_Latn''', '''Standard Latvian''': '''lvs_Latn''', '''Magahi''': '''mag_Deva''', '''Maithili''': '''mai_Deva''', '''Malayalam''': '''mal_Mlym''', '''Marathi''': '''mar_Deva''', '''Minangkabau Arabic ''': '''min_Arab''', '''Minangkabau Latin''': '''min_Latn''', '''Macedonian''': '''mkd_Cyrl''', '''Plateau Malagasy''': '''plt_Latn''', '''Maltese''': '''mlt_Latn''', '''Meitei Bengali''': '''mni_Beng''', '''Halh Mongolian''': '''khk_Cyrl''', '''Mossi''': '''mos_Latn''', '''Maori''': '''mri_Latn''', '''Burmese''': '''mya_Mymr''', '''Dutch''': '''nld_Latn''', '''Norwegian Nynorsk''': '''nno_Latn''', '''Norwegian Bokmål''': '''nob_Latn''', '''Nepali''': '''npi_Deva''', '''Northern Sotho''': '''nso_Latn''', '''Nuer''': '''nus_Latn''', '''Nyanja''': '''nya_Latn''', '''Occitan''': '''oci_Latn''', '''West Central Oromo''': '''gaz_Latn''', '''Odia''': '''ory_Orya''', '''Pangasinan''': '''pag_Latn''', '''Eastern Panjabi''': '''pan_Guru''', '''Papiamento''': '''pap_Latn''', '''Western Persian''': '''pes_Arab''', '''Polish''': '''pol_Latn''', '''Portuguese''': '''por_Latn''', '''Dari''': '''prs_Arab''', '''Southern Pashto''': '''pbt_Arab''', '''Ayacucho Quechua''': '''quy_Latn''', '''Romanian''': '''ron_Latn''', '''Rundi''': '''run_Latn''', '''Russian''': '''rus_Cyrl''', '''Sango''': '''sag_Latn''', '''Sanskrit''': '''san_Deva''', '''Santali''': '''sat_Olck''', '''Sicilian''': '''scn_Latn''', '''Shan''': '''shn_Mymr''', '''Sinhala''': '''sin_Sinh''', '''Slovak''': '''slk_Latn''', '''Slovenian''': '''slv_Latn''', '''Samoan''': '''smo_Latn''', '''Shona''': '''sna_Latn''', '''Sindhi''': '''snd_Arab''', '''Somali''': '''som_Latn''', '''Southern Sotho''': '''sot_Latn''', '''Spanish''': '''spa_Latn''', '''Tosk Albanian''': '''als_Latn''', '''Sardinian''': '''srd_Latn''', '''Serbian''': '''srp_Cyrl''', '''Swati''': '''ssw_Latn''', '''Sundanese''': '''sun_Latn''', '''Swedish''': '''swe_Latn''', '''Swahili''': '''swh_Latn''', '''Silesian''': '''szl_Latn''', '''Tamil''': '''tam_Taml''', '''Tatar''': '''tat_Cyrl''', '''Telugu''': '''tel_Telu''', '''Tajik''': '''tgk_Cyrl''', '''Tagalog''': '''tgl_Latn''', '''Thai''': '''tha_Thai''', '''Tigrinya''': '''tir_Ethi''', '''Tamasheq Latin''': '''taq_Latn''', '''Tamasheq Tifinagh''': '''taq_Tfng''', '''Tok Pisin''': '''tpi_Latn''', '''Tswana''': '''tsn_Latn''', '''Tsonga''': '''tso_Latn''', '''Turkmen''': '''tuk_Latn''', '''Tumbuka''': '''tum_Latn''', '''Turkish''': '''tur_Latn''', '''Twi''': '''twi_Latn''', '''Central Atlas Tamazight''': '''tzm_Tfng''', '''Uyghur''': '''uig_Arab''', '''Ukrainian''': '''ukr_Cyrl''', '''Umbundu''': '''umb_Latn''', '''Urdu''': '''urd_Arab''', '''Northern Uzbek''': '''uzn_Latn''', '''Venetian''': '''vec_Latn''', '''Vietnamese''': '''vie_Latn''', '''Waray''': '''war_Latn''', '''Wolof''': '''wol_Latn''', '''Xhosa''': '''xho_Latn''', '''Eastern Yiddish''': '''ydd_Hebr''', '''Yoruba''': '''yor_Latn''', '''Yue Chinese''': '''yue_Hant''', '''Chinese Simplified''': '''zho_Hans''', '''Chinese Traditional''': '''zho_Hant''', '''Standard Malay''': '''zsm_Latn''', '''Zulu''': '''zul_Latn''', } class a_ ( UpperCamelCase_ ): _snake_case = """facebook/nllb-200-distilled-600M""" _snake_case = ( """This is a tool that translates text from a language to another. It takes three inputs: `text`, which should """ """be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, """ """which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in """ """plain English, such as 'Romanian', or 'Albanian'. It returns the text translated in `tgt_lang`.""" ) _snake_case = """translator""" _snake_case = AutoTokenizer _snake_case = AutoModelForSeqaSeqLM _snake_case = LANGUAGE_CODES _snake_case = ["""text""", """text""", """text"""] _snake_case = ["""text"""] def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> int: """simple docstring""" if src_lang not in self.lang_to_code: raise ValueError(F"""{src_lang} is not a supported language.""") if tgt_lang not in self.lang_to_code: raise ValueError(F"""{tgt_lang} is not a supported language.""") __snake_case : List[Any] = self.lang_to_code[src_lang] __snake_case : Optional[Any] = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( __a , return_tensors='pt' , src_lang=__a , tgt_lang=__a) def SCREAMING_SNAKE_CASE__ (self , __a) -> Optional[int]: """simple docstring""" return self.model.generate(**__a) def SCREAMING_SNAKE_CASE__ (self , __a) -> Dict: """simple docstring""" return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=__a)
61
'''simple docstring''' from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class a_ : def __init__(self , __a = None) -> None: """simple docstring""" if components is None: __snake_case : List[str] = [] __snake_case : Optional[int] = list(__a) def __len__(self) -> int: """simple docstring""" return len(self.__components) def __str__(self) -> str: """simple docstring""" return "(" + ",".join(map(__a , self.__components)) + ")" def __add__(self , __a) -> Vector: """simple docstring""" __snake_case : Optional[Any] = len(self) if size == len(__a): __snake_case : Optional[int] = [self.__components[i] + other.component(__a) for i in range(__a)] return Vector(__a) else: raise Exception('must have the same size') def __sub__(self , __a) -> Vector: """simple docstring""" __snake_case : Optional[Any] = len(self) if size == len(__a): __snake_case : Optional[int] = [self.__components[i] - other.component(__a) for i in range(__a)] return Vector(__a) else: # error case raise Exception('must have the same size') @overload def __mul__(self , __a) -> Vector: """simple docstring""" ... @overload def __mul__(self , __a) -> float: """simple docstring""" ... def __mul__(self , __a) -> float | Vector: """simple docstring""" if isinstance(__a , (float, int)): __snake_case : str = [c * other for c in self.__components] return Vector(__a) elif isinstance(__a , __a) and len(self) == len(__a): __snake_case : List[Any] = len(self) __snake_case : Dict = [self.__components[i] * other.component(__a) for i in range(__a)] return sum(__a) else: # error case raise Exception('invalid operand!') def SCREAMING_SNAKE_CASE__ (self) -> Vector: """simple docstring""" return Vector(self.__components) def SCREAMING_SNAKE_CASE__ (self , __a) -> float: """simple docstring""" if isinstance(__a , __a) and -len(self.__components) <= i < len(self.__components): return self.__components[i] else: raise Exception('index out of range') def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> None: """simple docstring""" assert -len(self.__components) <= pos < len(self.__components) __snake_case : int = value def SCREAMING_SNAKE_CASE__ (self) -> float: """simple docstring""" if len(self.__components) == 0: raise Exception('Vector is empty') __snake_case : Tuple = [c**2 for c in self.__components] return math.sqrt(sum(__a)) def SCREAMING_SNAKE_CASE__ (self , __a , __a = False) -> float: """simple docstring""" __snake_case : Tuple = self * other __snake_case : Optional[int] = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den)) else: return math.acos(num / den) def _SCREAMING_SNAKE_CASE ( A : int ) -> Vector: """simple docstring""" assert isinstance(A , A ) return Vector([0] * dimension ) def _SCREAMING_SNAKE_CASE ( A : int , A : int ) -> Vector: """simple docstring""" assert isinstance(A , A ) and (isinstance(A , A )) __snake_case : Any = [0] * dimension __snake_case : int = 1 return Vector(A ) def _SCREAMING_SNAKE_CASE ( A : float , A : Vector , A : Vector ) -> Vector: """simple docstring""" assert ( isinstance(A , A ) and isinstance(A , A ) and (isinstance(A , (int, float) )) ) return x * scalar + y def _SCREAMING_SNAKE_CASE ( A : int , A : int , A : int ) -> Vector: """simple docstring""" random.seed(A ) __snake_case : List[Any] = [random.randint(A , A ) for _ in range(A )] return Vector(A ) class a_ : def __init__(self , __a , __a , __a) -> None: """simple docstring""" __snake_case : Union[str, Any] = matrix __snake_case : int = w __snake_case : str = h def __str__(self) -> str: """simple docstring""" __snake_case : Dict = '' for i in range(self.__height): ans += "|" for j in range(self.__width): if j < self.__width - 1: ans += str(self.__matrix[i][j]) + "," else: ans += str(self.__matrix[i][j]) + "|\n" return ans def __add__(self , __a) -> Matrix: """simple docstring""" if self.__width == other.width() and self.__height == other.height(): __snake_case : Tuple = [] for i in range(self.__height): __snake_case : List[Any] = [ self.__matrix[i][j] + other.component(__a , __a) for j in range(self.__width) ] matrix.append(__a) return Matrix(__a , self.__width , self.__height) else: raise Exception('matrix must have the same dimension!') def __sub__(self , __a) -> Matrix: """simple docstring""" if self.__width == other.width() and self.__height == other.height(): __snake_case : str = [] for i in range(self.__height): __snake_case : List[str] = [ self.__matrix[i][j] - other.component(__a , __a) for j in range(self.__width) ] matrix.append(__a) return Matrix(__a , self.__width , self.__height) else: raise Exception('matrices must have the same dimension!') @overload def __mul__(self , __a) -> Matrix: """simple docstring""" ... @overload def __mul__(self , __a) -> Vector: """simple docstring""" ... def __mul__(self , __a) -> Vector | Matrix: """simple docstring""" if isinstance(__a , __a): # matrix-vector if len(__a) == self.__width: __snake_case : Tuple = zero_vector(self.__height) for i in range(self.__height): __snake_case : Union[str, Any] = [ self.__matrix[i][j] * other.component(__a) for j in range(self.__width) ] ans.change_component(__a , sum(__a)) return ans else: raise Exception( 'vector must have the same size as the ' 'number of columns of the matrix!') elif isinstance(__a , (int, float)): # matrix-scalar __snake_case : str = [ [self.__matrix[i][j] * other for j in range(self.__width)] for i in range(self.__height) ] return Matrix(__a , self.__width , self.__height) return None def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" return self.__height def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" return self.__width def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> float: """simple docstring""" if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception('change_component: indices out of bounds') def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> None: """simple docstring""" if 0 <= x < self.__height and 0 <= y < self.__width: __snake_case : List[Any] = value else: raise Exception('change_component: indices out of bounds') def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> float: """simple docstring""" if self.__height != self.__width: raise Exception('Matrix is not square') __snake_case : List[Any] = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(__a)): __snake_case : Tuple = minor[i][:y] + minor[i][y + 1 :] return Matrix(__a , self.__width - 1 , self.__height - 1).determinant() def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> float: """simple docstring""" if self.__height != self.__width: raise Exception('Matrix is not square') if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(__a , __a) else: raise Exception('Indices out of bounds') def SCREAMING_SNAKE_CASE__ (self) -> float: """simple docstring""" if self.__height != self.__width: raise Exception('Matrix is not square') if self.__height < 1: raise Exception('Matrix has no element') elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: __snake_case : Any = [ self.__matrix[0][y] * self.cofactor(0 , __a) for y in range(self.__width) ] return sum(__a) def _SCREAMING_SNAKE_CASE ( A : int ) -> Matrix: """simple docstring""" __snake_case : list[list[float]] = [[0] * n for _ in range(A )] return Matrix(A , A , A ) def _SCREAMING_SNAKE_CASE ( A : int , A : int , A : int , A : int ) -> Matrix: """simple docstring""" random.seed(A ) __snake_case : list[list[float]] = [ [random.randint(A , A ) for _ in range(A )] for _ in range(A ) ] return Matrix(A , A , A )
61
1
'''simple docstring''' import sys __A = ( '''73167176531330624919225119674426574742355349194934''' '''96983520312774506326239578318016984801869478851843''' '''85861560789112949495459501737958331952853208805511''' '''12540698747158523863050715693290963295227443043557''' '''66896648950445244523161731856403098711121722383113''' '''62229893423380308135336276614282806444486645238749''' '''30358907296290491560440772390713810515859307960866''' '''70172427121883998797908792274921901699720888093776''' '''65727333001053367881220235421809751254540594752243''' '''52584907711670556013604839586446706324415722155397''' '''53697817977846174064955149290862569321978468622482''' '''83972241375657056057490261407972968652414535100474''' '''82166370484403199890008895243450658541227588666881''' '''16427171479924442928230863465674813919123162824586''' '''17866458359124566529476545682848912883142607690042''' '''24219022671055626321111109370544217506941658960408''' '''07198403850962455444362981230987879927244284909188''' '''84580156166097919133875499200524063689912560717606''' '''05886116467109405077541002256983155200055935729725''' '''71636269561882670428252483600823257530420752963450''' ) def _SCREAMING_SNAKE_CASE ( A : str = N ) -> int: """simple docstring""" __snake_case : str = -sys.maxsize - 1 for i in range(len(A ) - 12 ): __snake_case : str = 1 for j in range(13 ): product *= int(n[i + j] ) if product > largest_product: __snake_case : Union[str, Any] = product return largest_product if __name__ == "__main__": print(f'''{solution() = }''')
61
'''simple docstring''' import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification if is_tf_available(): from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification if is_flax_available(): from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification __A = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co __A = '''main''' # Default branch name __A = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2''' # One particular commit (not the top of `main`) __A = '''aaaaaaa''' # This commit does not exist, so we should 404. __A = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684''' # Sha-1 of config.json on the top of `main`, for checking purposes __A = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3''' @contextlib.contextmanager def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: """simple docstring""" print('Welcome!' ) yield print('Bye!' ) @contextlib.contextmanager def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]: """simple docstring""" print('Bonjour!' ) yield print('Au revoir!' ) class a_ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" assert transformers.__spec__ is not None assert importlib.util.find_spec('transformers') is not None class a_ ( unittest.TestCase ): @unittest.mock.patch('sys.stdout' , new_callable=io.StringIO) def SCREAMING_SNAKE_CASE__ (self , __a) -> int: """simple docstring""" with ContextManagers([]): print('Transformers are awesome!') # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue() , 'Transformers are awesome!\n') @unittest.mock.patch('sys.stdout' , new_callable=io.StringIO) def SCREAMING_SNAKE_CASE__ (self , __a) -> List[str]: """simple docstring""" with ContextManagers([context_en()]): print('Transformers are awesome!') # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue() , 'Welcome!\nTransformers are awesome!\nBye!\n') @unittest.mock.patch('sys.stdout' , new_callable=io.StringIO) def SCREAMING_SNAKE_CASE__ (self , __a) -> Tuple: """simple docstring""" with ContextManagers([context_fr(), context_en()]): print('Transformers are awesome!') # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue() , 'Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n') @require_torch def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" self.assertEqual(find_labels(__a) , ['labels']) self.assertEqual(find_labels(__a) , ['labels', 'next_sentence_label']) self.assertEqual(find_labels(__a) , ['start_positions', 'end_positions']) class a_ ( UpperCamelCase_ ): pass self.assertEqual(find_labels(__a) , ['labels']) @require_tf def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" self.assertEqual(find_labels(__a) , ['labels']) self.assertEqual(find_labels(__a) , ['labels', 'next_sentence_label']) self.assertEqual(find_labels(__a) , ['start_positions', 'end_positions']) class a_ ( UpperCamelCase_ ): pass self.assertEqual(find_labels(__a) , ['labels']) @require_flax def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" self.assertEqual(find_labels(__a) , []) self.assertEqual(find_labels(__a) , []) self.assertEqual(find_labels(__a) , []) class a_ ( UpperCamelCase_ ): pass self.assertEqual(find_labels(__a) , [])
61
1
'''simple docstring''' from __future__ import annotations import math def _SCREAMING_SNAKE_CASE ( A : int ) -> bool: """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(A ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True __A = [num for num in range(3, 1_0_0_0_0_1, 2) if not is_prime(num)] def _SCREAMING_SNAKE_CASE ( A : int ) -> list[int]: """simple docstring""" if not isinstance(A , A ): raise ValueError('n must be an integer' ) if n <= 0: raise ValueError('n must be >= 0' ) __snake_case : Dict = [] for num in range(len(A ) ): __snake_case : Dict = 0 while 2 * i * i <= odd_composites[num]: __snake_case : Any = odd_composites[num] - 2 * i * i if is_prime(A ): break i += 1 else: list_nums.append(odd_composites[num] ) if len(A ) == n: return list_nums return [] def _SCREAMING_SNAKE_CASE ( ) -> int: """simple docstring""" return compute_nums(1 )[0] if __name__ == "__main__": print(f'''{solution() = }''')
61
'''simple docstring''' # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A = {'''configuration_timm_backbone''': ['''TimmBackboneConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ['''TimmBackbone'''] if TYPE_CHECKING: from .configuration_timm_backbone import TimmBackboneConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timm_backbone import TimmBackbone else: import sys __A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
61
1
'''simple docstring''' import functools def _SCREAMING_SNAKE_CASE ( A : str , A : str ) -> int: """simple docstring""" __snake_case : int = len(A ) __snake_case : Optional[Any] = len(A ) @functools.cache def min_distance(A : int , A : int ) -> int: # if first word index is overflow - delete all from the second word if indexa >= len_worda: return len_worda - indexa # if second word index is overflow - delete all from the first word if indexa >= len_worda: return len_worda - indexa __snake_case : str = int(worda[indexa] != worda[indexa] ) # current letters not identical return min( 1 + min_distance(indexa + 1 , A ) , 1 + min_distance(A , indexa + 1 ) , diff + min_distance(indexa + 1 , indexa + 1 ) , ) return min_distance(0 , 0 ) if __name__ == "__main__": import doctest doctest.testmod()
61
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( A : int ) -> int: """simple docstring""" __snake_case : str = 1 for i in range(1 , num + 1 ): fact *= i return fact def _SCREAMING_SNAKE_CASE ( A : int ) -> int: """simple docstring""" __snake_case : Union[str, Any] = 0 while number > 0: __snake_case : Dict = number % 10 sum_of_digits += last_digit __snake_case : Union[str, Any] = number // 10 # Removing the last_digit from the given number return sum_of_digits def _SCREAMING_SNAKE_CASE ( A : int = 1_00 ) -> int: """simple docstring""" __snake_case : List[Any] = factorial(A ) __snake_case : Dict = split_and_add(A ) return result if __name__ == "__main__": print(solution(int(input('''Enter the Number: ''').strip())))
61
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 __A = logging.get_logger(__name__) __A = { '''facebook/deit-base-distilled-patch16-224''': ( '''https://huggingface.co/facebook/deit-base-patch16-224/resolve/main/config.json''' ), # See all DeiT models at https://huggingface.co/models?filter=deit } class a_ ( UpperCamelCase_ ): _snake_case = """deit""" def __init__(self , __a=7_6_8 , __a=1_2 , __a=1_2 , __a=3_0_7_2 , __a="gelu" , __a=0.0 , __a=0.0 , __a=0.02 , __a=1E-12 , __a=2_2_4 , __a=1_6 , __a=3 , __a=True , __a=1_6 , **__a , ) -> Union[str, Any]: """simple docstring""" super().__init__(**__a) __snake_case : Optional[int] = hidden_size __snake_case : int = num_hidden_layers __snake_case : List[Any] = num_attention_heads __snake_case : Optional[int] = intermediate_size __snake_case : Tuple = hidden_act __snake_case : Optional[int] = hidden_dropout_prob __snake_case : Tuple = attention_probs_dropout_prob __snake_case : Optional[int] = initializer_range __snake_case : List[Any] = layer_norm_eps __snake_case : List[Any] = image_size __snake_case : Optional[Any] = patch_size __snake_case : List[Any] = num_channels __snake_case : Tuple = qkv_bias __snake_case : Optional[int] = encoder_stride class a_ ( UpperCamelCase_ ): _snake_case = version.parse("""1.11""" ) @property def SCREAMING_SNAKE_CASE__ (self) -> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ]) @property def SCREAMING_SNAKE_CASE__ (self) -> float: """simple docstring""" return 1E-4
61
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor class a_ ( unittest.TestCase ): def __init__(self , __a , __a=7 , __a=3 , __a=1_8 , __a=3_0 , __a=4_0_0 , __a=True , __a=None , __a=True , __a=None , __a=True , __a=[0.48_145_466, 0.4_578_275, 0.40_821_073] , __a=[0.26_862_954, 0.26_130_258, 0.27_577_711] , __a=True , ) -> List[Any]: """simple docstring""" __snake_case : Tuple = size if size is not None else {'height': 2_2_4, 'width': 2_2_4} __snake_case : Any = crop_size if crop_size is not None else {'height': 1_8, 'width': 1_8} __snake_case : Optional[int] = parent __snake_case : Dict = batch_size __snake_case : str = num_channels __snake_case : Optional[Any] = image_size __snake_case : Optional[int] = min_resolution __snake_case : Tuple = max_resolution __snake_case : Optional[int] = do_resize __snake_case : Optional[int] = size __snake_case : Union[str, Any] = do_center_crop __snake_case : List[Any] = crop_size __snake_case : int = do_normalize __snake_case : Optional[Any] = image_mean __snake_case : str = image_std __snake_case : Optional[Any] = do_convert_rgb def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def SCREAMING_SNAKE_CASE__ (self , __a=False , __a=False , __a=False) -> List[str]: """simple docstring""" assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" if equal_resolution: __snake_case : Optional[int] = [] for i in range(self.batch_size): image_inputs.append( np.random.randint( 2_5_5 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta)) else: __snake_case : Dict = [] for i in range(self.batch_size): __snake_case ,__snake_case : Optional[Any] = np.random.choice(np.arange(self.min_resolution , self.max_resolution) , 2) image_inputs.append(np.random.randint(2_5_5 , size=(self.num_channels, width, height) , dtype=np.uinta)) if not numpify and not torchify: # PIL expects the channel dimension as last dimension __snake_case : int = [Image.fromarray(np.moveaxis(__a , 0 , -1)) for x in image_inputs] if torchify: __snake_case : List[Any] = [torch.from_numpy(__a) for x in image_inputs] return image_inputs @require_torch @require_vision class a_ ( UpperCamelCase_ , unittest.TestCase ): _snake_case = ChineseCLIPImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : Union[str, Any] = ChineseCLIPImageProcessingTester(self , do_center_crop=__a) @property def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : int = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(__a , 'do_resize')) self.assertTrue(hasattr(__a , 'size')) self.assertTrue(hasattr(__a , 'do_center_crop')) self.assertTrue(hasattr(__a , 'center_crop')) self.assertTrue(hasattr(__a , 'do_normalize')) self.assertTrue(hasattr(__a , 'image_mean')) self.assertTrue(hasattr(__a , 'image_std')) self.assertTrue(hasattr(__a , 'do_convert_rgb')) def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size , {'height': 2_2_4, 'width': 2_2_4}) self.assertEqual(image_processor.crop_size , {'height': 1_8, 'width': 1_8}) __snake_case : List[str] = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 , crop_size=8_4) self.assertEqual(image_processor.size , {'shortest_edge': 4_2}) self.assertEqual(image_processor.crop_size , {'height': 8_4, 'width': 8_4}) def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" __snake_case : List[Any] = self.image_processing_class(**self.image_processor_dict) # create random PIL images __snake_case : Optional[Any] = self.image_processor_tester.prepare_inputs(equal_resolution=__a) for image in image_inputs: self.assertIsInstance(__a , Image.Image) # Test not batched input __snake_case : 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __snake_case : List[Any] = image_processing(__a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" __snake_case : Union[str, Any] = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors __snake_case : Optional[int] = self.image_processor_tester.prepare_inputs(equal_resolution=__a , numpify=__a) for image in image_inputs: self.assertIsInstance(__a , np.ndarray) # Test not batched input __snake_case : List[Any] = image_processing(image_inputs[0] , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __snake_case : int = image_processing(__a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : Any = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors __snake_case : Tuple = self.image_processor_tester.prepare_inputs(equal_resolution=__a , torchify=__a) for image in image_inputs: self.assertIsInstance(__a , torch.Tensor) # Test not batched input __snake_case : Any = image_processing(image_inputs[0] , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __snake_case : Union[str, Any] = image_processing(__a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) @require_torch @require_vision class a_ ( UpperCamelCase_ , unittest.TestCase ): _snake_case = ChineseCLIPImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" __snake_case : Optional[Any] = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=__a) __snake_case : List[Any] = 3 @property def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : Any = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(__a , 'do_resize')) self.assertTrue(hasattr(__a , 'size')) self.assertTrue(hasattr(__a , 'do_center_crop')) self.assertTrue(hasattr(__a , 'center_crop')) self.assertTrue(hasattr(__a , 'do_normalize')) self.assertTrue(hasattr(__a , 'image_mean')) self.assertTrue(hasattr(__a , 'image_std')) self.assertTrue(hasattr(__a , 'do_convert_rgb')) def SCREAMING_SNAKE_CASE__ (self) -> Tuple: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : List[Any] = self.image_processing_class(**self.image_processor_dict) # create random PIL images __snake_case : Union[str, Any] = self.image_processor_tester.prepare_inputs(equal_resolution=__a) for image in image_inputs: self.assertIsInstance(__a , Image.Image) # Test not batched input __snake_case : Optional[int] = image_processing(image_inputs[0] , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __snake_case : Optional[int] = image_processing(__a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , )
61
1
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_squeezebert import SqueezeBertTokenizer __A = logging.get_logger(__name__) __A = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} __A = { '''vocab_file''': { '''squeezebert/squeezebert-uncased''': ( '''https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt''' ), '''squeezebert/squeezebert-mnli''': '''https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt''', '''squeezebert/squeezebert-mnli-headless''': ( '''https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''squeezebert/squeezebert-uncased''': ( '''https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/tokenizer.json''' ), '''squeezebert/squeezebert-mnli''': ( '''https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/tokenizer.json''' ), '''squeezebert/squeezebert-mnli-headless''': ( '''https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/tokenizer.json''' ), }, } __A = { '''squeezebert/squeezebert-uncased''': 5_1_2, '''squeezebert/squeezebert-mnli''': 5_1_2, '''squeezebert/squeezebert-mnli-headless''': 5_1_2, } __A = { '''squeezebert/squeezebert-uncased''': {'''do_lower_case''': True}, '''squeezebert/squeezebert-mnli''': {'''do_lower_case''': True}, '''squeezebert/squeezebert-mnli-headless''': {'''do_lower_case''': True}, } class a_ ( UpperCamelCase_ ): _snake_case = VOCAB_FILES_NAMES _snake_case = PRETRAINED_VOCAB_FILES_MAP _snake_case = PRETRAINED_INIT_CONFIGURATION _snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _snake_case = SqueezeBertTokenizer def __init__(self , __a=None , __a=None , __a=True , __a="[UNK]" , __a="[SEP]" , __a="[PAD]" , __a="[CLS]" , __a="[MASK]" , __a=True , __a=None , **__a , ) -> List[str]: """simple docstring""" super().__init__( __a , tokenizer_file=__a , do_lower_case=__a , unk_token=__a , sep_token=__a , pad_token=__a , cls_token=__a , mask_token=__a , tokenize_chinese_chars=__a , strip_accents=__a , **__a , ) __snake_case : List[Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__()) if ( normalizer_state.get('lowercase' , __a) != do_lower_case or normalizer_state.get('strip_accents' , __a) != strip_accents or normalizer_state.get('handle_chinese_chars' , __a) != tokenize_chinese_chars ): __snake_case : Optional[int] = getattr(__a , normalizer_state.pop('type')) __snake_case : List[str] = do_lower_case __snake_case : Union[str, Any] = strip_accents __snake_case : Union[str, Any] = tokenize_chinese_chars __snake_case : Union[str, Any] = normalizer_class(**__a) __snake_case : Tuple = do_lower_case def SCREAMING_SNAKE_CASE__ (self , __a , __a=None) -> Optional[int]: """simple docstring""" __snake_case : Tuple = [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 SCREAMING_SNAKE_CASE__ (self , __a , __a = None) -> List[int]: """simple docstring""" __snake_case : List[str] = [self.sep_token_id] __snake_case : Tuple = [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 SCREAMING_SNAKE_CASE__ (self , __a , __a = None) -> Tuple[str]: """simple docstring""" __snake_case : Optional[Any] = self._tokenizer.model.save(__a , name=__a) return tuple(__a)
61
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { '''sayakpaul/vit-msn-base''': '''https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json''', # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class a_ ( UpperCamelCase_ ): _snake_case = """vit_msn""" def __init__(self , __a=7_6_8 , __a=1_2 , __a=1_2 , __a=3_0_7_2 , __a="gelu" , __a=0.0 , __a=0.0 , __a=0.02 , __a=1E-06 , __a=2_2_4 , __a=1_6 , __a=3 , __a=True , **__a , ) -> Any: """simple docstring""" super().__init__(**__a) __snake_case : List[str] = hidden_size __snake_case : Optional[int] = num_hidden_layers __snake_case : Optional[Any] = num_attention_heads __snake_case : str = intermediate_size __snake_case : List[str] = hidden_act __snake_case : List[Any] = hidden_dropout_prob __snake_case : Tuple = attention_probs_dropout_prob __snake_case : List[str] = initializer_range __snake_case : Optional[int] = layer_norm_eps __snake_case : Dict = image_size __snake_case : int = patch_size __snake_case : Dict = num_channels __snake_case : Tuple = qkv_bias
61
1
'''simple docstring''' import sys from typing import Tuple import numpy as np import torch from PIL import Image from torch import nn from transformers.image_utils import PILImageResampling from utils import img_tensorize class a_ : def __init__(self , __a , __a=sys.maxsize) -> List[str]: """simple docstring""" __snake_case : Union[str, Any] = 'bilinear' __snake_case : Optional[int] = max_size __snake_case : str = short_edge_length def __call__(self , __a) -> int: """simple docstring""" __snake_case : str = [] for img in imgs: __snake_case ,__snake_case : str = img.shape[:2] # later: provide list and randomly choose index for resize __snake_case : Any = np.random.randint(self.short_edge_length[0] , self.short_edge_length[1] + 1) if size == 0: return img __snake_case : int = size * 1.0 / min(__a , __a) if h < w: __snake_case ,__snake_case : Optional[int] = size, scale * w else: __snake_case ,__snake_case : Tuple = scale * h, size if max(__a , __a) > self.max_size: __snake_case : int = self.max_size * 1.0 / max(__a , __a) __snake_case : List[Any] = newh * scale __snake_case : List[Any] = neww * scale __snake_case : Dict = int(neww + 0.5) __snake_case : Optional[Any] = int(newh + 0.5) if img.dtype == np.uinta: __snake_case : Tuple = Image.fromarray(__a) __snake_case : List[str] = pil_image.resize((neww, newh) , PILImageResampling.BILINEAR) __snake_case : Optional[int] = np.asarray(__a) else: __snake_case : List[str] = img.permute(2 , 0 , 1).unsqueeze(0) # 3, 0, 1) # hw(c) -> nchw __snake_case : Any = nn.functional.interpolate( __a , (newh, neww) , mode=self.interp_method , align_corners=__a).squeeze(0) img_augs.append(__a) return img_augs class a_ : def __init__(self , __a) -> int: """simple docstring""" __snake_case : Union[str, Any] = ResizeShortestEdge([cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST] , cfg.INPUT.MAX_SIZE_TEST) __snake_case : str = cfg.INPUT.FORMAT __snake_case : Any = cfg.SIZE_DIVISIBILITY __snake_case : Union[str, Any] = cfg.PAD_VALUE __snake_case : Union[str, Any] = cfg.INPUT.MAX_SIZE_TEST __snake_case : List[Any] = cfg.MODEL.DEVICE __snake_case : List[str] = torch.tensor(cfg.MODEL.PIXEL_STD).to(self.device).view(len(cfg.MODEL.PIXEL_STD) , 1 , 1) __snake_case : Union[str, Any] = torch.tensor(cfg.MODEL.PIXEL_MEAN).to(self.device).view(len(cfg.MODEL.PIXEL_STD) , 1 , 1) __snake_case : Optional[Any] = lambda __a: (x - self.pixel_mean) / self.pixel_std def SCREAMING_SNAKE_CASE__ (self , __a) -> Dict: """simple docstring""" __snake_case : int = tuple(max(__a) for s in zip(*[img.shape for img in images])) __snake_case : int = [im.shape[-2:] for im in images] __snake_case : Dict = [ nn.functional.pad( __a , [0, max_size[-1] - size[1], 0, max_size[-2] - size[0]] , value=self.pad_value , ) for size, im in zip(__a , __a) ] return torch.stack(__a), torch.tensor(__a) def __call__(self , __a , __a=False) -> Union[str, Any]: """simple docstring""" with torch.no_grad(): if not isinstance(__a , __a): __snake_case : List[Any] = [images] if single_image: assert len(__a) == 1 for i in range(len(__a)): if isinstance(images[i] , torch.Tensor): images.insert(__a , images.pop(__a).to(self.device).float()) elif not isinstance(images[i] , torch.Tensor): images.insert( __a , torch.as_tensor(img_tensorize(images.pop(__a) , input_format=self.input_format)) .to(self.device) .float() , ) # resize smallest edge __snake_case : List[Any] = torch.tensor([im.shape[:2] for im in images]) __snake_case : Optional[Any] = self.aug(__a) # transpose images and convert to torch tensors # images = [torch.as_tensor(i.astype("float32")).permute(2, 0, 1).to(self.device) for i in images] # now normalize before pad to avoid useless arithmetic __snake_case : int = [self.normalizer(__a) for x in images] # now pad them to do the following operations __snake_case ,__snake_case : Tuple = self.pad(__a) # Normalize if self.size_divisibility > 0: raise NotImplementedError() # pad __snake_case : Any = torch.true_divide(__a , __a) if single_image: return images[0], sizes[0], scales_yx[0] else: return images, sizes, scales_yx def _SCREAMING_SNAKE_CASE ( A : Any , A : List[Any] ) -> Union[str, Any]: """simple docstring""" boxes[:, 0::2] *= scale_yx[:, 1] boxes[:, 1::2] *= scale_yx[:, 0] return boxes def _SCREAMING_SNAKE_CASE ( A : Dict , A : Tuple[int, int] ) -> Optional[int]: """simple docstring""" assert torch.isfinite(A ).all(), "Box tensor contains infinite or NaN!" __snake_case ,__snake_case : Optional[int] = box_size tensor[:, 0].clamp_(min=0 , max=A ) tensor[:, 1].clamp_(min=0 , max=A ) tensor[:, 2].clamp_(min=0 , max=A ) tensor[:, 3].clamp_(min=0 , max=A )
61
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( A : float , A : list[float] ) -> float: """simple docstring""" if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) __snake_case : List[str] = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(A ) ) return round(A , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
61
1
'''simple docstring''' import torch from diffusers import EulerDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class a_ ( UpperCamelCase_ ): _snake_case = (EulerDiscreteScheduler,) _snake_case = 10 def SCREAMING_SNAKE_CASE__ (self , **__a) -> Any: """simple docstring""" __snake_case : Dict = { 'num_train_timesteps': 1_1_0_0, 'beta_start': 0.0_001, 'beta_end': 0.02, 'beta_schedule': 'linear', } config.update(**__a) return config def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]: """simple docstring""" for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=__a) def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001] , [0.0_002, 0.002, 0.02]): self.check_over_configs(beta_start=__a , beta_end=__a) def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=__a) def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__a) def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : Optional[Any] = self.scheduler_classes[0] __snake_case : Optional[Any] = self.get_scheduler_config() __snake_case : Any = scheduler_class(**__a) scheduler.set_timesteps(self.num_inference_steps) __snake_case : Union[str, Any] = torch.manual_seed(0) __snake_case : int = self.dummy_model() __snake_case : Optional[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma __snake_case : Optional[int] = sample.to(__a) for i, t in enumerate(scheduler.timesteps): __snake_case : Dict = scheduler.scale_model_input(__a , __a) __snake_case : Union[str, Any] = model(__a , __a) __snake_case : str = scheduler.step(__a , __a , __a , generator=__a) __snake_case : Union[str, Any] = output.prev_sample __snake_case : Optional[int] = torch.sum(torch.abs(__a)) __snake_case : List[Any] = torch.mean(torch.abs(__a)) assert abs(result_sum.item() - 10.0_807) < 1E-2 assert abs(result_mean.item() - 0.0_131) < 1E-3 def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : Tuple = self.scheduler_classes[0] __snake_case : Optional[int] = self.get_scheduler_config(prediction_type='v_prediction') __snake_case : List[Any] = scheduler_class(**__a) scheduler.set_timesteps(self.num_inference_steps) __snake_case : Tuple = torch.manual_seed(0) __snake_case : List[str] = self.dummy_model() __snake_case : Tuple = self.dummy_sample_deter * scheduler.init_noise_sigma __snake_case : Dict = sample.to(__a) for i, t in enumerate(scheduler.timesteps): __snake_case : int = scheduler.scale_model_input(__a , __a) __snake_case : Union[str, Any] = model(__a , __a) __snake_case : Tuple = scheduler.step(__a , __a , __a , generator=__a) __snake_case : Optional[int] = output.prev_sample __snake_case : Tuple = torch.sum(torch.abs(__a)) __snake_case : str = torch.mean(torch.abs(__a)) assert abs(result_sum.item() - 0.0_002) < 1E-2 assert abs(result_mean.item() - 2.2_676E-06) < 1E-3 def SCREAMING_SNAKE_CASE__ (self) -> Any: """simple docstring""" __snake_case : List[str] = self.scheduler_classes[0] __snake_case : Dict = self.get_scheduler_config() __snake_case : str = scheduler_class(**__a) scheduler.set_timesteps(self.num_inference_steps , device=__a) __snake_case : List[str] = torch.manual_seed(0) __snake_case : Union[str, Any] = self.dummy_model() __snake_case : Optional[int] = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() __snake_case : Any = sample.to(__a) for t in scheduler.timesteps: __snake_case : Optional[int] = scheduler.scale_model_input(__a , __a) __snake_case : Optional[int] = model(__a , __a) __snake_case : List[str] = scheduler.step(__a , __a , __a , generator=__a) __snake_case : int = output.prev_sample __snake_case : List[Any] = torch.sum(torch.abs(__a)) __snake_case : List[Any] = torch.mean(torch.abs(__a)) assert abs(result_sum.item() - 10.0_807) < 1E-2 assert abs(result_mean.item() - 0.0_131) < 1E-3 def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" __snake_case : Tuple = self.scheduler_classes[0] __snake_case : Tuple = self.get_scheduler_config() __snake_case : str = scheduler_class(**__a , use_karras_sigmas=__a) scheduler.set_timesteps(self.num_inference_steps , device=__a) __snake_case : str = torch.manual_seed(0) __snake_case : int = self.dummy_model() __snake_case : Optional[int] = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() __snake_case : Optional[int] = sample.to(__a) for t in scheduler.timesteps: __snake_case : Tuple = scheduler.scale_model_input(__a , __a) __snake_case : Tuple = model(__a , __a) __snake_case : Union[str, Any] = scheduler.step(__a , __a , __a , generator=__a) __snake_case : Optional[int] = output.prev_sample __snake_case : str = torch.sum(torch.abs(__a)) __snake_case : Dict = torch.mean(torch.abs(__a)) assert abs(result_sum.item() - 124.52_299_499_511_719) < 1E-2 assert abs(result_mean.item() - 0.16_213_932_633_399_963) < 1E-3
61
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __A = { '''configuration_distilbert''': [ '''DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DistilBertConfig''', '''DistilBertOnnxConfig''', ], '''tokenization_distilbert''': ['''DistilBertTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ['''DistilBertTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ '''DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''DistilBertForMaskedLM''', '''DistilBertForMultipleChoice''', '''DistilBertForQuestionAnswering''', '''DistilBertForSequenceClassification''', '''DistilBertForTokenClassification''', '''DistilBertModel''', '''DistilBertPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ '''TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFDistilBertForMaskedLM''', '''TFDistilBertForMultipleChoice''', '''TFDistilBertForQuestionAnswering''', '''TFDistilBertForSequenceClassification''', '''TFDistilBertForTokenClassification''', '''TFDistilBertMainLayer''', '''TFDistilBertModel''', '''TFDistilBertPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ '''FlaxDistilBertForMaskedLM''', '''FlaxDistilBertForMultipleChoice''', '''FlaxDistilBertForQuestionAnswering''', '''FlaxDistilBertForSequenceClassification''', '''FlaxDistilBertForTokenClassification''', '''FlaxDistilBertModel''', '''FlaxDistilBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_distilbert import ( DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DistilBertConfig, DistilBertOnnxConfig, ) from .tokenization_distilbert import DistilBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_distilbert_fast import DistilBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_distilbert import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, DistilBertPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertMainLayer, TFDistilBertModel, TFDistilBertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, FlaxDistilBertPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
61
1
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( A : list , A : int = 0 ) -> list: """simple docstring""" __snake_case : Dict = length or len(A ) __snake_case : Any = False for i in range(length - 1 ): if list_data[i] > list_data[i + 1]: __snake_case ,__snake_case : Tuple = list_data[i + 1], list_data[i] __snake_case : Optional[int] = True return list_data if not swapped else bubble_sort(A , length - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
61
'''simple docstring''' # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. __A = abspath(join(dirname(dirname(__file__)), '''src''')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='''ignore''', category=FutureWarning) def _SCREAMING_SNAKE_CASE ( A : Tuple ) -> str: """simple docstring""" from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(A ) def _SCREAMING_SNAKE_CASE ( A : int ) -> Optional[int]: """simple docstring""" from diffusers.utils.testing_utils import pytest_terminal_summary_main __snake_case : Any = terminalreporter.config.getoption('--make-reports' ) if make_reports: pytest_terminal_summary_main(A , id=A )
61
1
'''simple docstring''' import operator as op __A = '''scaler.pt''' __A = '''pytorch_model''' __A = '''random_states''' __A = '''optimizer''' __A = '''scheduler''' __A = '''pytorch_model.bin''' __A = '''pytorch_model.bin.index.json''' __A = '''model.safetensors''' __A = '''model.safetensors.index.json''' __A = '''1.10.2''' __A = '''py38''' __A = '''4.17.0''' __A = ['''ml.p3.16xlarge''', '''ml.p3dn.24xlarge''', '''ml.p4dn.24xlarge'''] __A = ['''FULL_SHARD''', '''SHARD_GRAD_OP''', '''NO_SHARD''', '''HYBRID_SHARD''', '''HYBRID_SHARD_ZERO2'''] __A = ['''TRANSFORMER_BASED_WRAP''', '''SIZE_BASED_WRAP''', '''NO_WRAP'''] __A = ['''BACKWARD_PRE''', '''BACKWARD_POST''', '''NO_PREFETCH'''] __A = ['''FULL_STATE_DICT''', '''LOCAL_STATE_DICT''', '''SHARDED_STATE_DICT'''] __A = '''2.0.1''' __A = ['''pdsh''', '''standard''', '''openmpi''', '''mvapich'''] __A = ['''default''', '''reduce-overhead''', '''max-autotune'''] __A = {'''>''': op.gt, '''>=''': op.ge, '''==''': op.eq, '''!=''': op.ne, '''<=''': op.le, '''<''': op.lt} # These are the args for `torch.distributed.launch` for pytorch < 1.9 __A = [ '''nnodes''', '''nproc_per_node''', '''rdzv_backend''', '''rdzv_endpoint''', '''rdzv_id''', '''rdzv_conf''', '''standalone''', '''max_restarts''', '''monitor_interval''', '''start_method''', '''role''', '''module''', '''m''', '''no_python''', '''run_path''', '''log_dir''', '''r''', '''redirects''', '''t''', '''tee''', '''node_rank''', '''master_addr''', '''master_port''', ] __A = ['''DEEPSPEED''', '''MULTI_GPU''', '''FSDP''', '''MEGATRON_LM'''] __A = ['''DEEPSPEED''', '''MULTI_XPU''', '''FSDP''']
61
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __A = { '''configuration_biogpt''': ['''BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BioGptConfig'''], '''tokenization_biogpt''': ['''BioGptTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ '''BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BioGptForCausalLM''', '''BioGptForTokenClassification''', '''BioGptForSequenceClassification''', '''BioGptModel''', '''BioGptPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
61
1
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { '''Salesforce/blip-vqa-base''': '''https://huggingface.co/Salesforce/blip-vqa-base/resolve/main/config.json''', '''Salesforce/blip-vqa-capfit-large''': ( '''https://huggingface.co/Salesforce/blip-vqa-base-capfit/resolve/main/config.json''' ), '''Salesforce/blip-image-captioning-base''': ( '''https://huggingface.co/Salesforce/blip-image-captioning-base/resolve/main/config.json''' ), '''Salesforce/blip-image-captioning-large''': ( '''https://huggingface.co/Salesforce/blip-image-captioning-large/resolve/main/config.json''' ), '''Salesforce/blip-itm-base-coco''': '''https://huggingface.co/Salesforce/blip-itm-base-coco/resolve/main/config.json''', '''Salesforce/blip-itm-large-coco''': '''https://huggingface.co/Salesforce/blip-itm-large-coco/resolve/main/config.json''', '''Salesforce/blip-itm-base-flikr''': '''https://huggingface.co/Salesforce/blip-itm-base-flikr/resolve/main/config.json''', '''Salesforce/blip-itm-large-flikr''': ( '''https://huggingface.co/Salesforce/blip-itm-large-flikr/resolve/main/config.json''' ), } class a_ ( UpperCamelCase_ ): _snake_case = """blip_text_model""" def __init__(self , __a=3_0_5_2_4 , __a=7_6_8 , __a=7_6_8 , __a=3_0_7_2 , __a=7_6_8 , __a=1_2 , __a=8 , __a=5_1_2 , __a="gelu" , __a=1E-12 , __a=0.0 , __a=0.0 , __a=0.02 , __a=3_0_5_2_2 , __a=2 , __a=0 , __a=1_0_2 , __a=True , __a=True , **__a , ) -> Tuple: """simple docstring""" super().__init__( pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , sep_token_id=__a , **__a , ) __snake_case : int = vocab_size __snake_case : Tuple = hidden_size __snake_case : Optional[Any] = encoder_hidden_size __snake_case : Tuple = intermediate_size __snake_case : Any = projection_dim __snake_case : Any = hidden_dropout_prob __snake_case : List[str] = num_hidden_layers __snake_case : Dict = num_attention_heads __snake_case : Any = max_position_embeddings __snake_case : Any = layer_norm_eps __snake_case : str = hidden_act __snake_case : str = initializer_range __snake_case : int = attention_probs_dropout_prob __snake_case : Any = is_decoder __snake_case : str = use_cache @classmethod def SCREAMING_SNAKE_CASE__ (cls , __a , **__a) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(__a) __snake_case ,__snake_case : List[str] = cls.get_config_dict(__a , **__a) # get the text config dict if we are loading from BlipConfig if config_dict.get('model_type') == "blip": __snake_case : str = config_dict['text_config'] if "model_type" in config_dict and hasattr(cls , 'model_type') and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""") return cls.from_dict(__a , **__a) class a_ ( UpperCamelCase_ ): _snake_case = """blip_vision_model""" def __init__(self , __a=7_6_8 , __a=3_0_7_2 , __a=5_1_2 , __a=1_2 , __a=1_2 , __a=3_8_4 , __a=1_6 , __a="gelu" , __a=1E-5 , __a=0.0 , __a=1E-10 , **__a , ) -> int: """simple docstring""" super().__init__(**__a) __snake_case : Tuple = hidden_size __snake_case : Any = intermediate_size __snake_case : int = projection_dim __snake_case : List[Any] = num_hidden_layers __snake_case : List[Any] = num_attention_heads __snake_case : List[str] = patch_size __snake_case : Any = image_size __snake_case : Optional[Any] = initializer_range __snake_case : List[str] = attention_dropout __snake_case : List[Any] = layer_norm_eps __snake_case : Optional[int] = hidden_act @classmethod def SCREAMING_SNAKE_CASE__ (cls , __a , **__a) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(__a) __snake_case ,__snake_case : Dict = cls.get_config_dict(__a , **__a) # get the vision config dict if we are loading from BlipConfig if config_dict.get('model_type') == "blip": __snake_case : Any = config_dict['vision_config'] if "model_type" in config_dict and hasattr(cls , 'model_type') and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""") return cls.from_dict(__a , **__a) class a_ ( UpperCamelCase_ ): _snake_case = """blip""" _snake_case = True def __init__(self , __a=None , __a=None , __a=5_1_2 , __a=2.6_592 , __a=2_5_6 , **__a , ) -> List[str]: """simple docstring""" super().__init__(**__a) if text_config is None: __snake_case : str = {} logger.info('`text_config` is `None`. Initializing the `BlipTextConfig` with default values.') if vision_config is None: __snake_case : Dict = {} logger.info('`vision_config` is `None`. Initializing the `BlipVisionConfig` with default values.') __snake_case : Union[str, Any] = BlipTextConfig(**__a) __snake_case : List[str] = BlipVisionConfig(**__a) __snake_case : List[Any] = self.vision_config.hidden_size __snake_case : Union[str, Any] = projection_dim __snake_case : Any = logit_scale_init_value __snake_case : Tuple = 1.0 __snake_case : Optional[int] = 0.02 __snake_case : Union[str, Any] = image_text_hidden_size @classmethod def SCREAMING_SNAKE_CASE__ (cls , __a , __a , **__a) -> Any: """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **__a) def SCREAMING_SNAKE_CASE__ (self) -> Any: """simple docstring""" __snake_case : Union[str, Any] = copy.deepcopy(self.__dict__) __snake_case : Tuple = self.text_config.to_dict() __snake_case : List[str] = self.vision_config.to_dict() __snake_case : str = self.__class__.model_type return output
61
'''simple docstring''' from packaging import version from .import_utils import is_accelerate_available if is_accelerate_available(): import accelerate def _SCREAMING_SNAKE_CASE ( A : Optional[Any] ) -> int: """simple docstring""" if not is_accelerate_available(): return method __snake_case : Optional[Any] = version.parse(accelerate.__version__ ).base_version if version.parse(A ) < version.parse('0.17.0' ): return method def wrapper(self : Optional[Any] , *A : Optional[Any] , **A : Optional[int] ): if hasattr(self , '_hf_hook' ) and hasattr(self._hf_hook , 'pre_forward' ): self._hf_hook.pre_forward(self ) return method(self , *A , **A ) return wrapper
61
1
'''simple docstring''' from io import BytesIO from typing import List, Union import requests from ..utils import add_end_docstrings, is_decord_available, is_torch_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_decord_available(): import numpy as np from decord import VideoReader if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING __A = logging.get_logger(__name__) @add_end_docstrings(UpperCamelCase_ ) class a_ ( UpperCamelCase_ ): def __init__(self , *__a , **__a) -> Optional[Any]: """simple docstring""" super().__init__(*__a , **__a) requires_backends(self , 'decord') self.check_model_type(__a) def SCREAMING_SNAKE_CASE__ (self , __a=None , __a=None , __a=None) -> Any: """simple docstring""" __snake_case : Tuple = {} if frame_sampling_rate is not None: __snake_case : Optional[int] = frame_sampling_rate if num_frames is not None: __snake_case : Dict = num_frames __snake_case : List[str] = {} if top_k is not None: __snake_case : Optional[int] = top_k return preprocess_params, {}, postprocess_params def __call__(self , __a , **__a) -> List[Any]: """simple docstring""" return super().__call__(__a , **__a) def SCREAMING_SNAKE_CASE__ (self , __a , __a=None , __a=1) -> str: """simple docstring""" if num_frames is None: __snake_case : Tuple = self.model.config.num_frames if video.startswith('http://') or video.startswith('https://'): __snake_case : Optional[Any] = BytesIO(requests.get(__a).content) __snake_case : Dict = VideoReader(__a) videoreader.seek(0) __snake_case : Dict = 0 __snake_case : Dict = num_frames * frame_sampling_rate - 1 __snake_case : List[str] = np.linspace(__a , __a , num=__a , dtype=np.intaa) __snake_case : str = videoreader.get_batch(__a).asnumpy() __snake_case : List[str] = list(__a) __snake_case : Tuple = self.image_processor(__a , return_tensors=self.framework) return model_inputs def SCREAMING_SNAKE_CASE__ (self , __a) -> Dict: """simple docstring""" __snake_case : Union[str, Any] = self.model(**__a) return model_outputs def SCREAMING_SNAKE_CASE__ (self , __a , __a=5) -> List[str]: """simple docstring""" if top_k > self.model.config.num_labels: __snake_case : Optional[int] = self.model.config.num_labels if self.framework == "pt": __snake_case : Dict = model_outputs.logits.softmax(-1)[0] __snake_case ,__snake_case : Union[str, Any] = probs.topk(__a) else: raise ValueError(F"""Unsupported framework: {self.framework}""") __snake_case : Tuple = scores.tolist() __snake_case : int = ids.tolist() return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(__a , __a)]
61
'''simple docstring''' import unittest from transformers import load_tool from transformers.utils import is_torch_available if is_torch_available(): import torch from transformers.testing_utils import require_torch from .test_tools_common import ToolTesterMixin @require_torch class a_ ( unittest.TestCase , UpperCamelCase_ ): def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" __snake_case : List[str] = load_tool('text-to-speech') self.tool.setup() def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]: """simple docstring""" torch.manual_seed(0) __snake_case : Dict = self.tool('hey') __snake_case : List[Any] = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485]) , )) def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" torch.manual_seed(0) __snake_case : Any = self.tool('hey') __snake_case : Any = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485]) , ))
61
1
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( A : str ) -> str: """simple docstring""" __snake_case : Any = '' for ch in key: if ch == " " or ch not in key_no_dups and ch.isalpha(): key_no_dups += ch return key_no_dups def _SCREAMING_SNAKE_CASE ( A : str ) -> dict[str, str]: """simple docstring""" __snake_case : Tuple = [chr(i + 65 ) for i in range(26 )] # Remove duplicate characters from key __snake_case : str = remove_duplicates(key.upper() ) __snake_case : Any = len(A ) # First fill cipher with key characters __snake_case : Tuple = {alphabet[i]: char for i, char in enumerate(A )} # Then map remaining characters in alphabet to # the alphabet from the beginning for i in range(len(A ) , 26 ): __snake_case : Any = alphabet[i - offset] # Ensure we are not mapping letters to letters previously mapped while char in key: offset -= 1 __snake_case : int = alphabet[i - offset] __snake_case : int = char return cipher_alphabet def _SCREAMING_SNAKE_CASE ( A : str , A : dict[str, str] ) -> str: """simple docstring""" return "".join(cipher_map.get(A , A ) for ch in message.upper() ) def _SCREAMING_SNAKE_CASE ( A : str , A : dict[str, str] ) -> str: """simple docstring""" __snake_case : List[Any] = {v: k for k, v in cipher_map.items()} return "".join(rev_cipher_map.get(A , A ) for ch in message.upper() ) def _SCREAMING_SNAKE_CASE ( ) -> None: """simple docstring""" __snake_case : Any = input('Enter message to encode or decode: ' ).strip() __snake_case : str = input('Enter keyword: ' ).strip() __snake_case : List[Any] = input('Encipher or decipher? E/D:' ).strip()[0].lower() try: __snake_case : Any = {'e': encipher, 'd': decipher}[option] except KeyError: raise KeyError('invalid input option' ) __snake_case : Optional[int] = create_cipher_map(A ) print(func(A , A ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
61
'''simple docstring''' import math class a_ : def __init__(self , __a=0) -> Any: # a graph with Node 0,1,...,N-1 """simple docstring""" __snake_case : List[str] = n __snake_case : Tuple = [ [math.inf for j in range(0 , __a)] for i in range(0 , __a) ] # adjacency matrix for weight __snake_case : Union[str, Any] = [ [math.inf for j in range(0 , __a)] for i in range(0 , __a) ] # dp[i][j] stores minimum distance from i to j def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Tuple: """simple docstring""" __snake_case : Union[str, Any] = w def SCREAMING_SNAKE_CASE__ (self) -> Tuple: """simple docstring""" for k in range(0 , self.n): for i in range(0 , self.n): for j in range(0 , self.n): __snake_case : List[Any] = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j]) def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> Optional[int]: """simple docstring""" return self.dp[u][v] if __name__ == "__main__": __A = Graph(5) graph.add_edge(0, 2, 9) graph.add_edge(0, 4, 1_0) graph.add_edge(1, 3, 5) graph.add_edge(2, 3, 7) graph.add_edge(3, 0, 1_0) graph.add_edge(3, 1, 2) graph.add_edge(3, 2, 1) graph.add_edge(3, 4, 6) graph.add_edge(4, 1, 3) graph.add_edge(4, 2, 4) graph.add_edge(4, 3, 9) graph.floyd_warshall() graph.show_min(1, 4) graph.show_min(0, 3)
61
1
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, 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_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class a_ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): _snake_case = StableDiffusionXLImgaImgPipeline _snake_case = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""} _snake_case = PipelineTesterMixin.required_optional_params - {"""latents"""} _snake_case = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS _snake_case = IMAGE_TO_IMAGE_IMAGE_PARAMS _snake_case = IMAGE_TO_IMAGE_IMAGE_PARAMS def SCREAMING_SNAKE_CASE__ (self) -> Any: """simple docstring""" torch.manual_seed(0) __snake_case : int = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , attention_head_dim=(2, 4) , use_linear_projection=__a , addition_embed_type='text_time' , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=8_0 , cross_attention_dim=6_4 , ) __snake_case : Any = EulerDiscreteScheduler( beta_start=0.00_085 , beta_end=0.012 , steps_offset=1 , beta_schedule='scaled_linear' , timestep_spacing='leading' , ) torch.manual_seed(0) __snake_case : List[str] = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=1_2_8 , ) torch.manual_seed(0) __snake_case : str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , hidden_act='gelu' , projection_dim=3_2 , ) __snake_case : Any = CLIPTextModel(__a) __snake_case : List[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' , local_files_only=__a) __snake_case : int = CLIPTextModelWithProjection(__a) __snake_case : Tuple = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' , local_files_only=__a) __snake_case : Union[str, Any] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'text_encoder_2': text_encoder_a, 'tokenizer_2': tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def SCREAMING_SNAKE_CASE__ (self , __a , __a=0) -> Tuple: """simple docstring""" __snake_case : Optional[Any] = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(__a)).to(__a) __snake_case : Optional[int] = image / 2 + 0.5 if str(__a).startswith('mps'): __snake_case : Dict = torch.manual_seed(__a) else: __snake_case : Dict = torch.Generator(device=__a).manual_seed(__a) __snake_case : List[Any] = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 5.0, 'output_type': 'numpy', 'strength': 0.75, } return inputs def SCREAMING_SNAKE_CASE__ (self) -> Any: """simple docstring""" __snake_case : str = 'cpu' # ensure determinism for the device-dependent torch.Generator __snake_case : Optional[Any] = self.get_dummy_components() __snake_case : int = StableDiffusionXLImgaImgPipeline(**__a) __snake_case : Optional[int] = sd_pipe.to(__a) sd_pipe.set_progress_bar_config(disable=__a) __snake_case : List[Any] = self.get_dummy_inputs(__a) __snake_case : List[Any] = sd_pipe(**__a).images __snake_case : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) __snake_case : Optional[int] = np.array([0.4_656, 0.4_840, 0.4_439, 0.6_698, 0.5_574, 0.4_524, 0.5_799, 0.5_943, 0.5_165]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2 def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" super().test_attention_slicing_forward_pass(expected_max_diff=3E-3) def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3) def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self) -> str: """simple docstring""" __snake_case : Optional[int] = self.get_dummy_components() __snake_case : Tuple = StableDiffusionXLImgaImgPipeline(**__a) __snake_case : Optional[int] = sd_pipe.to(__a) __snake_case : Optional[Any] = sd_pipe.to(__a) sd_pipe.set_progress_bar_config(disable=__a) # forward without prompt embeds __snake_case : Union[str, Any] = self.get_dummy_inputs(__a) __snake_case : int = 3 * ['this is a negative prompt'] __snake_case : Optional[Any] = negative_prompt __snake_case : str = 3 * [inputs['prompt']] __snake_case : Dict = sd_pipe(**__a) __snake_case : Union[str, Any] = output.images[0, -3:, -3:, -1] # forward with prompt embeds __snake_case : int = self.get_dummy_inputs(__a) __snake_case : Tuple = 3 * ['this is a negative prompt'] __snake_case : Union[str, Any] = 3 * [inputs.pop('prompt')] ( ( __snake_case ) ,( __snake_case ) ,( __snake_case ) ,( __snake_case ) , ) : Tuple = sd_pipe.encode_prompt(__a , negative_prompt=__a) __snake_case : str = sd_pipe( **__a , prompt_embeds=__a , negative_prompt_embeds=__a , pooled_prompt_embeds=__a , negative_pooled_prompt_embeds=__a , ) __snake_case : str = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()).max() < 1E-4 @slow @require_torch_gpu class a_ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ (self , __a , __a="cpu" , __a=torch.floataa , __a=0) -> Any: """simple docstring""" __snake_case : int = torch.Generator(device=__a).manual_seed(__a) __snake_case : Tuple = np.random.RandomState(__a).standard_normal((1, 4, 6_4, 6_4)) __snake_case : Tuple = torch.from_numpy(__a).to(device=__a , dtype=__a) __snake_case : Tuple = { 'prompt': 'a photograph of an astronaut riding a horse', 'latents': latents, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ (self) -> Tuple: """simple docstring""" __snake_case : Optional[int] = DiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-base') pipe.to(__a) pipe.set_progress_bar_config(disable=__a) __snake_case : Tuple = self.get_inputs(__a) __snake_case : Any = pipe(**__a).images __snake_case : Any = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_1_2, 5_1_2, 3) __snake_case : Optional[int] = np.array([0.49_493, 0.47_896, 0.40_798, 0.54_214, 0.53_212, 0.48_202, 0.47_656, 0.46_329, 0.48_506]) assert np.abs(image_slice - expected_slice).max() < 7E-3
61
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL __A = logging.get_logger(__name__) class a_ ( UpperCamelCase_ ): _snake_case = ["""pixel_values"""] def __init__(self , __a = True , __a = None , __a = None , __a = PILImageResampling.BILINEAR , __a = True , __a = 1 / 2_5_5 , __a = True , __a = None , __a = None , **__a , ) -> None: """simple docstring""" super().__init__(**__a) __snake_case : Tuple = size if size is not None else {'shortest_edge': 3_8_4} __snake_case : List[Any] = get_size_dict(__a , default_to_square=__a) __snake_case : int = do_resize __snake_case : List[str] = size # Default value set here for backwards compatibility where the value in config is None __snake_case : Any = crop_pct if crop_pct is not None else 2_2_4 / 2_5_6 __snake_case : Tuple = resample __snake_case : Dict = do_rescale __snake_case : Any = rescale_factor __snake_case : str = do_normalize __snake_case : Union[str, Any] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __snake_case : Dict = image_std if image_std is not None else IMAGENET_STANDARD_STD def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a , __a = PILImageResampling.BICUBIC , __a = None , **__a , ) -> np.ndarray: """simple docstring""" __snake_case : Dict = get_size_dict(__a , default_to_square=__a) if "shortest_edge" not in size: raise ValueError(F"""Size dictionary must contain 'shortest_edge' key. Got {size.keys()}""") __snake_case : List[str] = size['shortest_edge'] if shortest_edge < 3_8_4: # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct __snake_case : Any = int(shortest_edge / crop_pct) __snake_case : Any = get_resize_output_image_size(__a , size=__a , default_to_square=__a) __snake_case : int = resize(image=__a , size=__a , resample=__a , data_format=__a , **__a) # then crop to (shortest_edge, shortest_edge) return center_crop(image=__a , size=(shortest_edge, shortest_edge) , data_format=__a , **__a) else: # warping (no cropping) when evaluated at 384 or larger return resize( __a , size=(shortest_edge, shortest_edge) , resample=__a , data_format=__a , **__a) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a = None , **__a , ) -> Any: """simple docstring""" return rescale(__a , scale=__a , data_format=__a , **__a) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a , __a = None , **__a , ) -> np.ndarray: """simple docstring""" return normalize(__a , mean=__a , std=__a , data_format=__a , **__a) def SCREAMING_SNAKE_CASE__ (self , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = ChannelDimension.FIRST , **__a , ) -> PIL.Image.Image: """simple docstring""" __snake_case : Optional[int] = do_resize if do_resize is not None else self.do_resize __snake_case : Dict = crop_pct if crop_pct is not None else self.crop_pct __snake_case : Tuple = resample if resample is not None else self.resample __snake_case : Any = do_rescale if do_rescale is not None else self.do_rescale __snake_case : Any = rescale_factor if rescale_factor is not None else self.rescale_factor __snake_case : Union[str, Any] = do_normalize if do_normalize is not None else self.do_normalize __snake_case : Optional[int] = image_mean if image_mean is not None else self.image_mean __snake_case : Optional[Any] = image_std if image_std is not None else self.image_std __snake_case : List[str] = size if size is not None else self.size __snake_case : Any = get_size_dict(__a , default_to_square=__a) __snake_case : Dict = make_list_of_images(__a) if not valid_images(__a): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.') if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.') if do_resize and size["shortest_edge"] < 3_8_4 and crop_pct is None: raise ValueError('crop_pct must be specified if size < 384.') if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.') if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.') # All transformations expect numpy arrays. __snake_case : Tuple = [to_numpy_array(__a) for image in images] if do_resize: __snake_case : Optional[int] = [self.resize(image=__a , size=__a , crop_pct=__a , resample=__a) for image in images] if do_rescale: __snake_case : Optional[int] = [self.rescale(image=__a , scale=__a) for image in images] if do_normalize: __snake_case : Any = [self.normalize(image=__a , mean=__a , std=__a) for image in images] __snake_case : Dict = [to_channel_dimension_format(__a , __a) for image in images] __snake_case : Union[str, Any] = {'pixel_values': images} return BatchFeature(data=__a , tensor_type=__a)
61
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { '''vinvino02/glpn-kitti''': '''https://huggingface.co/vinvino02/glpn-kitti/resolve/main/config.json''', # See all GLPN models at https://huggingface.co/models?filter=glpn } class a_ ( UpperCamelCase_ ): _snake_case = """glpn""" def __init__(self , __a=3 , __a=4 , __a=[2, 2, 2, 2] , __a=[8, 4, 2, 1] , __a=[3_2, 6_4, 1_6_0, 2_5_6] , __a=[7, 3, 3, 3] , __a=[4, 2, 2, 2] , __a=[1, 2, 5, 8] , __a=[4, 4, 4, 4] , __a="gelu" , __a=0.0 , __a=0.0 , __a=0.02 , __a=0.1 , __a=1E-6 , __a=6_4 , __a=1_0 , __a=-1 , **__a , ) -> List[str]: """simple docstring""" super().__init__(**__a) __snake_case : int = num_channels __snake_case : int = num_encoder_blocks __snake_case : Union[str, Any] = depths __snake_case : Optional[Any] = sr_ratios __snake_case : Optional[Any] = hidden_sizes __snake_case : Tuple = patch_sizes __snake_case : str = strides __snake_case : List[str] = mlp_ratios __snake_case : Tuple = num_attention_heads __snake_case : Optional[int] = hidden_act __snake_case : int = hidden_dropout_prob __snake_case : Union[str, Any] = attention_probs_dropout_prob __snake_case : int = initializer_range __snake_case : Optional[Any] = drop_path_rate __snake_case : Optional[int] = layer_norm_eps __snake_case : List[Any] = decoder_hidden_size __snake_case : Tuple = max_depth __snake_case : Optional[int] = head_in_index
61
'''simple docstring''' from functools import lru_cache @lru_cache def _SCREAMING_SNAKE_CASE ( A : int ) -> int: """simple docstring""" if num < 0: raise ValueError('Number should not be negative.' ) return 1 if num in (0, 1) else num * factorial(num - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
61
1
'''simple docstring''' from math import pi, sqrt, tan def _SCREAMING_SNAKE_CASE ( A : float ) -> float: """simple docstring""" if side_length < 0: raise ValueError('surface_area_cube() only accepts non-negative values' ) return 6 * side_length**2 def _SCREAMING_SNAKE_CASE ( A : float , A : float , A : float ) -> float: """simple docstring""" if length < 0 or breadth < 0 or height < 0: raise ValueError('surface_area_cuboid() only accepts non-negative values' ) return 2 * ((length * breadth) + (breadth * height) + (length * height)) def _SCREAMING_SNAKE_CASE ( A : float ) -> float: """simple docstring""" if radius < 0: raise ValueError('surface_area_sphere() only accepts non-negative values' ) return 4 * pi * radius**2 def _SCREAMING_SNAKE_CASE ( A : float ) -> float: """simple docstring""" if radius < 0: raise ValueError('surface_area_hemisphere() only accepts non-negative values' ) return 3 * pi * radius**2 def _SCREAMING_SNAKE_CASE ( A : float , A : float ) -> float: """simple docstring""" if radius < 0 or height < 0: raise ValueError('surface_area_cone() only accepts non-negative values' ) return pi * radius * (radius + (height**2 + radius**2) ** 0.5) def _SCREAMING_SNAKE_CASE ( A : float , A : float , A : float ) -> float: """simple docstring""" if radius_a < 0 or radius_a < 0 or height < 0: raise ValueError( 'surface_area_conical_frustum() only accepts non-negative values' ) __snake_case : Tuple = (height**2 + (radius_a - radius_a) ** 2) ** 0.5 return pi * ((slant_height * (radius_a + radius_a)) + radius_a**2 + radius_a**2) def _SCREAMING_SNAKE_CASE ( A : float , A : float ) -> float: """simple docstring""" if radius < 0 or height < 0: raise ValueError('surface_area_cylinder() only accepts non-negative values' ) return 2 * pi * radius * (height + radius) def _SCREAMING_SNAKE_CASE ( A : float , A : float ) -> float: """simple docstring""" if torus_radius < 0 or tube_radius < 0: raise ValueError('surface_area_torus() only accepts non-negative values' ) if torus_radius < tube_radius: raise ValueError( 'surface_area_torus() does not support spindle or self intersecting tori' ) return 4 * pow(A , 2 ) * torus_radius * tube_radius def _SCREAMING_SNAKE_CASE ( A : float , A : float ) -> float: """simple docstring""" if length < 0 or width < 0: raise ValueError('area_rectangle() only accepts non-negative values' ) return length * width def _SCREAMING_SNAKE_CASE ( A : float ) -> float: """simple docstring""" if side_length < 0: raise ValueError('area_square() only accepts non-negative values' ) return side_length**2 def _SCREAMING_SNAKE_CASE ( A : float , A : float ) -> float: """simple docstring""" if base < 0 or height < 0: raise ValueError('area_triangle() only accepts non-negative values' ) return (base * height) / 2 def _SCREAMING_SNAKE_CASE ( A : float , A : float , A : float ) -> float: """simple docstring""" if sidea < 0 or sidea < 0 or sidea < 0: raise ValueError('area_triangle_three_sides() only accepts non-negative values' ) elif sidea + sidea < sidea or sidea + sidea < sidea or sidea + sidea < sidea: raise ValueError('Given three sides do not form a triangle' ) __snake_case : List[Any] = (sidea + sidea + sidea) / 2 __snake_case : int = sqrt( semi_perimeter * (semi_perimeter - sidea) * (semi_perimeter - sidea) * (semi_perimeter - sidea) ) return area def _SCREAMING_SNAKE_CASE ( A : float , A : float ) -> float: """simple docstring""" if base < 0 or height < 0: raise ValueError('area_parallelogram() only accepts non-negative values' ) return base * height def _SCREAMING_SNAKE_CASE ( A : float , A : float , A : float ) -> float: """simple docstring""" if basea < 0 or basea < 0 or height < 0: raise ValueError('area_trapezium() only accepts non-negative values' ) return 1 / 2 * (basea + basea) * height def _SCREAMING_SNAKE_CASE ( A : float ) -> float: """simple docstring""" if radius < 0: raise ValueError('area_circle() only accepts non-negative values' ) return pi * radius**2 def _SCREAMING_SNAKE_CASE ( A : float , A : float ) -> float: """simple docstring""" if radius_x < 0 or radius_y < 0: raise ValueError('area_ellipse() only accepts non-negative values' ) return pi * radius_x * radius_y def _SCREAMING_SNAKE_CASE ( A : float , A : float ) -> float: """simple docstring""" if diagonal_a < 0 or diagonal_a < 0: raise ValueError('area_rhombus() only accepts non-negative values' ) return 1 / 2 * diagonal_a * diagonal_a def _SCREAMING_SNAKE_CASE ( A : int , A : float ) -> float: """simple docstring""" if not isinstance(A , A ) or sides < 3: raise ValueError( 'area_reg_polygon() only accepts integers greater than or \ equal to three as number of sides' ) elif length < 0: raise ValueError( 'area_reg_polygon() only accepts non-negative values as \ length of a side' ) return (sides * length**2) / (4 * tan(pi / sides )) return (sides * length**2) / (4 * tan(pi / sides )) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) # verbose so we can see methods missing tests print('''[DEMO] Areas of various geometric shapes: \n''') print(f'''Rectangle: {area_rectangle(1_0, 2_0) = }''') print(f'''Square: {area_square(1_0) = }''') print(f'''Triangle: {area_triangle(1_0, 1_0) = }''') print(f'''Triangle: {area_triangle_three_sides(5, 1_2, 1_3) = }''') print(f'''Parallelogram: {area_parallelogram(1_0, 2_0) = }''') print(f'''Rhombus: {area_rhombus(1_0, 2_0) = }''') print(f'''Trapezium: {area_trapezium(1_0, 2_0, 3_0) = }''') print(f'''Circle: {area_circle(2_0) = }''') print(f'''Ellipse: {area_ellipse(1_0, 2_0) = }''') print('''\nSurface Areas of various geometric shapes: \n''') print(f'''Cube: {surface_area_cube(2_0) = }''') print(f'''Cuboid: {surface_area_cuboid(1_0, 2_0, 3_0) = }''') print(f'''Sphere: {surface_area_sphere(2_0) = }''') print(f'''Hemisphere: {surface_area_hemisphere(2_0) = }''') print(f'''Cone: {surface_area_cone(1_0, 2_0) = }''') print(f'''Conical Frustum: {surface_area_conical_frustum(1_0, 2_0, 3_0) = }''') print(f'''Cylinder: {surface_area_cylinder(1_0, 2_0) = }''') print(f'''Torus: {surface_area_torus(2_0, 1_0) = }''') print(f'''Equilateral Triangle: {area_reg_polygon(3, 1_0) = }''') print(f'''Square: {area_reg_polygon(4, 1_0) = }''') print(f'''Reqular Pentagon: {area_reg_polygon(5, 1_0) = }''')
61
'''simple docstring''' import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class a_ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): _snake_case = VQModel _snake_case = """sample""" @property def SCREAMING_SNAKE_CASE__ (self , __a=(3_2, 3_2)) -> str: """simple docstring""" __snake_case : Dict = 4 __snake_case : Optional[int] = 3 __snake_case : str = floats_tensor((batch_size, num_channels) + sizes).to(__a) return {"sample": image} @property def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" return (3, 3_2, 3_2) @property def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" return (3, 3_2, 3_2) def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" __snake_case : Optional[Any] = { 'block_out_channels': [3_2, 6_4], 'in_channels': 3, 'out_channels': 3, 'down_block_types': ['DownEncoderBlock2D', 'DownEncoderBlock2D'], 'up_block_types': ['UpDecoderBlock2D', 'UpDecoderBlock2D'], 'latent_channels': 3, } __snake_case : List[Any] = self.dummy_input return init_dict, inputs_dict def SCREAMING_SNAKE_CASE__ (self) -> Any: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" __snake_case ,__snake_case : List[Any] = VQModel.from_pretrained('fusing/vqgan-dummy' , output_loading_info=__a) self.assertIsNotNone(__a) self.assertEqual(len(loading_info['missing_keys']) , 0) model.to(__a) __snake_case : Any = model(**self.dummy_input) assert image is not None, "Make sure output is not None" def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" __snake_case : Union[str, Any] = VQModel.from_pretrained('fusing/vqgan-dummy') model.to(__a).eval() torch.manual_seed(0) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0) __snake_case : Tuple = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size) __snake_case : Optional[int] = image.to(__a) with torch.no_grad(): __snake_case : List[Any] = model(__a).sample __snake_case : int = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off __snake_case : int = torch.tensor([-0.0_153, -0.4_044, -0.1_880, -0.5_161, -0.2_418, -0.4_072, -0.1_612, -0.0_633, -0.0_143]) # fmt: on self.assertTrue(torch.allclose(__a , __a , atol=1E-3))
61
1
'''simple docstring''' from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup __A = '''https://www.indeed.co.in/jobs?q=mobile+app+development&l=''' def _SCREAMING_SNAKE_CASE ( A : str = "mumbai" ) -> Generator[tuple[str, str], None, None]: """simple docstring""" __snake_case : Any = BeautifulSoup(requests.get(url + location ).content , 'html.parser' ) # This attribute finds out all the specifics listed in a job for job in soup.find_all('div' , attrs={'data-tn-component': 'organicJob'} ): __snake_case : int = job.find('a' , attrs={'data-tn-element': 'jobTitle'} ).text.strip() __snake_case : List[str] = job.find('span' , {'class': 'company'} ).text.strip() yield job_title, company_name if __name__ == "__main__": for i, job in enumerate(fetch_jobs('''Bangalore'''), 1): print(f'''Job {i:>2} is {job[0]} at {job[1]}''')
61
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process __A = logging.getLogger(__name__) @dataclass class a_ : _snake_case = field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} ) _snake_case = field( default=UpperCamelCase_ , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) _snake_case = field( default="""NER""" , metadata={"""help""": """Task type to fine tune in training (e.g. NER, POS, etc)"""} ) _snake_case = field( default=UpperCamelCase_ , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} ) _snake_case = field(default=UpperCamelCase_ , metadata={"""help""": """Set this flag to use fast tokenization."""} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. _snake_case = field( default=UpperCamelCase_ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) @dataclass class a_ : _snake_case = field( metadata={"""help""": """The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."""} ) _snake_case = field( default=UpperCamelCase_ , metadata={"""help""": """Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."""} , ) _snake_case = field( default=128 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) _snake_case = field( default=UpperCamelCase_ , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} ) def _SCREAMING_SNAKE_CASE ( ) -> int: """simple docstring""" # 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. __snake_case : List[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. __snake_case ,__snake_case ,__snake_case : List[str] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __snake_case ,__snake_case ,__snake_case : int = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. Use""" ' --overwrite_output_dir to overcome.' ) __snake_case : List[str] = import_module('tasks' ) try: __snake_case : Any = getattr(A , model_args.task_type ) __snake_case : TokenClassificationTask = token_classification_task_clazz() except AttributeError: raise ValueError( F"""Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. """ F"""Available tasks classes are: {TokenClassificationTask.__subclasses__()}""" ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( 'Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('Training/evaluation parameters %s' , A ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task __snake_case : Optional[Any] = token_classification_task.get_labels(data_args.labels ) __snake_case : Dict[int, str] = dict(enumerate(A ) ) __snake_case : Optional[Any] = len(A ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __snake_case : Any = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=A , idalabel=A , labelaid={label: i for i, label in enumerate(A )} , cache_dir=model_args.cache_dir , ) __snake_case : List[str] = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast , ) __snake_case : Optional[int] = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=A , cache_dir=model_args.cache_dir , ) # Get datasets __snake_case : List[Any] = ( TokenClassificationDataset( token_classification_task=A , data_dir=data_args.data_dir , tokenizer=A , labels=A , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) __snake_case : int = ( TokenClassificationDataset( token_classification_task=A , data_dir=data_args.data_dir , tokenizer=A , labels=A , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def align_predictions(A : np.ndarray , A : np.ndarray ) -> Tuple[List[int], List[int]]: __snake_case : str = np.argmax(A , axis=2 ) __snake_case ,__snake_case : int = preds.shape __snake_case : Dict = [[] for _ in range(A )] __snake_case : Union[str, Any] = [[] for _ in range(A )] for i in range(A ): for j in range(A ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(A : EvalPrediction ) -> Dict: __snake_case ,__snake_case : Any = align_predictions(p.predictions , p.label_ids ) return { "accuracy_score": accuracy_score(A , A ), "precision": precision_score(A , A ), "recall": recall_score(A , A ), "f1": fa_score(A , A ), } # Data collator __snake_case : Optional[int] = DataCollatorWithPadding(A , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer __snake_case : Optional[Any] = Trainer( model=A , args=A , train_dataset=A , eval_dataset=A , compute_metrics=A , data_collator=A , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation __snake_case : List[Any] = {} if training_args.do_eval: logger.info('*** Evaluate ***' ) __snake_case : List[str] = trainer.evaluate() __snake_case : Tuple = os.path.join(training_args.output_dir , 'eval_results.txt' ) if trainer.is_world_process_zero(): with open(A , 'w' ) as writer: logger.info('***** Eval results *****' ) for key, value in result.items(): logger.info(' %s = %s' , A , A ) writer.write('%s = %s\n' % (key, value) ) results.update(A ) # Predict if training_args.do_predict: __snake_case : str = TokenClassificationDataset( token_classification_task=A , data_dir=data_args.data_dir , tokenizer=A , labels=A , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , ) __snake_case ,__snake_case ,__snake_case : str = trainer.predict(A ) __snake_case ,__snake_case : List[str] = align_predictions(A , A ) __snake_case : Optional[int] = os.path.join(training_args.output_dir , 'test_results.txt' ) if trainer.is_world_process_zero(): with open(A , 'w' ) as writer: for key, value in metrics.items(): logger.info(' %s = %s' , A , A ) writer.write('%s = %s\n' % (key, value) ) # Save predictions __snake_case : List[str] = os.path.join(training_args.output_dir , 'test_predictions.txt' ) if trainer.is_world_process_zero(): with open(A , 'w' ) as writer: with open(os.path.join(data_args.data_dir , 'test.txt' ) , 'r' ) as f: token_classification_task.write_predictions_to_file(A , A , A ) return results def _SCREAMING_SNAKE_CASE ( A : int ) -> Any: """simple docstring""" # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
61
1
'''simple docstring''' from __future__ import annotations import time import numpy as np __A = [8, 5, 9, 7] __A = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] __A = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class a_ : def __init__(self , __a , __a , __a , ) -> None: """simple docstring""" __snake_case : Dict = claim_vector __snake_case : str = allocated_resources_table __snake_case : Tuple = maximum_claim_table def SCREAMING_SNAKE_CASE__ (self) -> list[int]: """simple docstring""" return [ sum(p_item[i] for p_item in self.__allocated_resources_table) for i in range(len(self.__allocated_resources_table[0])) ] def SCREAMING_SNAKE_CASE__ (self) -> list[int]: """simple docstring""" return np.array(self.__claim_vector) - np.array( self.__processes_resource_summation()) def SCREAMING_SNAKE_CASE__ (self) -> list[list[int]]: """simple docstring""" return [ list(np.array(self.__maximum_claim_table[i]) - np.array(__a)) for i, allocated_resource in enumerate(self.__allocated_resources_table) ] def SCREAMING_SNAKE_CASE__ (self) -> dict[int, list[int]]: """simple docstring""" return {self.__need().index(__a): i for i in self.__need()} def SCREAMING_SNAKE_CASE__ (self , **__a) -> None: """simple docstring""" __snake_case : Optional[Any] = self.__need() __snake_case : List[Any] = self.__allocated_resources_table __snake_case : List[str] = self.__available_resources() __snake_case : Any = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print('_' * 5_0 + '\n') while need_list: __snake_case : List[str] = False for each_need in need_list: __snake_case : int = True for index, need in enumerate(__a): if need > available_resources[index]: __snake_case : Any = False break if execution: __snake_case : Union[str, Any] = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: __snake_case : List[str] = original_need_index print(F"""Process {process_number + 1} is executing.""") # remove the process run from stack need_list.remove(__a) # update available/freed resources stack __snake_case : Union[str, Any] = np.array(__a) + np.array( alloc_resources_table[process_number]) print( 'Updated available resource stack for processes: ' + ' '.join([str(__a) for x in available_resources])) break if safe: print('The process is in a safe state.\n') else: print('System in unsafe state. Aborting...\n') break def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" print(' ' * 9 + 'Allocated Resource Table') for item in self.__allocated_resources_table: print( F"""P{self.__allocated_resources_table.index(__a) + 1}""" + ' '.join(F"""{it:>8}""" for it in item) + '\n') print(' ' * 9 + 'System Resource Table') for item in self.__maximum_claim_table: print( F"""P{self.__maximum_claim_table.index(__a) + 1}""" + ' '.join(F"""{it:>8}""" for it in item) + '\n') print( 'Current Usage by Active Processes: ' + ' '.join(str(__a) for x in self.__claim_vector)) print( 'Initial Available Resources: ' + ' '.join(str(__a) for x in self.__available_resources())) time.sleep(1) if __name__ == "__main__": import doctest doctest.testmod()
61
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( A : list ) -> list: """simple docstring""" __snake_case : Tuple = False while is_sorted is False: # Until all the indices are traversed keep looping __snake_case : Optional[Any] = True for i in range(0 , len(A ) - 1 , 2 ): # iterating over all even indices if input_list[i] > input_list[i + 1]: __snake_case ,__snake_case : int = input_list[i + 1], input_list[i] # swapping if elements not in order __snake_case : List[Any] = False for i in range(1 , len(A ) - 1 , 2 ): # iterating over all odd indices if input_list[i] > input_list[i + 1]: __snake_case ,__snake_case : Tuple = input_list[i + 1], input_list[i] # swapping if elements not in order __snake_case : Any = False return input_list if __name__ == "__main__": print('''Enter list to be sorted''') __A = [int(x) for x in input().split()] # inputing elements of the list in one line __A = odd_even_sort(input_list) print('''The sorted list is''') print(sorted_list)
61
1
'''simple docstring''' from decimal import Decimal, getcontext from math import ceil, factorial def _SCREAMING_SNAKE_CASE ( A : int ) -> str: """simple docstring""" if not isinstance(A , A ): raise TypeError('Undefined for non-integers' ) elif precision < 1: raise ValueError('Undefined for non-natural numbers' ) __snake_case : Optional[int] = precision __snake_case : List[Any] = ceil(precision / 14 ) __snake_case : str = 42_68_80 * Decimal(1_00_05 ).sqrt() __snake_case : Optional[int] = 1 __snake_case : Union[str, Any] = 13_59_14_09 __snake_case : Union[str, Any] = Decimal(A ) for k in range(1 , A ): __snake_case : int = factorial(6 * k ) // (factorial(3 * k ) * factorial(A ) ** 3) linear_term += 5_45_14_01_34 exponential_term *= -26_25_37_41_26_40_76_80_00 partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term return str(constant_term / partial_sum )[:-1] if __name__ == "__main__": __A = 5_0 print(f'''The first {n} digits of pi is: {pi(n)}''')
61
'''simple docstring''' import argparse import json from collections import OrderedDict from functools import partial from pathlib import Path import timm import torch from huggingface_hub import hf_hub_download from transformers import LevitConfig, LevitForImageClassificationWithTeacher, LevitImageProcessor from transformers.utils import logging logging.set_verbosity_info() __A = logging.get_logger() def _SCREAMING_SNAKE_CASE ( A : int , A : str , A : LevitConfig , A : Path , A : bool = True ) -> Dict: """simple docstring""" print(F"""Converting {name}...""" ) with torch.no_grad(): if hidden_sizes == 1_28: if name[-1] == "S": __snake_case : Optional[int] = timm.create_model('levit_128s' , pretrained=A ) else: __snake_case : Tuple = timm.create_model('levit_128' , pretrained=A ) if hidden_sizes == 1_92: __snake_case : int = timm.create_model('levit_192' , pretrained=A ) if hidden_sizes == 2_56: __snake_case : List[Any] = timm.create_model('levit_256' , pretrained=A ) if hidden_sizes == 3_84: __snake_case : int = timm.create_model('levit_384' , pretrained=A ) from_model.eval() __snake_case : str = LevitForImageClassificationWithTeacher(A ).eval() __snake_case : int = OrderedDict() __snake_case : Optional[Any] = from_model.state_dict() __snake_case : Tuple = list(from_model.state_dict().keys() ) __snake_case : List[str] = list(our_model.state_dict().keys() ) print(len(A ) , len(A ) ) for i in range(len(A ) ): __snake_case : Optional[int] = weights[og_keys[i]] our_model.load_state_dict(A ) __snake_case : Tuple = torch.randn((2, 3, 2_24, 2_24) ) __snake_case : Union[str, Any] = from_model(A ) __snake_case : List[str] = our_model(A ).logits assert torch.allclose(A , A ), "The model logits don't match the original one." __snake_case : int = name print(A ) if push_to_hub: our_model.save_pretrained(save_directory / checkpoint_name ) __snake_case : int = LevitImageProcessor() image_processor.save_pretrained(save_directory / checkpoint_name ) print(F"""Pushed {checkpoint_name}""" ) def _SCREAMING_SNAKE_CASE ( A : Path , A : str = None , A : bool = True ) -> List[Any]: """simple docstring""" __snake_case : Optional[Any] = 'imagenet-1k-id2label.json' __snake_case : Tuple = 10_00 __snake_case : Dict = (1, num_labels) __snake_case : List[str] = 'huggingface/label-files' __snake_case : Any = num_labels __snake_case : str = json.load(open(hf_hub_download(A , A , repo_type='dataset' ) , 'r' ) ) __snake_case : Any = {int(A ): v for k, v in idalabel.items()} __snake_case : int = idalabel __snake_case : Union[str, Any] = {v: k for k, v in idalabel.items()} __snake_case : Optional[int] = partial(A , num_labels=A , idalabel=A , labelaid=A ) __snake_case : Dict = { 'levit-128S': 1_28, 'levit-128': 1_28, 'levit-192': 1_92, 'levit-256': 2_56, 'levit-384': 3_84, } __snake_case : Union[str, Any] = { 'levit-128S': ImageNetPreTrainedConfig( hidden_sizes=[1_28, 2_56, 3_84] , num_attention_heads=[4, 6, 8] , depths=[2, 3, 4] , key_dim=[16, 16, 16] , drop_path_rate=0 , ), 'levit-128': ImageNetPreTrainedConfig( hidden_sizes=[1_28, 2_56, 3_84] , num_attention_heads=[4, 8, 12] , depths=[4, 4, 4] , key_dim=[16, 16, 16] , drop_path_rate=0 , ), 'levit-192': ImageNetPreTrainedConfig( hidden_sizes=[1_92, 2_88, 3_84] , num_attention_heads=[3, 5, 6] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0 , ), 'levit-256': ImageNetPreTrainedConfig( hidden_sizes=[2_56, 3_84, 5_12] , num_attention_heads=[4, 6, 8] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0 , ), 'levit-384': ImageNetPreTrainedConfig( hidden_sizes=[3_84, 5_12, 7_68] , num_attention_heads=[6, 9, 12] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0.1 , ), } if model_name: convert_weight_and_push( names_to_hidden_sizes[model_name] , A , names_to_config[model_name] , A , A ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(names_to_hidden_sizes[model_name] , A , A , A , A ) return config, expected_shape if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default=None, type=str, help='''The name of the model you wish to convert, it must be one of the supported Levit* architecture,''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default='''levit-dump-folder/''', type=Path, required=False, help='''Path to the output PyTorch model directory.''', ) parser.add_argument('''--push_to_hub''', action='''store_true''', help='''Push model and image processor to the hub''') parser.add_argument( '''--no-push_to_hub''', dest='''push_to_hub''', action='''store_false''', help='''Do not push model and image processor to the hub''', ) __A = parser.parse_args() __A = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
61
1
'''simple docstring''' from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. __A = 1_0 def _SCREAMING_SNAKE_CASE ( A : int , A : int , A : list[int] , A : int ) -> int: """simple docstring""" for i in range(A , A ): if array[i] == target: return i return -1 def _SCREAMING_SNAKE_CASE ( A : list[int] , A : int ) -> int: """simple docstring""" __snake_case : Any = 0 __snake_case : Any = len(A ) while left <= right: if right - left < precision: return lin_search(A , A , A , A ) __snake_case : Dict = (left + right) // 3 + 1 __snake_case : Optional[Any] = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: __snake_case : Optional[int] = one_third - 1 elif array[two_third] < target: __snake_case : Tuple = two_third + 1 else: __snake_case : str = one_third + 1 __snake_case : Union[str, Any] = two_third - 1 else: return -1 def _SCREAMING_SNAKE_CASE ( A : int , A : int , A : list[int] , A : int ) -> int: """simple docstring""" if left < right: if right - left < precision: return lin_search(A , A , A , A ) __snake_case : Union[str, Any] = (left + right) // 3 + 1 __snake_case : List[str] = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: return rec_ternary_search(A , one_third - 1 , A , A ) elif array[two_third] < target: return rec_ternary_search(two_third + 1 , A , A , A ) else: return rec_ternary_search(one_third + 1 , two_third - 1 , A , A ) else: return -1 if __name__ == "__main__": import doctest doctest.testmod() __A = input('''Enter numbers separated by comma:\n''').strip() __A = [int(item.strip()) for item in user_input.split(''',''')] assert collection == sorted(collection), f"List must be ordered.\n{collection}." __A = int(input('''Enter the number to be found in the list:\n''').strip()) __A = ite_ternary_search(collection, target) __A = rec_ternary_search(0, len(collection) - 1, collection, target) if resulta != -1: print(f'''Iterative search: {target} found at positions: {resulta}''') print(f'''Recursive search: {target} found at positions: {resulta}''') else: print('''Not found''')
61
'''simple docstring''' import inspect import unittest from typing import List import numpy as np from transformers import EfficientFormerConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerModel, ) from transformers.models.efficientformer.modeling_tf_efficientformer import ( TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_vision_available(): from PIL import Image from transformers import EfficientFormerImageProcessor class a_ : def __init__(self , __a , __a = 1_3 , __a = 6_4 , __a = 2 , __a = 3 , __a = 3 , __a = True , __a = True , __a = 1_2_8 , __a=[1_6, 3_2, 6_4, 1_2_8] , __a = 7 , __a = 4 , __a = 3_7 , __a = "gelu" , __a = 0.1 , __a = 0.1 , __a = 1_0 , __a = 0.02 , __a = 2 , __a = 1 , __a = 1_2_8 , __a = [2, 2, 2, 2] , __a = 2 , __a = 2 , ) -> str: """simple docstring""" __snake_case : Optional[Any] = parent __snake_case : Optional[int] = batch_size __snake_case : Optional[Any] = image_size __snake_case : Optional[int] = patch_size __snake_case : Optional[Any] = num_channels __snake_case : Optional[Any] = is_training __snake_case : Tuple = use_labels __snake_case : Optional[int] = hidden_size __snake_case : Any = num_hidden_layers __snake_case : List[str] = num_attention_heads __snake_case : Tuple = intermediate_size __snake_case : List[str] = hidden_act __snake_case : Dict = hidden_dropout_prob __snake_case : Any = attention_probs_dropout_prob __snake_case : Dict = type_sequence_label_size __snake_case : str = initializer_range __snake_case : int = encoder_stride __snake_case : List[str] = num_attention_outputs __snake_case : Optional[Any] = embed_dim __snake_case : Optional[Any] = embed_dim + 1 __snake_case : List[str] = resolution __snake_case : Optional[int] = depths __snake_case : List[Any] = hidden_sizes __snake_case : List[str] = dim __snake_case : Union[str, Any] = mlp_expansion_ratio def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" __snake_case : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) __snake_case : List[str] = None if self.use_labels: __snake_case : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size) __snake_case : Tuple = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" return EfficientFormerConfig( 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=__a , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , resolution=self.resolution , depths=self.depths , hidden_sizes=self.hidden_sizes , dim=self.dim , mlp_expansion_ratio=self.mlp_expansion_ratio , ) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Optional[int]: """simple docstring""" __snake_case : Union[str, Any] = TFEfficientFormerModel(config=__a) __snake_case : int = model(__a , training=__a) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Tuple: """simple docstring""" __snake_case : Dict = self.type_sequence_label_size __snake_case : List[Any] = TFEfficientFormerForImageClassification(__a) __snake_case : Optional[int] = model(__a , labels=__a , training=__a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) # test greyscale images __snake_case : List[Any] = 1 __snake_case : List[Any] = TFEfficientFormerForImageClassification(__a) __snake_case : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) __snake_case : str = model(__a , labels=__a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) def SCREAMING_SNAKE_CASE__ (self) -> Any: """simple docstring""" __snake_case : Union[str, Any] = self.prepare_config_and_inputs() __snake_case ,__snake_case ,__snake_case : Union[str, Any] = config_and_inputs __snake_case : Optional[int] = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class a_ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): _snake_case = ( ( TFEfficientFormerModel, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerForImageClassification, ) if is_tf_available() else () ) _snake_case = ( { """feature-extraction""": TFEfficientFormerModel, """image-classification""": ( TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, ), } if is_tf_available() else {} ) _snake_case = False _snake_case = False _snake_case = False _snake_case = False _snake_case = False def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : Dict = TFEfficientFormerModelTester(self) __snake_case : List[Any] = ConfigTester( self , config_class=__a , has_text_modality=__a , hidden_size=3_7) def SCREAMING_SNAKE_CASE__ (self) -> str: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='EfficientFormer does not use inputs_embeds') def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" pass @unittest.skip(reason='EfficientFormer does not support input and output embeddings') def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self) -> Any: """simple docstring""" __snake_case ,__snake_case : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : Optional[int] = model_class(__a) __snake_case : Union[str, Any] = inspect.signature(model.call) # signature.parameters is an OrderedDict => so arg_names order is deterministic __snake_case : Optional[int] = [*signature.parameters.keys()] __snake_case : Dict = ['pixel_values'] self.assertListEqual(arg_names[:1] , __a) def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" def check_hidden_states_output(__a , __a , __a): __snake_case : str = model_class(__a) __snake_case : List[Any] = model(**self._prepare_for_class(__a , __a) , training=__a) __snake_case : str = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __snake_case : Optional[Any] = getattr( self.model_tester , 'expected_num_hidden_layers' , self.model_tester.num_hidden_layers + 1) self.assertEqual(len(__a) , __a) if hasattr(self.model_tester , 'encoder_seq_length'): __snake_case : List[Any] = self.model_tester.encoder_seq_length if hasattr(self.model_tester , 'chunk_length') and self.model_tester.chunk_length > 1: __snake_case : str = seq_length * self.model_tester.chunk_length else: __snake_case : Optional[int] = self.model_tester.seq_length self.assertListEqual( list(hidden_states[-1].shape[-2:]) , [seq_length, self.model_tester.hidden_size] , ) if config.is_encoder_decoder: __snake_case : List[Any] = outputs.decoder_hidden_states self.asseretIsInstance(__a , (list, tuple)) self.assertEqual(len(__a) , __a) __snake_case : List[str] = getattr(self.model_tester , 'seq_length' , __a) __snake_case : Tuple = getattr(self.model_tester , 'decoder_seq_length' , __a) self.assertListEqual( list(hidden_states[-1].shape[-2:]) , [decoder_seq_length, self.model_tester.hidden_size] , ) __snake_case ,__snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : List[str] = True check_hidden_states_output(__a , __a , __a) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __snake_case : str = True check_hidden_states_output(__a , __a , __a) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a=False) -> int: """simple docstring""" __snake_case : Optional[int] = super()._prepare_for_class(__a , __a , return_labels=__a) if return_labels: if model_class.__name__ == "TFEfficientFormerForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" __snake_case : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a) @unittest.skip(reason='EfficientFormer does not implement masked image modeling yet') def SCREAMING_SNAKE_CASE__ (self) -> Tuple: """simple docstring""" __snake_case : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*__a) def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__a) @slow def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case : Any = TFEfficientFormerModel.from_pretrained(__a) self.assertIsNotNone(__a) def SCREAMING_SNAKE_CASE__ (self) -> Tuple: """simple docstring""" __snake_case ,__snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() __snake_case : Tuple = True __snake_case : Optional[Any] = getattr(self.model_tester , 'seq_length' , __a) __snake_case : List[Any] = getattr(self.model_tester , 'encoder_seq_length' , __a) __snake_case : Tuple = getattr(self.model_tester , 'key_length' , __a) __snake_case : Optional[Any] = getattr(self.model_tester , 'chunk_length' , __a) if chunk_length is not None and hasattr(self.model_tester , 'num_hashes'): __snake_case : str = encoder_seq_length * self.model_tester.num_hashes for model_class in self.all_model_classes: __snake_case : Optional[Any] = True __snake_case : Dict = False __snake_case : Optional[int] = True __snake_case : Dict = model_class(__a) __snake_case : Tuple = model(**self._prepare_for_class(__a , __a) , training=__a) __snake_case : Union[str, Any] = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(__a) , self.model_tester.num_attention_outputs) # check that output_attentions also work using config del inputs_dict["output_attentions"] __snake_case : Dict = True __snake_case : str = model_class(__a) __snake_case : str = model(**self._prepare_for_class(__a , __a) , training=__a) __snake_case : Tuple = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(__a) , self.model_tester.num_attention_outputs) if chunk_length is not None: self.assertListEqual( list(attentions[0].shape[-4:]) , [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length] , ) else: self.assertListEqual( list(attentions[0].shape[-3:]) , [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length] , ) def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case ,__snake_case : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # Prepare our model __snake_case : Tuple = model_class(__a) # These are maximally general inputs for the model, with multiple None dimensions # Hopefully this will catch any conditionals that fail for flexible shapes __snake_case : Optional[Any] = { key: tf.keras.Input(shape=val.shape[1:] , dtype=val.dtype , name=__a) for key, val in model.input_signature.items() if key in model.dummy_inputs } __snake_case : Tuple = model(__a) self.assertTrue(outputs_dict is not None) def _SCREAMING_SNAKE_CASE ( ) -> int: """simple docstring""" __snake_case : Tuple = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class a_ ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" return ( EfficientFormerImageProcessor.from_pretrained('snap-research/efficientformer-l1-300') if is_vision_available() else None ) @slow def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" __snake_case : List[str] = TFEfficientFormerForImageClassification.from_pretrained('snap-research/efficientformer-l1-300') __snake_case : Optional[int] = self.default_image_processor __snake_case : List[Any] = prepare_img() __snake_case : List[Any] = image_processor(images=__a , return_tensors='tf') # forward pass __snake_case : List[str] = model(**__a , training=__a) # verify the logits __snake_case : str = tf.TensorShape((1, 1_0_0_0)) self.assertEqual(outputs.logits.shape , __a) __snake_case : Any = tf.constant([-0.0_555, 0.4_825, -0.0_852]) self.assertTrue(np.allclose(outputs.logits[0, :3] , __a , atol=1E-4)) @slow def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" __snake_case : List[Any] = TFEfficientFormerForImageClassificationWithTeacher.from_pretrained( 'snap-research/efficientformer-l1-300') __snake_case : List[Any] = self.default_image_processor __snake_case : Union[str, Any] = prepare_img() __snake_case : List[Any] = image_processor(images=__a , return_tensors='tf') # forward pass __snake_case : Optional[int] = model(**__a , training=__a) # verify the logits __snake_case : Optional[int] = tf.TensorShape((1, 1_0_0_0)) self.assertEqual(outputs.logits.shape , __a) __snake_case : List[str] = tf.constant([-0.1_312, 0.4_353, -1.0_499]) self.assertTrue(np.allclose(outputs.logits[0, :3] , __a , atol=1E-4))
61
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __A = {'''configuration_xlnet''': ['''XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLNetConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ['''XLNetTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ['''XLNetTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ '''XLNET_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XLNetForMultipleChoice''', '''XLNetForQuestionAnswering''', '''XLNetForQuestionAnsweringSimple''', '''XLNetForSequenceClassification''', '''XLNetForTokenClassification''', '''XLNetLMHeadModel''', '''XLNetModel''', '''XLNetPreTrainedModel''', '''load_tf_weights_in_xlnet''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ '''TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFXLNetForMultipleChoice''', '''TFXLNetForQuestionAnsweringSimple''', '''TFXLNetForSequenceClassification''', '''TFXLNetForTokenClassification''', '''TFXLNetLMHeadModel''', '''TFXLNetMainLayer''', '''TFXLNetModel''', '''TFXLNetPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet import XLNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet_fast import XLNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlnet import ( XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, XLNetForMultipleChoice, XLNetForQuestionAnswering, XLNetForQuestionAnsweringSimple, XLNetForSequenceClassification, XLNetForTokenClassification, XLNetLMHeadModel, XLNetModel, XLNetPreTrainedModel, load_tf_weights_in_xlnet, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlnet import ( TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLNetForMultipleChoice, TFXLNetForQuestionAnsweringSimple, TFXLNetForSequenceClassification, TFXLNetForTokenClassification, TFXLNetLMHeadModel, TFXLNetMainLayer, TFXLNetModel, TFXLNetPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
61
'''simple docstring''' __A = {str(digit): digit**5 for digit in range(1_0)} def _SCREAMING_SNAKE_CASE ( A : int ) -> int: """simple docstring""" return sum(DIGITS_FIFTH_POWER[digit] for digit in str(A ) ) def _SCREAMING_SNAKE_CASE ( ) -> int: """simple docstring""" return sum( number for number in range(10_00 , 1_00_00_00 ) if number == digits_fifth_powers_sum(A ) ) if __name__ == "__main__": print(solution())
61
1
'''simple docstring''' import unittest import torch from torch import nn from diffusers.models.activations import get_activation class a_ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" __snake_case : str = get_activation('swish') self.assertIsInstance(__a , nn.SiLU) self.assertEqual(act(torch.tensor(-1_0_0 , dtype=torch.floataa)).item() , 0) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa)).item() , 0) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa)).item() , 0) self.assertEqual(act(torch.tensor(2_0 , dtype=torch.floataa)).item() , 2_0) def SCREAMING_SNAKE_CASE__ (self) -> Any: """simple docstring""" __snake_case : List[Any] = get_activation('silu') self.assertIsInstance(__a , nn.SiLU) self.assertEqual(act(torch.tensor(-1_0_0 , dtype=torch.floataa)).item() , 0) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa)).item() , 0) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa)).item() , 0) self.assertEqual(act(torch.tensor(2_0 , dtype=torch.floataa)).item() , 2_0) def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" __snake_case : List[str] = get_activation('mish') self.assertIsInstance(__a , nn.Mish) self.assertEqual(act(torch.tensor(-2_0_0 , dtype=torch.floataa)).item() , 0) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa)).item() , 0) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa)).item() , 0) self.assertEqual(act(torch.tensor(2_0 , dtype=torch.floataa)).item() , 2_0) def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]: """simple docstring""" __snake_case : List[str] = get_activation('gelu') self.assertIsInstance(__a , nn.GELU) self.assertEqual(act(torch.tensor(-1_0_0 , dtype=torch.floataa)).item() , 0) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa)).item() , 0) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa)).item() , 0) self.assertEqual(act(torch.tensor(2_0 , dtype=torch.floataa)).item() , 2_0)
61
'''simple docstring''' from __future__ import annotations from collections import deque from collections.abc import Sequence from dataclasses import dataclass from typing import Any @dataclass class a_ : _snake_case = 42 _snake_case = None _snake_case = None def _SCREAMING_SNAKE_CASE ( ) -> Node | None: """simple docstring""" __snake_case : str = Node(1 ) __snake_case : Tuple = Node(2 ) __snake_case : Optional[int] = Node(3 ) __snake_case : List[str] = Node(4 ) __snake_case : List[str] = Node(5 ) return tree def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> list[int]: """simple docstring""" return [root.data, *preorder(root.left ), *preorder(root.right )] if root else [] def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> list[int]: """simple docstring""" return postorder(root.left ) + postorder(root.right ) + [root.data] if root else [] def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> list[int]: """simple docstring""" return [*inorder(root.left ), root.data, *inorder(root.right )] if root else [] def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> int: """simple docstring""" return (max(height(root.left ) , height(root.right ) ) + 1) if root else 0 def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> Sequence[Node | None]: """simple docstring""" __snake_case : list[Any] = [] if root is None: return output __snake_case : Optional[int] = deque([root] ) while process_queue: __snake_case : List[str] = process_queue.popleft() output.append(node.data ) if node.left: process_queue.append(node.left ) if node.right: process_queue.append(node.right ) return output def _SCREAMING_SNAKE_CASE ( A : Node | None , A : int ) -> Sequence[Node | None]: """simple docstring""" __snake_case : list[Any] = [] def populate_output(A : Node | None , A : int ) -> None: if not root: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.left , level - 1 ) populate_output(root.right , level - 1 ) populate_output(A , A ) return output def _SCREAMING_SNAKE_CASE ( A : Node | None , A : int ) -> Sequence[Node | None]: """simple docstring""" __snake_case : list[Any] = [] def populate_output(A : Node | None , A : int ) -> None: if root is None: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.right , level - 1 ) populate_output(root.left , level - 1 ) populate_output(A , A ) return output def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> Sequence[Node | None] | list[Any]: """simple docstring""" if root is None: return [] __snake_case : list[Sequence[Node | None]] = [] __snake_case : List[Any] = 0 __snake_case : int = height(A ) for h in range(1 , height_tree + 1 ): if not flag: output.append(get_nodes_from_left_to_right(A , A ) ) __snake_case : int = 1 else: output.append(get_nodes_from_right_to_left(A , A ) ) __snake_case : Tuple = 0 return output def _SCREAMING_SNAKE_CASE ( ) -> None: # Main function for testing. """simple docstring""" __snake_case : Optional[int] = make_tree() print(F"""In-order Traversal: {inorder(A )}""" ) print(F"""Pre-order Traversal: {preorder(A )}""" ) print(F"""Post-order Traversal: {postorder(A )}""" , '\n' ) print(F"""Height of Tree: {height(A )}""" , '\n' ) print('Complete Level Order Traversal: ' ) print(level_order(A ) , '\n' ) print('Level-wise order Traversal: ' ) for level in range(1 , height(A ) + 1 ): print(F"""Level {level}:""" , get_nodes_from_left_to_right(A , level=A ) ) print('\nZigZag order Traversal: ' ) print(zigzag(A ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
61
1
'''simple docstring''' import math import sys def _SCREAMING_SNAKE_CASE ( A : str ) -> str: """simple docstring""" __snake_case : Dict = '' try: with open(A , 'rb' ) as binary_file: __snake_case : Optional[int] = binary_file.read() for dat in data: __snake_case : str = F"""{dat:08b}""" result += curr_byte return result except OSError: print('File not accessible' ) sys.exit() def _SCREAMING_SNAKE_CASE ( A : str ) -> str: """simple docstring""" __snake_case : str = {'0': '0', '1': '1'} __snake_case ,__snake_case : Tuple = '', '' __snake_case : Optional[int] = len(A ) for i in range(len(A ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue __snake_case : Any = lexicon[curr_string] result += last_match_id __snake_case : Tuple = last_match_id + '0' if math.loga(A ).is_integer(): __snake_case : Optional[Any] = {} for curr_key in list(A ): __snake_case : Any = lexicon.pop(A ) __snake_case : str = new_lex __snake_case : Dict = last_match_id + '1' index += 1 __snake_case : Tuple = '' return result def _SCREAMING_SNAKE_CASE ( A : str , A : str ) -> None: """simple docstring""" __snake_case : int = 8 try: with open(A , 'wb' ) as opened_file: __snake_case : str = [ to_write[i : i + byte_length] for i in range(0 , len(A ) , A ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append('10000000' ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array[:-1]: opened_file.write(int(A , 2 ).to_bytes(1 , byteorder='big' ) ) except OSError: print('File not accessible' ) sys.exit() def _SCREAMING_SNAKE_CASE ( A : str ) -> str: """simple docstring""" __snake_case : Optional[int] = 0 for letter in data_bits: if letter == "1": break counter += 1 __snake_case : Any = data_bits[counter:] __snake_case : str = data_bits[counter + 1 :] return data_bits def _SCREAMING_SNAKE_CASE ( A : str , A : str ) -> None: """simple docstring""" __snake_case : List[Any] = read_file_binary(A ) __snake_case : Tuple = remove_prefix(A ) __snake_case : Optional[Any] = decompress_data(A ) write_file_binary(A , A ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
61
'''simple docstring''' from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class a_ : def __init__(self , __a = None) -> None: """simple docstring""" if components is None: __snake_case : List[str] = [] __snake_case : Optional[int] = list(__a) def __len__(self) -> int: """simple docstring""" return len(self.__components) def __str__(self) -> str: """simple docstring""" return "(" + ",".join(map(__a , self.__components)) + ")" def __add__(self , __a) -> Vector: """simple docstring""" __snake_case : Optional[Any] = len(self) if size == len(__a): __snake_case : Optional[int] = [self.__components[i] + other.component(__a) for i in range(__a)] return Vector(__a) else: raise Exception('must have the same size') def __sub__(self , __a) -> Vector: """simple docstring""" __snake_case : Optional[Any] = len(self) if size == len(__a): __snake_case : Optional[int] = [self.__components[i] - other.component(__a) for i in range(__a)] return Vector(__a) else: # error case raise Exception('must have the same size') @overload def __mul__(self , __a) -> Vector: """simple docstring""" ... @overload def __mul__(self , __a) -> float: """simple docstring""" ... def __mul__(self , __a) -> float | Vector: """simple docstring""" if isinstance(__a , (float, int)): __snake_case : str = [c * other for c in self.__components] return Vector(__a) elif isinstance(__a , __a) and len(self) == len(__a): __snake_case : List[Any] = len(self) __snake_case : Dict = [self.__components[i] * other.component(__a) for i in range(__a)] return sum(__a) else: # error case raise Exception('invalid operand!') def SCREAMING_SNAKE_CASE__ (self) -> Vector: """simple docstring""" return Vector(self.__components) def SCREAMING_SNAKE_CASE__ (self , __a) -> float: """simple docstring""" if isinstance(__a , __a) and -len(self.__components) <= i < len(self.__components): return self.__components[i] else: raise Exception('index out of range') def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> None: """simple docstring""" assert -len(self.__components) <= pos < len(self.__components) __snake_case : int = value def SCREAMING_SNAKE_CASE__ (self) -> float: """simple docstring""" if len(self.__components) == 0: raise Exception('Vector is empty') __snake_case : Tuple = [c**2 for c in self.__components] return math.sqrt(sum(__a)) def SCREAMING_SNAKE_CASE__ (self , __a , __a = False) -> float: """simple docstring""" __snake_case : Tuple = self * other __snake_case : Optional[int] = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den)) else: return math.acos(num / den) def _SCREAMING_SNAKE_CASE ( A : int ) -> Vector: """simple docstring""" assert isinstance(A , A ) return Vector([0] * dimension ) def _SCREAMING_SNAKE_CASE ( A : int , A : int ) -> Vector: """simple docstring""" assert isinstance(A , A ) and (isinstance(A , A )) __snake_case : Any = [0] * dimension __snake_case : int = 1 return Vector(A ) def _SCREAMING_SNAKE_CASE ( A : float , A : Vector , A : Vector ) -> Vector: """simple docstring""" assert ( isinstance(A , A ) and isinstance(A , A ) and (isinstance(A , (int, float) )) ) return x * scalar + y def _SCREAMING_SNAKE_CASE ( A : int , A : int , A : int ) -> Vector: """simple docstring""" random.seed(A ) __snake_case : List[Any] = [random.randint(A , A ) for _ in range(A )] return Vector(A ) class a_ : def __init__(self , __a , __a , __a) -> None: """simple docstring""" __snake_case : Union[str, Any] = matrix __snake_case : int = w __snake_case : str = h def __str__(self) -> str: """simple docstring""" __snake_case : Dict = '' for i in range(self.__height): ans += "|" for j in range(self.__width): if j < self.__width - 1: ans += str(self.__matrix[i][j]) + "," else: ans += str(self.__matrix[i][j]) + "|\n" return ans def __add__(self , __a) -> Matrix: """simple docstring""" if self.__width == other.width() and self.__height == other.height(): __snake_case : Tuple = [] for i in range(self.__height): __snake_case : List[Any] = [ self.__matrix[i][j] + other.component(__a , __a) for j in range(self.__width) ] matrix.append(__a) return Matrix(__a , self.__width , self.__height) else: raise Exception('matrix must have the same dimension!') def __sub__(self , __a) -> Matrix: """simple docstring""" if self.__width == other.width() and self.__height == other.height(): __snake_case : str = [] for i in range(self.__height): __snake_case : List[str] = [ self.__matrix[i][j] - other.component(__a , __a) for j in range(self.__width) ] matrix.append(__a) return Matrix(__a , self.__width , self.__height) else: raise Exception('matrices must have the same dimension!') @overload def __mul__(self , __a) -> Matrix: """simple docstring""" ... @overload def __mul__(self , __a) -> Vector: """simple docstring""" ... def __mul__(self , __a) -> Vector | Matrix: """simple docstring""" if isinstance(__a , __a): # matrix-vector if len(__a) == self.__width: __snake_case : Tuple = zero_vector(self.__height) for i in range(self.__height): __snake_case : Union[str, Any] = [ self.__matrix[i][j] * other.component(__a) for j in range(self.__width) ] ans.change_component(__a , sum(__a)) return ans else: raise Exception( 'vector must have the same size as the ' 'number of columns of the matrix!') elif isinstance(__a , (int, float)): # matrix-scalar __snake_case : str = [ [self.__matrix[i][j] * other for j in range(self.__width)] for i in range(self.__height) ] return Matrix(__a , self.__width , self.__height) return None def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" return self.__height def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" return self.__width def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> float: """simple docstring""" if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception('change_component: indices out of bounds') def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> None: """simple docstring""" if 0 <= x < self.__height and 0 <= y < self.__width: __snake_case : List[Any] = value else: raise Exception('change_component: indices out of bounds') def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> float: """simple docstring""" if self.__height != self.__width: raise Exception('Matrix is not square') __snake_case : List[Any] = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(__a)): __snake_case : Tuple = minor[i][:y] + minor[i][y + 1 :] return Matrix(__a , self.__width - 1 , self.__height - 1).determinant() def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> float: """simple docstring""" if self.__height != self.__width: raise Exception('Matrix is not square') if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(__a , __a) else: raise Exception('Indices out of bounds') def SCREAMING_SNAKE_CASE__ (self) -> float: """simple docstring""" if self.__height != self.__width: raise Exception('Matrix is not square') if self.__height < 1: raise Exception('Matrix has no element') elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: __snake_case : Any = [ self.__matrix[0][y] * self.cofactor(0 , __a) for y in range(self.__width) ] return sum(__a) def _SCREAMING_SNAKE_CASE ( A : int ) -> Matrix: """simple docstring""" __snake_case : list[list[float]] = [[0] * n for _ in range(A )] return Matrix(A , A , A ) def _SCREAMING_SNAKE_CASE ( A : int , A : int , A : int , A : int ) -> Matrix: """simple docstring""" random.seed(A ) __snake_case : list[list[float]] = [ [random.randint(A , A ) for _ in range(A )] for _ in range(A ) ] return Matrix(A , A , A )
61
1
'''simple docstring''' import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def _SCREAMING_SNAKE_CASE ( A : str ) -> List[str]: """simple docstring""" monkeypatch.setattr('datasets.utils.deprecation_utils._emitted_deprecation_warnings' , set() ) @pytest.fixture def _SCREAMING_SNAKE_CASE ( A : Optional[int] ) -> Dict: """simple docstring""" class a_ : def __init__(self , __a) -> Optional[int]: """simple docstring""" __snake_case : List[str] = metric_id class a_ : _snake_case = [MetricMock(UpperCamelCase_ ) for metric_id in ["""accuracy""", """mse""", """precision""", """codeparrot/apps_metric"""]] def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" return self._metrics monkeypatch.setattr('datasets.inspect.huggingface_hub' , HfhMock() ) @pytest.mark.parametrize( 'func, args' , [(load_metric, ('metrics/mse',)), (list_metrics, ()), (inspect_metric, ('metrics/mse', 'tmp_path'))] ) def _SCREAMING_SNAKE_CASE ( A : Tuple , A : List[str] , A : Dict , A : Union[str, Any] , A : Dict ) -> str: """simple docstring""" if "tmp_path" in args: __snake_case : Dict = tuple(arg if arg != 'tmp_path' else tmp_path for arg in args ) with pytest.warns(A , match='https://huggingface.co/docs/evaluate' ): func(*A )
61
'''simple docstring''' import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification if is_tf_available(): from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification if is_flax_available(): from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification __A = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co __A = '''main''' # Default branch name __A = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2''' # One particular commit (not the top of `main`) __A = '''aaaaaaa''' # This commit does not exist, so we should 404. __A = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684''' # Sha-1 of config.json on the top of `main`, for checking purposes __A = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3''' @contextlib.contextmanager def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: """simple docstring""" print('Welcome!' ) yield print('Bye!' ) @contextlib.contextmanager def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]: """simple docstring""" print('Bonjour!' ) yield print('Au revoir!' ) class a_ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" assert transformers.__spec__ is not None assert importlib.util.find_spec('transformers') is not None class a_ ( unittest.TestCase ): @unittest.mock.patch('sys.stdout' , new_callable=io.StringIO) def SCREAMING_SNAKE_CASE__ (self , __a) -> int: """simple docstring""" with ContextManagers([]): print('Transformers are awesome!') # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue() , 'Transformers are awesome!\n') @unittest.mock.patch('sys.stdout' , new_callable=io.StringIO) def SCREAMING_SNAKE_CASE__ (self , __a) -> List[str]: """simple docstring""" with ContextManagers([context_en()]): print('Transformers are awesome!') # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue() , 'Welcome!\nTransformers are awesome!\nBye!\n') @unittest.mock.patch('sys.stdout' , new_callable=io.StringIO) def SCREAMING_SNAKE_CASE__ (self , __a) -> Tuple: """simple docstring""" with ContextManagers([context_fr(), context_en()]): print('Transformers are awesome!') # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue() , 'Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n') @require_torch def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" self.assertEqual(find_labels(__a) , ['labels']) self.assertEqual(find_labels(__a) , ['labels', 'next_sentence_label']) self.assertEqual(find_labels(__a) , ['start_positions', 'end_positions']) class a_ ( UpperCamelCase_ ): pass self.assertEqual(find_labels(__a) , ['labels']) @require_tf def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" self.assertEqual(find_labels(__a) , ['labels']) self.assertEqual(find_labels(__a) , ['labels', 'next_sentence_label']) self.assertEqual(find_labels(__a) , ['start_positions', 'end_positions']) class a_ ( UpperCamelCase_ ): pass self.assertEqual(find_labels(__a) , ['labels']) @require_flax def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" self.assertEqual(find_labels(__a) , []) self.assertEqual(find_labels(__a) , []) self.assertEqual(find_labels(__a) , []) class a_ ( UpperCamelCase_ ): pass self.assertEqual(find_labels(__a) , [])
61
1
'''simple docstring''' import warnings from transformers import AutoTokenizer from transformers.utils import is_torch_available from transformers.utils.generic import ExplicitEnum from ...processing_utils import ProcessorMixin if is_torch_available(): import torch class a_ ( UpperCamelCase_ ): _snake_case = """char""" _snake_case = """bpe""" _snake_case = """wp""" __A = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class a_ ( UpperCamelCase_ ): _snake_case = ["""image_processor""", """char_tokenizer"""] _snake_case = """ViTImageProcessor""" _snake_case = """MgpstrTokenizer""" def __init__(self , __a=None , __a=None , **__a) -> Optional[Any]: """simple docstring""" __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.' , __a , ) __snake_case : List[Any] = kwargs.pop('feature_extractor') __snake_case : str = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.') if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.') __snake_case : Tuple = tokenizer __snake_case : Any = AutoTokenizer.from_pretrained('gpt2') __snake_case : List[str] = AutoTokenizer.from_pretrained('bert-base-uncased') super().__init__(__a , __a) def __call__(self , __a=None , __a=None , __a=None , **__a) -> Optional[Any]: """simple docstring""" if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.') if images is not None: __snake_case : Union[str, Any] = self.image_processor(__a , return_tensors=__a , **__a) if text is not None: __snake_case : Dict = self.char_tokenizer(__a , return_tensors=__a , **__a) if text is None: return inputs elif images is None: return encodings else: __snake_case : Union[str, Any] = encodings['input_ids'] return inputs def SCREAMING_SNAKE_CASE__ (self , __a) -> Union[str, Any]: """simple docstring""" __snake_case ,__snake_case ,__snake_case : List[str] = sequences __snake_case : int = char_preds.size(0) __snake_case ,__snake_case : str = self._decode_helper(__a , 'char') __snake_case ,__snake_case : List[str] = self._decode_helper(__a , 'bpe') __snake_case ,__snake_case : List[str] = self._decode_helper(__a , 'wp') __snake_case : Any = [] __snake_case : List[str] = [] for i in range(__a): __snake_case : Union[str, Any] = [char_scores[i], bpe_scores[i], wp_scores[i]] __snake_case : Any = [char_strs[i], bpe_strs[i], wp_strs[i]] __snake_case : List[str] = scores.index(max(__a)) final_strs.append(strs[max_score_index]) final_scores.append(scores[max_score_index]) __snake_case : str = {} __snake_case : Optional[Any] = final_strs __snake_case : str = final_scores __snake_case : Tuple = char_strs __snake_case : str = bpe_strs __snake_case : Any = wp_strs return out def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> str: """simple docstring""" if format == DecodeType.CHARACTER: __snake_case : str = self.char_decode __snake_case : Union[str, Any] = 1 __snake_case : Union[str, Any] = '[s]' elif format == DecodeType.BPE: __snake_case : Tuple = self.bpe_decode __snake_case : str = 2 __snake_case : Any = '#' elif format == DecodeType.WORDPIECE: __snake_case : Any = self.wp_decode __snake_case : Tuple = 1_0_2 __snake_case : Dict = '[SEP]' else: raise ValueError(F"""Format {format} is not supported.""") __snake_case ,__snake_case : Tuple = [], [] __snake_case : List[str] = pred_logits.size(0) __snake_case : Optional[Any] = pred_logits.size(1) __snake_case ,__snake_case : str = pred_logits.topk(1 , dim=-1 , largest=__a , sorted=__a) __snake_case : Optional[Any] = preds_index.view(-1 , __a)[:, 1:] __snake_case : Optional[Any] = decoder(__a) __snake_case ,__snake_case : str = torch.nn.functional.softmax(__a , dim=2).max(dim=2) __snake_case : Union[str, Any] = preds_max_prob[:, 1:] for index in range(__a): __snake_case : List[Any] = preds_str[index].find(__a) __snake_case : List[Any] = preds_str[index][:pred_eos] __snake_case : Union[str, Any] = preds_index[index].cpu().tolist() __snake_case : str = pred_index.index(__a) if eos_token in pred_index else -1 __snake_case : Any = preds_max_prob[index][: pred_eos_index + 1] __snake_case : Dict = pred_max_prob.cumprod(dim=0)[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(__a) conf_scores.append(__a) return dec_strs, conf_scores def SCREAMING_SNAKE_CASE__ (self , __a) -> str: """simple docstring""" __snake_case : List[Any] = [seq.replace(' ' , '') for seq in self.char_tokenizer.batch_decode(__a)] return decode_strs def SCREAMING_SNAKE_CASE__ (self , __a) -> Optional[int]: """simple docstring""" return self.bpe_tokenizer.batch_decode(__a) def SCREAMING_SNAKE_CASE__ (self , __a) -> int: """simple docstring""" __snake_case : Optional[Any] = [seq.replace(' ' , '') for seq in self.wp_tokenizer.batch_decode(__a)] return decode_strs
61
'''simple docstring''' # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A = {'''configuration_timm_backbone''': ['''TimmBackboneConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ['''TimmBackbone'''] if TYPE_CHECKING: from .configuration_timm_backbone import TimmBackboneConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timm_backbone import TimmBackbone else: import sys __A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
61
1
'''simple docstring''' import csv from collections import defaultdict from dataclasses import dataclass, field from typing import List, Optional import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import ScalarFormatter from transformers import HfArgumentParser def _SCREAMING_SNAKE_CASE ( A : int=None , A : Union[str, Any]=None ) -> List[Any]: """simple docstring""" return field(default_factory=lambda: default , metadata=A ) @dataclass class a_ : _snake_case = field( metadata={"""help""": """The csv file to plot."""} , ) _snake_case = field( default=UpperCamelCase_ , metadata={"""help""": """Whether to plot along batch size or sequence length. Defaults to sequence length."""} , ) _snake_case = field( default=UpperCamelCase_ , metadata={"""help""": """Whether the csv file has time results or memory results. Defaults to memory results."""} , ) _snake_case = field( default=UpperCamelCase_ , metadata={"""help""": """Disable logarithmic scale when plotting"""} , ) _snake_case = field( default=UpperCamelCase_ , metadata={ """help""": """Whether the csv file has training results or inference results. Defaults to inference results.""" } , ) _snake_case = field( default=UpperCamelCase_ , metadata={"""help""": """Filename under which the plot will be saved. If unused no plot is saved."""} , ) _snake_case = list_field( default=UpperCamelCase_ , metadata={"""help""": """List of model names that are used instead of the ones in the csv file."""} ) def _SCREAMING_SNAKE_CASE ( A : Any ) -> Any: """simple docstring""" try: int(A ) return True except ValueError: return False def _SCREAMING_SNAKE_CASE ( A : Optional[Any] ) -> int: """simple docstring""" try: float(A ) return True except ValueError: return False class a_ : def __init__(self , __a) -> List[str]: """simple docstring""" __snake_case : str = args __snake_case : Optional[int] = defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}}) with open(self.args.csv_file , newline='') as csv_file: __snake_case : Any = csv.DictReader(__a) for row in reader: __snake_case : List[Any] = row['model'] self.result_dict[model_name]["bsz"].append(int(row['batch_size'])) self.result_dict[model_name]["seq_len"].append(int(row['sequence_length'])) if can_convert_to_int(row['result']): # value is not None __snake_case : str = int(row['result']) elif can_convert_to_float(row['result']): # value is not None __snake_case : Tuple = float(row['result']) def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" __snake_case ,__snake_case : str = plt.subplots() __snake_case : Union[str, Any] = 'Time usage' if self.args.is_time else 'Memory usage' __snake_case : Union[str, Any] = title_str + ' for training' if self.args.is_train else title_str + ' for inference' if not self.args.no_log_scale: # set logarithm scales ax.set_xscale('log') ax.set_yscale('log') for axis in [ax.xaxis, ax.yaxis]: axis.set_major_formatter(ScalarFormatter()) for model_name_idx, model_name in enumerate(self.result_dict.keys()): __snake_case : Dict = sorted(set(self.result_dict[model_name]['bsz'])) __snake_case : Union[str, Any] = sorted(set(self.result_dict[model_name]['seq_len'])) __snake_case : str = self.result_dict[model_name]['result'] ((__snake_case) ,(__snake_case)) : int = ( (batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes) ) __snake_case : Optional[int] = ( model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx] ) for inner_loop_value in inner_loop_array: if self.args.plot_along_batch: __snake_case : str = np.asarray( [results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results] , dtype=__a , ) else: __snake_case : Optional[Any] = np.asarray( [results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results] , dtype=np.floataa , ) ((__snake_case) ,(__snake_case)) : Dict = ( ('batch_size', 'len') if self.args.plot_along_batch else ('in #tokens', 'bsz') ) __snake_case : Tuple = np.asarray(__a , __a)[: len(__a)] plt.scatter( __a , __a , label=F"""{label_model_name} - {inner_loop_label}: {inner_loop_value}""") plt.plot(__a , __a , '--') title_str += F""" {label_model_name} vs.""" __snake_case : List[Any] = title_str[:-4] __snake_case : List[str] = 'Time in s' if self.args.is_time else 'Memory in MB' # plot plt.title(__a) plt.xlabel(__a) plt.ylabel(__a) plt.legend() if self.args.figure_png_file is not None: plt.savefig(self.args.figure_png_file) else: plt.show() def _SCREAMING_SNAKE_CASE ( ) -> List[str]: """simple docstring""" __snake_case : int = HfArgumentParser(A ) __snake_case : Optional[Any] = parser.parse_args_into_dataclasses()[0] __snake_case : Optional[Any] = Plot(args=A ) plot.plot() if __name__ == "__main__": main()
61
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( A : int ) -> int: """simple docstring""" __snake_case : str = 1 for i in range(1 , num + 1 ): fact *= i return fact def _SCREAMING_SNAKE_CASE ( A : int ) -> int: """simple docstring""" __snake_case : Union[str, Any] = 0 while number > 0: __snake_case : Dict = number % 10 sum_of_digits += last_digit __snake_case : Union[str, Any] = number // 10 # Removing the last_digit from the given number return sum_of_digits def _SCREAMING_SNAKE_CASE ( A : int = 1_00 ) -> int: """simple docstring""" __snake_case : List[Any] = factorial(A ) __snake_case : Dict = split_and_add(A ) return result if __name__ == "__main__": print(solution(int(input('''Enter the Number: ''').strip())))
61
1
'''simple docstring''' import warnings from ...utils import logging from .image_processing_dpt import DPTImageProcessor __A = logging.get_logger(__name__) class a_ ( UpperCamelCase_ ): def __init__(self , *__a , **__a) -> None: """simple docstring""" warnings.warn( 'The class DPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use DPTImageProcessor instead.' , __a , ) super().__init__(*__a , **__a)
61
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor class a_ ( unittest.TestCase ): def __init__(self , __a , __a=7 , __a=3 , __a=1_8 , __a=3_0 , __a=4_0_0 , __a=True , __a=None , __a=True , __a=None , __a=True , __a=[0.48_145_466, 0.4_578_275, 0.40_821_073] , __a=[0.26_862_954, 0.26_130_258, 0.27_577_711] , __a=True , ) -> List[Any]: """simple docstring""" __snake_case : Tuple = size if size is not None else {'height': 2_2_4, 'width': 2_2_4} __snake_case : Any = crop_size if crop_size is not None else {'height': 1_8, 'width': 1_8} __snake_case : Optional[int] = parent __snake_case : Dict = batch_size __snake_case : str = num_channels __snake_case : Optional[Any] = image_size __snake_case : Optional[int] = min_resolution __snake_case : Tuple = max_resolution __snake_case : Optional[int] = do_resize __snake_case : Optional[int] = size __snake_case : Union[str, Any] = do_center_crop __snake_case : List[Any] = crop_size __snake_case : int = do_normalize __snake_case : Optional[Any] = image_mean __snake_case : str = image_std __snake_case : Optional[Any] = do_convert_rgb def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def SCREAMING_SNAKE_CASE__ (self , __a=False , __a=False , __a=False) -> List[str]: """simple docstring""" assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" if equal_resolution: __snake_case : Optional[int] = [] for i in range(self.batch_size): image_inputs.append( np.random.randint( 2_5_5 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta)) else: __snake_case : Dict = [] for i in range(self.batch_size): __snake_case ,__snake_case : Optional[Any] = np.random.choice(np.arange(self.min_resolution , self.max_resolution) , 2) image_inputs.append(np.random.randint(2_5_5 , size=(self.num_channels, width, height) , dtype=np.uinta)) if not numpify and not torchify: # PIL expects the channel dimension as last dimension __snake_case : int = [Image.fromarray(np.moveaxis(__a , 0 , -1)) for x in image_inputs] if torchify: __snake_case : List[Any] = [torch.from_numpy(__a) for x in image_inputs] return image_inputs @require_torch @require_vision class a_ ( UpperCamelCase_ , unittest.TestCase ): _snake_case = ChineseCLIPImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : Union[str, Any] = ChineseCLIPImageProcessingTester(self , do_center_crop=__a) @property def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : int = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(__a , 'do_resize')) self.assertTrue(hasattr(__a , 'size')) self.assertTrue(hasattr(__a , 'do_center_crop')) self.assertTrue(hasattr(__a , 'center_crop')) self.assertTrue(hasattr(__a , 'do_normalize')) self.assertTrue(hasattr(__a , 'image_mean')) self.assertTrue(hasattr(__a , 'image_std')) self.assertTrue(hasattr(__a , 'do_convert_rgb')) def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size , {'height': 2_2_4, 'width': 2_2_4}) self.assertEqual(image_processor.crop_size , {'height': 1_8, 'width': 1_8}) __snake_case : List[str] = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 , crop_size=8_4) self.assertEqual(image_processor.size , {'shortest_edge': 4_2}) self.assertEqual(image_processor.crop_size , {'height': 8_4, 'width': 8_4}) def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" __snake_case : List[Any] = self.image_processing_class(**self.image_processor_dict) # create random PIL images __snake_case : Optional[Any] = self.image_processor_tester.prepare_inputs(equal_resolution=__a) for image in image_inputs: self.assertIsInstance(__a , Image.Image) # Test not batched input __snake_case : 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __snake_case : List[Any] = image_processing(__a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" __snake_case : Union[str, Any] = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors __snake_case : Optional[int] = self.image_processor_tester.prepare_inputs(equal_resolution=__a , numpify=__a) for image in image_inputs: self.assertIsInstance(__a , np.ndarray) # Test not batched input __snake_case : List[Any] = image_processing(image_inputs[0] , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __snake_case : int = image_processing(__a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : Any = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors __snake_case : Tuple = self.image_processor_tester.prepare_inputs(equal_resolution=__a , torchify=__a) for image in image_inputs: self.assertIsInstance(__a , torch.Tensor) # Test not batched input __snake_case : Any = image_processing(image_inputs[0] , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __snake_case : Union[str, Any] = image_processing(__a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) @require_torch @require_vision class a_ ( UpperCamelCase_ , unittest.TestCase ): _snake_case = ChineseCLIPImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" __snake_case : Optional[Any] = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=__a) __snake_case : List[Any] = 3 @property def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : Any = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(__a , 'do_resize')) self.assertTrue(hasattr(__a , 'size')) self.assertTrue(hasattr(__a , 'do_center_crop')) self.assertTrue(hasattr(__a , 'center_crop')) self.assertTrue(hasattr(__a , 'do_normalize')) self.assertTrue(hasattr(__a , 'image_mean')) self.assertTrue(hasattr(__a , 'image_std')) self.assertTrue(hasattr(__a , 'do_convert_rgb')) def SCREAMING_SNAKE_CASE__ (self) -> Tuple: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : List[Any] = self.image_processing_class(**self.image_processor_dict) # create random PIL images __snake_case : Union[str, Any] = self.image_processor_tester.prepare_inputs(equal_resolution=__a) for image in image_inputs: self.assertIsInstance(__a , Image.Image) # Test not batched input __snake_case : Optional[int] = image_processing(image_inputs[0] , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __snake_case : Optional[int] = image_processing(__a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , )
61
1
'''simple docstring''' import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class a_ ( UpperCamelCase_ ): _snake_case = (DEISMultistepScheduler,) _snake_case = (("""num_inference_steps""", 25),) def SCREAMING_SNAKE_CASE__ (self , **__a) -> List[Any]: """simple docstring""" __snake_case : Optional[int] = { 'num_train_timesteps': 1_0_0_0, 'beta_start': 0.0_001, 'beta_end': 0.02, 'beta_schedule': 'linear', 'solver_order': 2, } config.update(**__a) return config def SCREAMING_SNAKE_CASE__ (self , __a=0 , **__a) -> Optional[int]: """simple docstring""" __snake_case : Union[str, Any] = dict(self.forward_default_kwargs) __snake_case : Optional[int] = kwargs.pop('num_inference_steps' , __a) __snake_case : List[Any] = self.dummy_sample __snake_case : Optional[int] = 0.1 * sample __snake_case : Tuple = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: __snake_case : Optional[int] = self.get_scheduler_config(**__a) __snake_case : int = scheduler_class(**__a) scheduler.set_timesteps(__a) # copy over dummy past residuals __snake_case : Optional[Any] = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__a) __snake_case : Optional[int] = scheduler_class.from_pretrained(__a) new_scheduler.set_timesteps(__a) # copy over dummy past residuals __snake_case : Optional[Any] = dummy_past_residuals[: new_scheduler.config.solver_order] __snake_case ,__snake_case : int = sample, sample for t in range(__a , time_step + scheduler.config.solver_order + 1): __snake_case : Tuple = scheduler.step(__a , __a , __a , **__a).prev_sample __snake_case : List[str] = new_scheduler.step(__a , __a , __a , **__a).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1E-5, "Scheduler outputs are not identical" def SCREAMING_SNAKE_CASE__ (self) -> Tuple: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self , __a=0 , **__a) -> Any: """simple docstring""" __snake_case : Optional[Any] = dict(self.forward_default_kwargs) __snake_case : str = kwargs.pop('num_inference_steps' , __a) __snake_case : Any = self.dummy_sample __snake_case : List[Any] = 0.1 * sample __snake_case : Optional[Any] = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: __snake_case : Tuple = self.get_scheduler_config() __snake_case : Any = scheduler_class(**__a) scheduler.set_timesteps(__a) # copy over dummy past residuals (must be after setting timesteps) __snake_case : int = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__a) __snake_case : Optional[int] = scheduler_class.from_pretrained(__a) # copy over dummy past residuals new_scheduler.set_timesteps(__a) # copy over dummy past residual (must be after setting timesteps) __snake_case : Tuple = dummy_past_residuals[: new_scheduler.config.solver_order] __snake_case : Dict = scheduler.step(__a , __a , __a , **__a).prev_sample __snake_case : Tuple = new_scheduler.step(__a , __a , __a , **__a).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1E-5, "Scheduler outputs are not identical" def SCREAMING_SNAKE_CASE__ (self , __a=None , **__a) -> Optional[Any]: """simple docstring""" if scheduler is None: __snake_case : Dict = self.scheduler_classes[0] __snake_case : Tuple = self.get_scheduler_config(**__a) __snake_case : Optional[int] = scheduler_class(**__a) __snake_case : Optional[Any] = self.scheduler_classes[0] __snake_case : Optional[Any] = self.get_scheduler_config(**__a) __snake_case : int = scheduler_class(**__a) __snake_case : Any = 1_0 __snake_case : Optional[Any] = self.dummy_model() __snake_case : str = self.dummy_sample_deter scheduler.set_timesteps(__a) for i, t in enumerate(scheduler.timesteps): __snake_case : Tuple = model(__a , __a) __snake_case : Optional[Any] = scheduler.step(__a , __a , __a).prev_sample return sample def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" __snake_case : List[Any] = dict(self.forward_default_kwargs) __snake_case : str = kwargs.pop('num_inference_steps' , __a) for scheduler_class in self.scheduler_classes: __snake_case : Any = self.get_scheduler_config() __snake_case : Optional[int] = scheduler_class(**__a) __snake_case : Dict = self.dummy_sample __snake_case : Dict = 0.1 * sample if num_inference_steps is not None and hasattr(__a , 'set_timesteps'): scheduler.set_timesteps(__a) elif num_inference_steps is not None and not hasattr(__a , 'set_timesteps'): __snake_case : str = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) __snake_case : Any = [residual + 0.2, residual + 0.15, residual + 0.10] __snake_case : List[Any] = dummy_past_residuals[: scheduler.config.solver_order] __snake_case : Union[str, Any] = scheduler.timesteps[5] __snake_case : List[str] = scheduler.timesteps[6] __snake_case : Optional[Any] = scheduler.step(__a , __a , __a , **__a).prev_sample __snake_case : List[Any] = scheduler.step(__a , __a , __a , **__a).prev_sample self.assertEqual(output_a.shape , sample.shape) self.assertEqual(output_a.shape , output_a.shape) def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : Optional[int] = DEISMultistepScheduler(**self.get_scheduler_config()) __snake_case : Dict = self.full_loop(scheduler=__a) __snake_case : Any = torch.mean(torch.abs(__a)) assert abs(result_mean.item() - 0.23_916) < 1E-3 __snake_case : Dict = DPMSolverSinglestepScheduler.from_config(scheduler.config) __snake_case : Union[str, Any] = DPMSolverMultistepScheduler.from_config(scheduler.config) __snake_case : Tuple = UniPCMultistepScheduler.from_config(scheduler.config) __snake_case : Dict = DEISMultistepScheduler.from_config(scheduler.config) __snake_case : Dict = self.full_loop(scheduler=__a) __snake_case : List[str] = torch.mean(torch.abs(__a)) assert abs(result_mean.item() - 0.23_916) < 1E-3 def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" for timesteps in [2_5, 5_0, 1_0_0, 9_9_9, 1_0_0_0]: self.check_over_configs(num_train_timesteps=__a) def SCREAMING_SNAKE_CASE__ (self) -> Tuple: """simple docstring""" self.check_over_configs(thresholding=__a) for order in [1, 2, 3]: for solver_type in ["logrho"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=__a , prediction_type=__a , sample_max_value=__a , algorithm_type='deis' , solver_order=__a , solver_type=__a , ) def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__a) def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]: """simple docstring""" for algorithm_type in ["deis"]: for solver_type in ["logrho"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=__a , solver_type=__a , prediction_type=__a , algorithm_type=__a , ) __snake_case : Dict = self.full_loop( solver_order=__a , solver_type=__a , prediction_type=__a , algorithm_type=__a , ) assert not torch.isnan(__a).any(), "Samples have nan numbers" def SCREAMING_SNAKE_CASE__ (self) -> Any: """simple docstring""" self.check_over_configs(lower_order_final=__a) self.check_over_configs(lower_order_final=__a) def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" for num_inference_steps in [1, 2, 3, 5, 1_0, 5_0, 1_0_0, 9_9_9, 1_0_0_0]: self.check_over_forward(num_inference_steps=__a , time_step=0) def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" __snake_case : List[Any] = self.full_loop() __snake_case : Optional[Any] = torch.mean(torch.abs(__a)) assert abs(result_mean.item() - 0.23_916) < 1E-3 def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : List[str] = self.full_loop(prediction_type='v_prediction') __snake_case : Tuple = torch.mean(torch.abs(__a)) assert abs(result_mean.item() - 0.091) < 1E-3 def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" __snake_case : List[str] = self.scheduler_classes[0] __snake_case : int = self.get_scheduler_config(thresholding=__a , dynamic_thresholding_ratio=0) __snake_case : Union[str, Any] = scheduler_class(**__a) __snake_case : List[str] = 1_0 __snake_case : Dict = self.dummy_model() __snake_case : str = self.dummy_sample_deter.half() scheduler.set_timesteps(__a) for i, t in enumerate(scheduler.timesteps): __snake_case : List[Any] = model(__a , __a) __snake_case : Dict = scheduler.step(__a , __a , __a).prev_sample assert sample.dtype == torch.floataa
61
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { '''sayakpaul/vit-msn-base''': '''https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json''', # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class a_ ( UpperCamelCase_ ): _snake_case = """vit_msn""" def __init__(self , __a=7_6_8 , __a=1_2 , __a=1_2 , __a=3_0_7_2 , __a="gelu" , __a=0.0 , __a=0.0 , __a=0.02 , __a=1E-06 , __a=2_2_4 , __a=1_6 , __a=3 , __a=True , **__a , ) -> Any: """simple docstring""" super().__init__(**__a) __snake_case : List[str] = hidden_size __snake_case : Optional[int] = num_hidden_layers __snake_case : Optional[Any] = num_attention_heads __snake_case : str = intermediate_size __snake_case : List[str] = hidden_act __snake_case : List[Any] = hidden_dropout_prob __snake_case : Tuple = attention_probs_dropout_prob __snake_case : List[str] = initializer_range __snake_case : Optional[int] = layer_norm_eps __snake_case : Dict = image_size __snake_case : int = patch_size __snake_case : Dict = num_channels __snake_case : Tuple = qkv_bias
61
1
'''simple docstring''' import datasets from .nmt_bleu import compute_bleu # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py __A = '''\ @INPROCEEDINGS{Papineni02bleu:a, author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu}, title = {BLEU: a Method for Automatic Evaluation of Machine Translation}, booktitle = {}, year = {2002}, pages = {311--318} } @inproceedings{lin-och-2004-orange, title = "{ORANGE}: a Method for Evaluating Automatic Evaluation Metrics for Machine Translation", author = "Lin, Chin-Yew and Och, Franz Josef", booktitle = "{COLING} 2004: Proceedings of the 20th International Conference on Computational Linguistics", month = "aug 23{--}aug 27", year = "2004", address = "Geneva, Switzerland", publisher = "COLING", url = "https://www.aclweb.org/anthology/C04-1072", pages = "501--507", } ''' __A = '''\ BLEU (bilingual evaluation understudy) is an algorithm for evaluating the quality of text which has been machine-translated from one natural language to another. Quality is considered to be the correspondence between a machine\'s output and that of a human: "the closer a machine translation is to a professional human translation, the better it is" – this is the central idea behind BLEU. BLEU was one of the first metrics to claim a high correlation with human judgements of quality, and remains one of the most popular automated and inexpensive metrics. Scores are calculated for individual translated segments—generally sentences—by comparing them with a set of good quality reference translations. Those scores are then averaged over the whole corpus to reach an estimate of the translation\'s overall quality. Intelligibility or grammatical correctness are not taken into account[citation needed]. BLEU\'s output is always a number between 0 and 1. This value indicates how similar the candidate text is to the reference texts, with values closer to 1 representing more similar texts. Few human translations will attain a score of 1, since this would indicate that the candidate is identical to one of the reference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additional reference translations will increase the BLEU score. ''' __A = ''' Computes BLEU score of translated segments against one or more references. Args: predictions: list of translations to score. Each translation should be tokenized into a list of tokens. references: list of lists of references for each translation. Each reference should be tokenized into a list of tokens. max_order: Maximum n-gram order to use when computing BLEU score. smooth: Whether or not to apply Lin et al. 2004 smoothing. Returns: \'bleu\': bleu score, \'precisions\': geometric mean of n-gram precisions, \'brevity_penalty\': brevity penalty, \'length_ratio\': ratio of lengths, \'translation_length\': translation_length, \'reference_length\': reference_length Examples: >>> predictions = [ ... ["hello", "there", "general", "kenobi"], # tokenized prediction of the first sample ... ["foo", "bar", "foobar"] # tokenized prediction of the second sample ... ] >>> references = [ ... [["hello", "there", "general", "kenobi"], ["hello", "there", "!"]], # tokenized references for the first sample (2 references) ... [["foo", "bar", "foobar"]] # tokenized references for the second sample (1 reference) ... ] >>> bleu = datasets.load_metric("bleu") >>> results = bleu.compute(predictions=predictions, references=references) >>> print(results["bleu"]) 1.0 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('string' , id='token') , id='sequence'), 'references': datasets.Sequence( datasets.Sequence(datasets.Value('string' , id='token') , id='sequence') , id='references'), }) , codebase_urls=['https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py'] , reference_urls=[ 'https://en.wikipedia.org/wiki/BLEU', 'https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213', ] , ) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a=4 , __a=False) -> Any: """simple docstring""" __snake_case : Dict = compute_bleu( reference_corpus=__a , translation_corpus=__a , max_order=__a , smooth=__a) ((__snake_case) ,(__snake_case) ,(__snake_case) ,(__snake_case) ,(__snake_case) ,(__snake_case)) : Dict = score return { "bleu": bleu, "precisions": precisions, "brevity_penalty": bp, "length_ratio": ratio, "translation_length": translation_length, "reference_length": reference_length, }
61
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( A : float , A : list[float] ) -> float: """simple docstring""" if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) __snake_case : List[str] = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(A ) ) return round(A , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
61
1
'''simple docstring''' import random def _SCREAMING_SNAKE_CASE ( A : Dict , A : List[str] , A : Optional[int] ) -> List[str]: """simple docstring""" __snake_case : str = a[left_index] __snake_case : List[str] = left_index + 1 for j in range(left_index + 1 , A ): if a[j] < pivot: __snake_case ,__snake_case : Dict = a[i], a[j] i += 1 __snake_case ,__snake_case : Dict = a[i - 1], a[left_index] return i - 1 def _SCREAMING_SNAKE_CASE ( A : int , A : Any , A : Tuple ) -> List[str]: """simple docstring""" if left < right: __snake_case : Any = random.randint(A , right - 1 ) __snake_case ,__snake_case : Optional[Any] = ( a[left], a[pivot], ) # switches the pivot with the left most bound __snake_case : Optional[Any] = partition(A , A , A ) quick_sort_random( A , A , A ) # recursive quicksort to the left of the pivot point quick_sort_random( A , pivot_index + 1 , A ) # recursive quicksort to the right of the pivot point def _SCREAMING_SNAKE_CASE ( ) -> Any: """simple docstring""" __snake_case : int = input('Enter numbers separated by a comma:\n' ).strip() __snake_case : str = [int(A ) for item in user_input.split(',' )] quick_sort_random(A , 0 , len(A ) ) print(A ) if __name__ == "__main__": main()
61
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __A = { '''configuration_distilbert''': [ '''DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DistilBertConfig''', '''DistilBertOnnxConfig''', ], '''tokenization_distilbert''': ['''DistilBertTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ['''DistilBertTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ '''DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''DistilBertForMaskedLM''', '''DistilBertForMultipleChoice''', '''DistilBertForQuestionAnswering''', '''DistilBertForSequenceClassification''', '''DistilBertForTokenClassification''', '''DistilBertModel''', '''DistilBertPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ '''TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFDistilBertForMaskedLM''', '''TFDistilBertForMultipleChoice''', '''TFDistilBertForQuestionAnswering''', '''TFDistilBertForSequenceClassification''', '''TFDistilBertForTokenClassification''', '''TFDistilBertMainLayer''', '''TFDistilBertModel''', '''TFDistilBertPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ '''FlaxDistilBertForMaskedLM''', '''FlaxDistilBertForMultipleChoice''', '''FlaxDistilBertForQuestionAnswering''', '''FlaxDistilBertForSequenceClassification''', '''FlaxDistilBertForTokenClassification''', '''FlaxDistilBertModel''', '''FlaxDistilBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_distilbert import ( DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DistilBertConfig, DistilBertOnnxConfig, ) from .tokenization_distilbert import DistilBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_distilbert_fast import DistilBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_distilbert import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, DistilBertPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertMainLayer, TFDistilBertModel, TFDistilBertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, FlaxDistilBertPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
61
1
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( A : int ) -> int: """simple docstring""" __snake_case : str = 1 for i in range(1 , num + 1 ): fact *= i return fact def _SCREAMING_SNAKE_CASE ( A : int ) -> int: """simple docstring""" __snake_case : Union[str, Any] = 0 while number > 0: __snake_case : Dict = number % 10 sum_of_digits += last_digit __snake_case : Union[str, Any] = number // 10 # Removing the last_digit from the given number return sum_of_digits def _SCREAMING_SNAKE_CASE ( A : int = 1_00 ) -> int: """simple docstring""" __snake_case : List[Any] = factorial(A ) __snake_case : Dict = split_and_add(A ) return result if __name__ == "__main__": print(solution(int(input('''Enter the Number: ''').strip())))
61
'''simple docstring''' # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. __A = abspath(join(dirname(dirname(__file__)), '''src''')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='''ignore''', category=FutureWarning) def _SCREAMING_SNAKE_CASE ( A : Tuple ) -> str: """simple docstring""" from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(A ) def _SCREAMING_SNAKE_CASE ( A : int ) -> Optional[int]: """simple docstring""" from diffusers.utils.testing_utils import pytest_terminal_summary_main __snake_case : Any = terminalreporter.config.getoption('--make-reports' ) if make_reports: pytest_terminal_summary_main(A , id=A )
61
1
'''simple docstring''' from __future__ import annotations def _SCREAMING_SNAKE_CASE ( A : list[int] , A : list[int] , A : int ) -> tuple[float, list[float]]: """simple docstring""" __snake_case : Any = list(range(len(A ) ) ) __snake_case : Optional[int] = [v / w for v, w in zip(A , A )] index.sort(key=lambda A : ratio[i] , reverse=A ) __snake_case : float = 0 __snake_case : list[float] = [0] * len(A ) for i in index: if weight[i] <= capacity: __snake_case : Union[str, Any] = 1 max_value += value[i] capacity -= weight[i] else: __snake_case : Optional[Any] = capacity / weight[i] max_value += value[i] * capacity / weight[i] break return max_value, fractions if __name__ == "__main__": import doctest doctest.testmod()
61
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __A = { '''configuration_biogpt''': ['''BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BioGptConfig'''], '''tokenization_biogpt''': ['''BioGptTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ '''BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BioGptForCausalLM''', '''BioGptForTokenClassification''', '''BioGptForSequenceClassification''', '''BioGptModel''', '''BioGptPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
61
1
'''simple docstring''' from __future__ import annotations from collections.abc import Callable def _SCREAMING_SNAKE_CASE ( A : Callable[[int | float], int | float] , A : int | float , A : int | float , A : int = 1_00 , ) -> float: """simple docstring""" __snake_case : str = x_start __snake_case : Union[str, Any] = fnc(A ) __snake_case : Union[str, Any] = 0.0 for _ in range(A ): # Approximates small segments of curve as linear and solve # for trapezoidal area __snake_case : Any = (x_end - x_start) / steps + xa __snake_case : Tuple = fnc(A ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step __snake_case : Tuple = xa __snake_case : Dict = fxa return area if __name__ == "__main__": def _SCREAMING_SNAKE_CASE ( A : List[Any] ) -> List[Any]: """simple docstring""" return x**3 + x**2 print('''f(x) = x^3 + x^2''') print('''The area between the curve, x = -5, x = 5 and the x axis is:''') __A = 1_0 while i <= 1_0_0_0_0_0: print(f'''with {i} steps: {trapezoidal_area(f, -5, 5, i)}''') i *= 1_0
61
'''simple docstring''' from packaging import version from .import_utils import is_accelerate_available if is_accelerate_available(): import accelerate def _SCREAMING_SNAKE_CASE ( A : Optional[Any] ) -> int: """simple docstring""" if not is_accelerate_available(): return method __snake_case : Optional[Any] = version.parse(accelerate.__version__ ).base_version if version.parse(A ) < version.parse('0.17.0' ): return method def wrapper(self : Optional[Any] , *A : Optional[Any] , **A : Optional[int] ): if hasattr(self , '_hf_hook' ) and hasattr(self._hf_hook , 'pre_forward' ): self._hf_hook.pre_forward(self ) return method(self , *A , **A ) return wrapper
61
1
'''simple docstring''' from __future__ import annotations from random import random class a_ : def __init__(self , __a = None) -> Optional[Any]: """simple docstring""" __snake_case : Optional[Any] = value __snake_case : List[str] = random() __snake_case : Node | None = None __snake_case : Node | None = None def __repr__(self) -> str: """simple docstring""" from pprint import pformat if self.left is None and self.right is None: return F"""'{self.value}: {self.prior:.5}'""" else: return pformat( {F"""{self.value}: {self.prior:.5}""": (self.left, self.right)} , indent=1) def __str__(self) -> str: """simple docstring""" __snake_case : Union[str, Any] = str(self.value) + ' ' __snake_case : str = str(self.left or '') __snake_case : str = str(self.right or '') return value + left + right def _SCREAMING_SNAKE_CASE ( A : Node | None , A : int ) -> tuple[Node | None, Node | None]: """simple docstring""" if root is None: # None tree is split into 2 Nones return None, None elif root.value is None: return None, None else: if value < root.value: __snake_case ,__snake_case : List[Any] = split(root.left , A ) return left, root else: __snake_case ,__snake_case : List[str] = split(root.right , A ) return root, right def _SCREAMING_SNAKE_CASE ( A : Node | None , A : Node | None ) -> Node | None: """simple docstring""" if (not left) or (not right): # If one node is None, return the other return left or right elif left.prior < right.prior: __snake_case : int = merge(left.right , A ) return left else: __snake_case : Tuple = merge(A , right.left ) return right def _SCREAMING_SNAKE_CASE ( A : Node | None , A : int ) -> Node | None: """simple docstring""" __snake_case : Dict = Node(A ) __snake_case ,__snake_case : Any = split(A , A ) return merge(merge(A , A ) , A ) def _SCREAMING_SNAKE_CASE ( A : Node | None , A : int ) -> Node | None: """simple docstring""" __snake_case ,__snake_case : Dict = split(A , value - 1 ) __snake_case ,__snake_case : str = split(A , A ) return merge(A , A ) def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> None: """simple docstring""" if not root: # None return else: inorder(root.left ) print(root.value , end=',' ) inorder(root.right ) def _SCREAMING_SNAKE_CASE ( A : Node | None , A : str ) -> Node | None: """simple docstring""" for arg in args.split(): if arg[0] == "+": __snake_case : List[str] = insert(A , int(arg[1:] ) ) elif arg[0] == "-": __snake_case : Any = erase(A , int(arg[1:] ) ) else: print('Unknown command' ) return root def _SCREAMING_SNAKE_CASE ( ) -> None: """simple docstring""" __snake_case : Any = None print( 'enter numbers to create a tree, + value to add value into treap, ' '- value to erase all nodes with value. \'q\' to quit. ' ) __snake_case : Union[str, Any] = input() while args != "q": __snake_case : List[Any] = interact_treap(A , A ) print(A ) __snake_case : Union[str, Any] = input() print('good by!' ) if __name__ == "__main__": import doctest doctest.testmod() main()
61
'''simple docstring''' import unittest from transformers import load_tool from transformers.utils import is_torch_available if is_torch_available(): import torch from transformers.testing_utils import require_torch from .test_tools_common import ToolTesterMixin @require_torch class a_ ( unittest.TestCase , UpperCamelCase_ ): def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" __snake_case : List[str] = load_tool('text-to-speech') self.tool.setup() def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]: """simple docstring""" torch.manual_seed(0) __snake_case : Dict = self.tool('hey') __snake_case : List[Any] = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485]) , )) def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" torch.manual_seed(0) __snake_case : Any = self.tool('hey') __snake_case : Any = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485]) , ))
61
1
'''simple docstring''' import doctest import glob import importlib import inspect import os import re from contextlib import contextmanager from functools import wraps from unittest.mock import patch import numpy as np import pytest from absl.testing import parameterized import datasets from datasets import load_metric from .utils import for_all_test_methods, local, slow # mark all tests as integration __A = pytest.mark.integration __A = {'''comet'''} __A = importlib.util.find_spec('''fairseq''') is not None __A = {'''code_eval'''} __A = os.name == '''nt''' __A = {'''bertscore''', '''frugalscore''', '''perplexity'''} __A = importlib.util.find_spec('''transformers''') is not None def _SCREAMING_SNAKE_CASE ( A : Dict ) -> int: """simple docstring""" @wraps(A ) def wrapper(self : Union[str, Any] , A : int ): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest('"test requires Fairseq"' ) else: test_case(self , A ) return wrapper def _SCREAMING_SNAKE_CASE ( A : Tuple ) -> Optional[Any]: """simple docstring""" @wraps(A ) def wrapper(self : Union[str, Any] , A : int ): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest('"test requires transformers"' ) else: test_case(self , A ) return wrapper def _SCREAMING_SNAKE_CASE ( A : List[str] ) -> str: """simple docstring""" @wraps(A ) def wrapper(self : List[str] , A : Optional[Any] ): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest('"test not supported on Windows"' ) else: test_case(self , A ) return wrapper def _SCREAMING_SNAKE_CASE ( ) -> str: """simple docstring""" __snake_case : str = [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob('./metrics/*/' )] return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished @parameterized.named_parameters(get_local_metric_names() ) @for_all_test_methods( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) @local class a_ ( parameterized.TestCase ): _snake_case = {} _snake_case = None @pytest.mark.filterwarnings('ignore:metric_module_factory is deprecated:FutureWarning') @pytest.mark.filterwarnings('ignore:load_metric is deprecated:FutureWarning') def SCREAMING_SNAKE_CASE__ (self , __a) -> int: """simple docstring""" __snake_case : int = '[...]' __snake_case : Union[str, Any] = importlib.import_module( datasets.load.metric_module_factory(os.path.join('metrics' , __a)).module_path) __snake_case : List[Any] = datasets.load.import_main_class(metric_module.__name__ , dataset=__a) # check parameters __snake_case : int = inspect.signature(metric._compute).parameters self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values())) # no **kwargs # run doctest with self.patch_intensive_calls(__a , metric_module.__name__): with self.use_local_metrics(): try: __snake_case : Optional[Any] = doctest.testmod(__a , verbose=__a , raise_on_error=__a) except doctest.UnexpectedException as e: raise e.exc_info[1] # raise the exception that doctest caught self.assertEqual(results.failed , 0) self.assertGreater(results.attempted , 1) @slow def SCREAMING_SNAKE_CASE__ (self , __a) -> List[str]: """simple docstring""" __snake_case : Dict = '[...]' __snake_case : str = importlib.import_module( datasets.load.metric_module_factory(os.path.join('metrics' , __a)).module_path) # run doctest with self.use_local_metrics(): __snake_case : Tuple = doctest.testmod(__a , verbose=__a , raise_on_error=__a) self.assertEqual(results.failed , 0) self.assertGreater(results.attempted , 1) @contextmanager def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> List[Any]: """simple docstring""" if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](__a): yield else: yield @contextmanager def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" def load_local_metric(__a , *__a , **__a): return load_metric(os.path.join('metrics' , __a) , *__a , **__a) with patch('datasets.load_metric') as mock_load_metric: __snake_case : int = load_local_metric yield @classmethod def SCREAMING_SNAKE_CASE__ (cls , __a) -> Any: """simple docstring""" def wrapper(__a): __snake_case : Optional[Any] = contextmanager(__a) __snake_case : Tuple = patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher('bleurt' ) def _SCREAMING_SNAKE_CASE ( A : Tuple ) -> str: """simple docstring""" import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string('sv' , '' , '' ) # handle pytest cli flags class a_ ( UpperCamelCase_ ): def SCREAMING_SNAKE_CASE__ (self , __a) -> List[Any]: """simple docstring""" assert len(input_dict['input_ids']) == 2 return np.array([1.03, 1.04]) # mock predict_fn which is supposed to do a forward pass with a bleurt model with patch('bleurt.score._create_predictor' ) as mock_create_predictor: __snake_case : Tuple = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher('bertscore' ) def _SCREAMING_SNAKE_CASE ( A : List[Any] ) -> List[Any]: """simple docstring""" import torch def bert_cos_score_idf(A : Any , A : Any , *A : Optional[Any] , **A : Tuple ): return torch.tensor([[1.0, 1.0, 1.0]] * len(A ) ) # mock get_model which is supposed to do download a bert model # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model with patch('bert_score.scorer.get_model' ), patch( 'bert_score.scorer.bert_cos_score_idf' ) as mock_bert_cos_score_idf: __snake_case : Optional[Any] = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher('comet' ) def _SCREAMING_SNAKE_CASE ( A : Tuple ) -> List[Any]: """simple docstring""" def load_from_checkpoint(A : str ): class a_ : def SCREAMING_SNAKE_CASE__ (self , __a , *__a , **__a) -> Any: """simple docstring""" assert len(__a) == 2 __snake_case : Optional[Any] = [0.19, 0.92] return scores, sum(__a) / len(__a) return Model() # mock load_from_checkpoint which is supposed to do download a bert model # mock load_from_checkpoint which is supposed to do download a bert model with patch('comet.download_model' ) as mock_download_model: __snake_case : Optional[Any] = None with patch('comet.load_from_checkpoint' ) as mock_load_from_checkpoint: __snake_case : List[Any] = load_from_checkpoint yield def _SCREAMING_SNAKE_CASE ( ) -> Tuple: """simple docstring""" __snake_case : Optional[int] = load_metric(os.path.join('metrics' , 'seqeval' ) ) __snake_case : Optional[int] = 'ERROR' __snake_case : Any = F"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}""" with pytest.raises(A , match=re.escape(A ) ): metric.compute(predictions=[] , references=[] , scheme=A )
61
'''simple docstring''' import math class a_ : def __init__(self , __a=0) -> Any: # a graph with Node 0,1,...,N-1 """simple docstring""" __snake_case : List[str] = n __snake_case : Tuple = [ [math.inf for j in range(0 , __a)] for i in range(0 , __a) ] # adjacency matrix for weight __snake_case : Union[str, Any] = [ [math.inf for j in range(0 , __a)] for i in range(0 , __a) ] # dp[i][j] stores minimum distance from i to j def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Tuple: """simple docstring""" __snake_case : Union[str, Any] = w def SCREAMING_SNAKE_CASE__ (self) -> Tuple: """simple docstring""" for k in range(0 , self.n): for i in range(0 , self.n): for j in range(0 , self.n): __snake_case : List[Any] = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j]) def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> Optional[int]: """simple docstring""" return self.dp[u][v] if __name__ == "__main__": __A = Graph(5) graph.add_edge(0, 2, 9) graph.add_edge(0, 4, 1_0) graph.add_edge(1, 3, 5) graph.add_edge(2, 3, 7) graph.add_edge(3, 0, 1_0) graph.add_edge(3, 1, 2) graph.add_edge(3, 2, 1) graph.add_edge(3, 4, 6) graph.add_edge(4, 1, 3) graph.add_edge(4, 2, 4) graph.add_edge(4, 3, 9) graph.floyd_warshall() graph.show_min(1, 4) graph.show_min(0, 3)
61
1
'''simple docstring''' from functools import lru_cache @lru_cache def _SCREAMING_SNAKE_CASE ( A : int ) -> int: """simple docstring""" if num < 0: raise ValueError('Number should not be negative.' ) return 1 if num in (0, 1) else num * factorial(num - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
61
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL __A = logging.get_logger(__name__) class a_ ( UpperCamelCase_ ): _snake_case = ["""pixel_values"""] def __init__(self , __a = True , __a = None , __a = None , __a = PILImageResampling.BILINEAR , __a = True , __a = 1 / 2_5_5 , __a = True , __a = None , __a = None , **__a , ) -> None: """simple docstring""" super().__init__(**__a) __snake_case : Tuple = size if size is not None else {'shortest_edge': 3_8_4} __snake_case : List[Any] = get_size_dict(__a , default_to_square=__a) __snake_case : int = do_resize __snake_case : List[str] = size # Default value set here for backwards compatibility where the value in config is None __snake_case : Any = crop_pct if crop_pct is not None else 2_2_4 / 2_5_6 __snake_case : Tuple = resample __snake_case : Dict = do_rescale __snake_case : Any = rescale_factor __snake_case : str = do_normalize __snake_case : Union[str, Any] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __snake_case : Dict = image_std if image_std is not None else IMAGENET_STANDARD_STD def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a , __a = PILImageResampling.BICUBIC , __a = None , **__a , ) -> np.ndarray: """simple docstring""" __snake_case : Dict = get_size_dict(__a , default_to_square=__a) if "shortest_edge" not in size: raise ValueError(F"""Size dictionary must contain 'shortest_edge' key. Got {size.keys()}""") __snake_case : List[str] = size['shortest_edge'] if shortest_edge < 3_8_4: # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct __snake_case : Any = int(shortest_edge / crop_pct) __snake_case : Any = get_resize_output_image_size(__a , size=__a , default_to_square=__a) __snake_case : int = resize(image=__a , size=__a , resample=__a , data_format=__a , **__a) # then crop to (shortest_edge, shortest_edge) return center_crop(image=__a , size=(shortest_edge, shortest_edge) , data_format=__a , **__a) else: # warping (no cropping) when evaluated at 384 or larger return resize( __a , size=(shortest_edge, shortest_edge) , resample=__a , data_format=__a , **__a) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a = None , **__a , ) -> Any: """simple docstring""" return rescale(__a , scale=__a , data_format=__a , **__a) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a , __a = None , **__a , ) -> np.ndarray: """simple docstring""" return normalize(__a , mean=__a , std=__a , data_format=__a , **__a) def SCREAMING_SNAKE_CASE__ (self , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = ChannelDimension.FIRST , **__a , ) -> PIL.Image.Image: """simple docstring""" __snake_case : Optional[int] = do_resize if do_resize is not None else self.do_resize __snake_case : Dict = crop_pct if crop_pct is not None else self.crop_pct __snake_case : Tuple = resample if resample is not None else self.resample __snake_case : Any = do_rescale if do_rescale is not None else self.do_rescale __snake_case : Any = rescale_factor if rescale_factor is not None else self.rescale_factor __snake_case : Union[str, Any] = do_normalize if do_normalize is not None else self.do_normalize __snake_case : Optional[int] = image_mean if image_mean is not None else self.image_mean __snake_case : Optional[Any] = image_std if image_std is not None else self.image_std __snake_case : List[str] = size if size is not None else self.size __snake_case : Any = get_size_dict(__a , default_to_square=__a) __snake_case : Dict = make_list_of_images(__a) if not valid_images(__a): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.') if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.') if do_resize and size["shortest_edge"] < 3_8_4 and crop_pct is None: raise ValueError('crop_pct must be specified if size < 384.') if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.') if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.') # All transformations expect numpy arrays. __snake_case : Tuple = [to_numpy_array(__a) for image in images] if do_resize: __snake_case : Optional[int] = [self.resize(image=__a , size=__a , crop_pct=__a , resample=__a) for image in images] if do_rescale: __snake_case : Optional[int] = [self.rescale(image=__a , scale=__a) for image in images] if do_normalize: __snake_case : Any = [self.normalize(image=__a , mean=__a , std=__a) for image in images] __snake_case : Dict = [to_channel_dimension_format(__a , __a) for image in images] __snake_case : Union[str, Any] = {'pixel_values': images} return BatchFeature(data=__a , tensor_type=__a)
61
1
'''simple docstring''' import argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as transformers_logging sys.path.append(os.path.join(os.getcwd())) # noqa: E402 # isort:skip from utils_rag import exact_match_score, fa_score # noqa: E402 # isort:skip __A = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) transformers_logging.set_verbosity_info() def _SCREAMING_SNAKE_CASE ( A : List[str] ) -> Union[str, Any]: """simple docstring""" if "token" in model_name_or_path: return "rag_token" if "sequence" in model_name_or_path: return "rag_sequence" if "bart" in model_name_or_path: return "bart" return None def _SCREAMING_SNAKE_CASE ( A : List[Any] , A : Any , A : List[str] ) -> List[str]: """simple docstring""" return max(metric_fn(A , A ) for gt in ground_truths ) def _SCREAMING_SNAKE_CASE ( A : str , A : str , A : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" __snake_case : List[Any] = [line.strip() for line in open(A , 'r' ).readlines()] __snake_case : int = [] if args.gold_data_mode == "qa": __snake_case : List[Any] = pd.read_csv(A , sep='\t' , header=A ) for answer_list in data[1]: __snake_case : str = ast.literal_eval(A ) answers.append(A ) else: __snake_case : int = [line.strip() for line in open(A , 'r' ).readlines()] __snake_case : int = [[reference] for reference in references] __snake_case : str = 0 for prediction, ground_truths in zip(A , A ): total += 1 em += metric_max_over_ground_truths(A , A , A ) fa += metric_max_over_ground_truths(A , A , A ) __snake_case : Any = 100.0 * em / total __snake_case : Tuple = 100.0 * fa / total logger.info(F"""F1: {fa:.2f}""" ) logger.info(F"""EM: {em:.2f}""" ) def _SCREAMING_SNAKE_CASE ( A : List[Any] , A : List[Any] , A : Optional[int] ) -> List[str]: """simple docstring""" __snake_case : Optional[Any] = args.k __snake_case : Optional[Any] = [line.strip() for line in open(A , 'r' ).readlines()] __snake_case : Dict = [line.strip() for line in open(A , 'r' ).readlines()] __snake_case : Tuple = 0 for hypo, reference in zip(A , A ): __snake_case : List[Any] = set(hypo.split('\t' )[:k] ) __snake_case : Optional[int] = set(reference.split('\t' ) ) total += 1 em += len(hypo_provenance & ref_provenance ) / k __snake_case : List[str] = 100.0 * em / total logger.info(F"""Precision@{k}: {em: .2f}""" ) def _SCREAMING_SNAKE_CASE ( A : List[str] , A : Optional[Any] , A : Optional[Any] ) -> Any: """simple docstring""" def strip_title(A : Optional[int] ): if title.startswith('"' ): __snake_case : Union[str, Any] = title[1:] if title.endswith('"' ): __snake_case : Union[str, Any] = title[:-1] return title __snake_case : Any = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( A , return_tensors='pt' , padding=A , truncation=A , )['input_ids'].to(args.device ) __snake_case : Tuple = rag_model.rag.question_encoder(A ) __snake_case : Dict = question_enc_outputs[0] __snake_case : int = rag_model.retriever( A , question_enc_pool_output.cpu().detach().to(torch.floataa ).numpy() , prefix=rag_model.rag.generator.config.prefix , n_docs=rag_model.config.n_docs , return_tensors='pt' , ) __snake_case : Dict = rag_model.retriever.index.get_doc_dicts(result.doc_ids ) __snake_case : Tuple = [] for docs in all_docs: __snake_case : int = [strip_title(A ) for title in docs['title']] provenance_strings.append('\t'.join(A ) ) return provenance_strings def _SCREAMING_SNAKE_CASE ( A : List[Any] , A : List[Any] , A : List[Any] ) -> Tuple: """simple docstring""" with torch.no_grad(): __snake_case : int = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( A , return_tensors='pt' , padding=A , truncation=A ) __snake_case : List[Any] = inputs_dict.input_ids.to(args.device ) __snake_case : Dict = inputs_dict.attention_mask.to(args.device ) __snake_case : List[Any] = rag_model.generate( # rag_model overwrites generate A , attention_mask=A , num_beams=args.num_beams , min_length=args.min_length , max_length=args.max_length , early_stopping=A , num_return_sequences=1 , bad_words_ids=[[0, 0]] , ) __snake_case : Union[str, Any] = rag_model.retriever.generator_tokenizer.batch_decode(A , skip_special_tokens=A ) if args.print_predictions: for q, a in zip(A , A ): logger.info('Q: {} - A: {}'.format(A , A ) ) return answers def _SCREAMING_SNAKE_CASE ( ) -> Tuple: """simple docstring""" __snake_case : Union[str, Any] = argparse.ArgumentParser() parser.add_argument( '--model_type' , choices=['rag_sequence', 'rag_token', 'bart'] , type=A , help=( 'RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the' ' model_name_or_path' ) , ) parser.add_argument( '--index_name' , default=A , choices=['exact', 'compressed', 'legacy'] , type=A , help='RAG model retriever type' , ) parser.add_argument( '--index_path' , default=A , type=A , help='Path to the retrieval index' , ) parser.add_argument('--n_docs' , default=5 , type=A , help='Number of retrieved docs' ) parser.add_argument( '--model_name_or_path' , default=A , type=A , required=A , help='Path to pretrained checkpoints or model identifier from huggingface.co/models' , ) parser.add_argument( '--eval_mode' , choices=['e2e', 'retrieval'] , default='e2e' , type=A , help=( 'Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates' ' precision@k.' ) , ) parser.add_argument('--k' , default=1 , type=A , help='k for the precision@k calculation' ) parser.add_argument( '--evaluation_set' , default=A , type=A , required=A , help='Path to a file containing evaluation samples' , ) parser.add_argument( '--gold_data_path' , default=A , type=A , required=A , help='Path to a tab-separated file with gold samples' , ) parser.add_argument( '--gold_data_mode' , default='qa' , type=A , choices=['qa', 'ans'] , help=( 'Format of the gold data file' 'qa - a single line in the following format: question [tab] answer_list' 'ans - a single line of the gold file contains the expected answer string' ) , ) parser.add_argument( '--predictions_path' , type=A , default='predictions.txt' , help='Name of the predictions file, to be stored in the checkpoints directory' , ) parser.add_argument( '--eval_all_checkpoints' , action='store_true' , help='Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number' , ) parser.add_argument( '--eval_batch_size' , default=8 , type=A , help='Batch size per GPU/CPU for evaluation.' , ) parser.add_argument( '--recalculate' , help='Recalculate predictions even if the prediction file exists' , action='store_true' , ) parser.add_argument( '--num_beams' , default=4 , type=A , help='Number of beams to be used when generating answers' , ) parser.add_argument('--min_length' , default=1 , type=A , help='Min length of the generated answers' ) parser.add_argument('--max_length' , default=50 , type=A , help='Max length of the generated answers' ) parser.add_argument( '--print_predictions' , action='store_true' , help='If True, prints predictions while evaluating.' , ) parser.add_argument( '--print_docs' , action='store_true' , help='If True, prints docs retried while generating.' , ) __snake_case : int = parser.parse_args() __snake_case : Tuple = torch.device('cuda' if torch.cuda.is_available() else 'cpu' ) return args def _SCREAMING_SNAKE_CASE ( A : Optional[int] ) -> List[Any]: """simple docstring""" __snake_case : Optional[int] = {} if args.model_type is None: __snake_case : Optional[int] = infer_model_type(args.model_name_or_path ) assert args.model_type is not None if args.model_type.startswith('rag' ): __snake_case : List[str] = RagTokenForGeneration if args.model_type == 'rag_token' else RagSequenceForGeneration __snake_case : str = args.n_docs if args.index_name is not None: __snake_case : Optional[Any] = args.index_name if args.index_path is not None: __snake_case : Union[str, Any] = args.index_path else: __snake_case : List[Any] = BartForConditionalGeneration __snake_case : Dict = ( [f.path for f in os.scandir(args.model_name_or_path ) if f.is_dir()] if args.eval_all_checkpoints else [args.model_name_or_path] ) logger.info('Evaluate the following checkpoints: %s' , A ) __snake_case : Tuple = get_scores if args.eval_mode == 'e2e' else get_precision_at_k __snake_case : Optional[int] = evaluate_batch_eae if args.eval_mode == 'e2e' else evaluate_batch_retrieval for checkpoint in checkpoints: if os.path.exists(args.predictions_path ) and (not args.recalculate): logger.info('Calculating metrics based on an existing predictions file: {}'.format(args.predictions_path ) ) score_fn(A , args.predictions_path , args.gold_data_path ) continue logger.info('***** Running evaluation for {} *****'.format(A ) ) logger.info(' Batch size = %d' , args.eval_batch_size ) logger.info(' Predictions will be stored under {}'.format(args.predictions_path ) ) if args.model_type.startswith('rag' ): __snake_case : Dict = RagRetriever.from_pretrained(A , **A ) __snake_case : List[str] = model_class.from_pretrained(A , retriever=A , **A ) model.retriever.init_retrieval() else: __snake_case : Union[str, Any] = model_class.from_pretrained(A , **A ) model.to(args.device ) with open(args.evaluation_set , 'r' ) as eval_file, open(args.predictions_path , 'w' ) as preds_file: __snake_case : int = [] for line in tqdm(A ): questions.append(line.strip() ) if len(A ) == args.eval_batch_size: __snake_case : Any = evaluate_batch_fn(A , A , A ) preds_file.write('\n'.join(A ) + '\n' ) preds_file.flush() __snake_case : List[str] = [] if len(A ) > 0: __snake_case : Optional[int] = evaluate_batch_fn(A , A , A ) preds_file.write('\n'.join(A ) ) preds_file.flush() score_fn(A , args.predictions_path , args.gold_data_path ) if __name__ == "__main__": __A = get_args() main(args)
61
'''simple docstring''' from functools import lru_cache @lru_cache def _SCREAMING_SNAKE_CASE ( A : int ) -> int: """simple docstring""" if num < 0: raise ValueError('Number should not be negative.' ) return 1 if num in (0, 1) else num * factorial(num - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
61
1
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( A : list[int] , A : str ) -> list[int]: """simple docstring""" __snake_case : List[str] = int(A ) # Initialize Result __snake_case : Optional[Any] = [] # Traverse through all denomination for denomination in reversed(A ): # Find denominations while int(A ) >= int(A ): total_value -= int(A ) answer.append(A ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": __A = [] __A = '''0''' if ( input('''Do you want to enter your denominations ? (yY/n): ''').strip().lower() == "y" ): __A = int(input('''Enter the number of denominations you want to add: ''').strip()) for i in range(0, n): denominations.append(int(input(f'''Denomination {i}: ''').strip())) __A = input('''Enter the change you want to make in Indian Currency: ''').strip() else: # All denominations of Indian Currency if user does not enter __A = [1, 2, 5, 1_0, 2_0, 5_0, 1_0_0, 5_0_0, 2_0_0_0] __A = input('''Enter the change you want to make: ''').strip() if int(value) == 0 or int(value) < 0: print('''The total value cannot be zero or negative.''') else: print(f'''Following is minimal change for {value}: ''') __A = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=''' ''')
61
'''simple docstring''' import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class a_ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): _snake_case = VQModel _snake_case = """sample""" @property def SCREAMING_SNAKE_CASE__ (self , __a=(3_2, 3_2)) -> str: """simple docstring""" __snake_case : Dict = 4 __snake_case : Optional[int] = 3 __snake_case : str = floats_tensor((batch_size, num_channels) + sizes).to(__a) return {"sample": image} @property def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" return (3, 3_2, 3_2) @property def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" return (3, 3_2, 3_2) def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" __snake_case : Optional[Any] = { 'block_out_channels': [3_2, 6_4], 'in_channels': 3, 'out_channels': 3, 'down_block_types': ['DownEncoderBlock2D', 'DownEncoderBlock2D'], 'up_block_types': ['UpDecoderBlock2D', 'UpDecoderBlock2D'], 'latent_channels': 3, } __snake_case : List[Any] = self.dummy_input return init_dict, inputs_dict def SCREAMING_SNAKE_CASE__ (self) -> Any: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" __snake_case ,__snake_case : List[Any] = VQModel.from_pretrained('fusing/vqgan-dummy' , output_loading_info=__a) self.assertIsNotNone(__a) self.assertEqual(len(loading_info['missing_keys']) , 0) model.to(__a) __snake_case : Any = model(**self.dummy_input) assert image is not None, "Make sure output is not None" def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" __snake_case : Union[str, Any] = VQModel.from_pretrained('fusing/vqgan-dummy') model.to(__a).eval() torch.manual_seed(0) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0) __snake_case : Tuple = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size) __snake_case : Optional[int] = image.to(__a) with torch.no_grad(): __snake_case : List[Any] = model(__a).sample __snake_case : int = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off __snake_case : int = torch.tensor([-0.0_153, -0.4_044, -0.1_880, -0.5_161, -0.2_418, -0.4_072, -0.1_612, -0.0_633, -0.0_143]) # fmt: on self.assertTrue(torch.allclose(__a , __a , atol=1E-3))
61
1
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( A : int = 10 , A : int = 10_00 , A : bool = True ) -> int: """simple docstring""" assert ( isinstance(A , A ) and isinstance(A , A ) and isinstance(A , A ) ), "Invalid type of value(s) specified to function!" if min_val > max_val: raise ValueError('Invalid value for min_val or max_val (min_value < max_value)' ) return min_val if option else max_val def _SCREAMING_SNAKE_CASE ( A : int , A : int ) -> int: """simple docstring""" return int((number_a + number_a) / 2 ) def _SCREAMING_SNAKE_CASE ( A : int , A : int , A : int ) -> None: """simple docstring""" assert ( isinstance(A , A ) and isinstance(A , A ) and isinstance(A , A ) ), 'argument values must be type of "int"' if lower > higher: raise ValueError('argument value for lower and higher must be(lower > higher)' ) if not lower < to_guess < higher: raise ValueError( 'guess value must be within the range of lower and higher value' ) def answer(A : int ) -> str: if number > to_guess: return "high" elif number < to_guess: return "low" else: return "same" print('started...' ) __snake_case : Dict = lower __snake_case : List[Any] = higher __snake_case : Optional[Any] = [] while True: __snake_case : Any = get_avg(A , A ) last_numbers.append(A ) if answer(A ) == "low": __snake_case : Optional[Any] = number elif answer(A ) == "high": __snake_case : Dict = number else: break print(F"""guess the number : {last_numbers[-1]}""" ) print(F"""details : {last_numbers!s}""" ) def _SCREAMING_SNAKE_CASE ( ) -> None: """simple docstring""" __snake_case : Optional[Any] = int(input('Enter lower value : ' ).strip() ) __snake_case : List[Any] = int(input('Enter high value : ' ).strip() ) __snake_case : List[str] = int(input('Enter value to guess : ' ).strip() ) guess_the_number(A , A , A ) if __name__ == "__main__": main()
61
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process __A = logging.getLogger(__name__) @dataclass class a_ : _snake_case = field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} ) _snake_case = field( default=UpperCamelCase_ , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) _snake_case = field( default="""NER""" , metadata={"""help""": """Task type to fine tune in training (e.g. NER, POS, etc)"""} ) _snake_case = field( default=UpperCamelCase_ , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} ) _snake_case = field(default=UpperCamelCase_ , metadata={"""help""": """Set this flag to use fast tokenization."""} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. _snake_case = field( default=UpperCamelCase_ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) @dataclass class a_ : _snake_case = field( metadata={"""help""": """The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."""} ) _snake_case = field( default=UpperCamelCase_ , metadata={"""help""": """Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."""} , ) _snake_case = field( default=128 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) _snake_case = field( default=UpperCamelCase_ , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} ) def _SCREAMING_SNAKE_CASE ( ) -> int: """simple docstring""" # 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. __snake_case : List[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. __snake_case ,__snake_case ,__snake_case : List[str] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __snake_case ,__snake_case ,__snake_case : int = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. Use""" ' --overwrite_output_dir to overcome.' ) __snake_case : List[str] = import_module('tasks' ) try: __snake_case : Any = getattr(A , model_args.task_type ) __snake_case : TokenClassificationTask = token_classification_task_clazz() except AttributeError: raise ValueError( F"""Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. """ F"""Available tasks classes are: {TokenClassificationTask.__subclasses__()}""" ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( 'Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('Training/evaluation parameters %s' , A ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task __snake_case : Optional[Any] = token_classification_task.get_labels(data_args.labels ) __snake_case : Dict[int, str] = dict(enumerate(A ) ) __snake_case : Optional[Any] = len(A ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __snake_case : Any = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=A , idalabel=A , labelaid={label: i for i, label in enumerate(A )} , cache_dir=model_args.cache_dir , ) __snake_case : List[str] = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast , ) __snake_case : Optional[int] = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=A , cache_dir=model_args.cache_dir , ) # Get datasets __snake_case : List[Any] = ( TokenClassificationDataset( token_classification_task=A , data_dir=data_args.data_dir , tokenizer=A , labels=A , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) __snake_case : int = ( TokenClassificationDataset( token_classification_task=A , data_dir=data_args.data_dir , tokenizer=A , labels=A , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def align_predictions(A : np.ndarray , A : np.ndarray ) -> Tuple[List[int], List[int]]: __snake_case : str = np.argmax(A , axis=2 ) __snake_case ,__snake_case : int = preds.shape __snake_case : Dict = [[] for _ in range(A )] __snake_case : Union[str, Any] = [[] for _ in range(A )] for i in range(A ): for j in range(A ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(A : EvalPrediction ) -> Dict: __snake_case ,__snake_case : Any = align_predictions(p.predictions , p.label_ids ) return { "accuracy_score": accuracy_score(A , A ), "precision": precision_score(A , A ), "recall": recall_score(A , A ), "f1": fa_score(A , A ), } # Data collator __snake_case : Optional[int] = DataCollatorWithPadding(A , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer __snake_case : Optional[Any] = Trainer( model=A , args=A , train_dataset=A , eval_dataset=A , compute_metrics=A , data_collator=A , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation __snake_case : List[Any] = {} if training_args.do_eval: logger.info('*** Evaluate ***' ) __snake_case : List[str] = trainer.evaluate() __snake_case : Tuple = os.path.join(training_args.output_dir , 'eval_results.txt' ) if trainer.is_world_process_zero(): with open(A , 'w' ) as writer: logger.info('***** Eval results *****' ) for key, value in result.items(): logger.info(' %s = %s' , A , A ) writer.write('%s = %s\n' % (key, value) ) results.update(A ) # Predict if training_args.do_predict: __snake_case : str = TokenClassificationDataset( token_classification_task=A , data_dir=data_args.data_dir , tokenizer=A , labels=A , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , ) __snake_case ,__snake_case ,__snake_case : str = trainer.predict(A ) __snake_case ,__snake_case : List[str] = align_predictions(A , A ) __snake_case : Optional[int] = os.path.join(training_args.output_dir , 'test_results.txt' ) if trainer.is_world_process_zero(): with open(A , 'w' ) as writer: for key, value in metrics.items(): logger.info(' %s = %s' , A , A ) writer.write('%s = %s\n' % (key, value) ) # Save predictions __snake_case : List[str] = os.path.join(training_args.output_dir , 'test_predictions.txt' ) if trainer.is_world_process_zero(): with open(A , 'w' ) as writer: with open(os.path.join(data_args.data_dir , 'test.txt' ) , 'r' ) as f: token_classification_task.write_predictions_to_file(A , A , A ) return results def _SCREAMING_SNAKE_CASE ( A : int ) -> Any: """simple docstring""" # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
61
1
'''simple docstring''' import os import unittest from transformers.models.cpmant.tokenization_cpmant import VOCAB_FILES_NAMES, CpmAntTokenizer from transformers.testing_utils import require_jieba, tooslow from ...test_tokenization_common import TokenizerTesterMixin @require_jieba class a_ ( UpperCamelCase_ , unittest.TestCase ): _snake_case = CpmAntTokenizer _snake_case = False def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" super().setUp() __snake_case : List[Any] = [ '<d>', '</d>', '<s>', '</s>', '</_>', '<unk>', '<pad>', '</n>', '我', '是', 'C', 'P', 'M', 'A', 'n', 't', ] __snake_case : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file']) with open(self.vocab_file , 'w' , encoding='utf-8') as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens])) @tooslow def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : Any = CpmAntTokenizer.from_pretrained('openbmb/cpm-ant-10b') __snake_case : Union[str, Any] = '今天天气真好!' __snake_case : Tuple = ['今天', '天气', '真', '好', '!'] __snake_case : Tuple = tokenizer.tokenize(__a) self.assertListEqual(__a , __a) __snake_case : Optional[int] = '今天天气真好!' __snake_case : str = [tokenizer.bos_token] + tokens __snake_case : Any = [6, 9_8_0_2, 1_4_9_6_2, 2_0_8_2, 8_3_1, 2_4_4] self.assertListEqual(tokenizer.convert_tokens_to_ids(__a) , __a) __snake_case : List[Any] = tokenizer.decode(__a) self.assertEqual(__a , __a)
61
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( A : list ) -> list: """simple docstring""" __snake_case : Tuple = False while is_sorted is False: # Until all the indices are traversed keep looping __snake_case : Optional[Any] = True for i in range(0 , len(A ) - 1 , 2 ): # iterating over all even indices if input_list[i] > input_list[i + 1]: __snake_case ,__snake_case : int = input_list[i + 1], input_list[i] # swapping if elements not in order __snake_case : List[Any] = False for i in range(1 , len(A ) - 1 , 2 ): # iterating over all odd indices if input_list[i] > input_list[i + 1]: __snake_case ,__snake_case : Tuple = input_list[i + 1], input_list[i] # swapping if elements not in order __snake_case : Any = False return input_list if __name__ == "__main__": print('''Enter list to be sorted''') __A = [int(x) for x in input().split()] # inputing elements of the list in one line __A = odd_even_sort(input_list) print('''The sorted list is''') print(sorted_list)
61
1
'''simple docstring''' import torch from diffusers import DPMSolverSDEScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import require_torchsde from .test_schedulers import SchedulerCommonTest @require_torchsde class a_ ( UpperCamelCase_ ): _snake_case = (DPMSolverSDEScheduler,) _snake_case = 10 def SCREAMING_SNAKE_CASE__ (self , **__a) -> int: """simple docstring""" __snake_case : Optional[int] = { 'num_train_timesteps': 1_1_0_0, 'beta_start': 0.0_001, 'beta_end': 0.02, 'beta_schedule': 'linear', 'noise_sampler_seed': 0, } config.update(**__a) return config def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=__a) def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001] , [0.0_002, 0.002, 0.02]): self.check_over_configs(beta_start=__a , beta_end=__a) def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]: """simple docstring""" for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=__a) def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__a) def SCREAMING_SNAKE_CASE__ (self) -> str: """simple docstring""" __snake_case : Tuple = self.scheduler_classes[0] __snake_case : Optional[int] = self.get_scheduler_config() __snake_case : Dict = scheduler_class(**__a) scheduler.set_timesteps(self.num_inference_steps) __snake_case : Dict = self.dummy_model() __snake_case : Tuple = self.dummy_sample_deter * scheduler.init_noise_sigma __snake_case : int = sample.to(__a) for i, t in enumerate(scheduler.timesteps): __snake_case : List[str] = scheduler.scale_model_input(__a , __a) __snake_case : Optional[int] = model(__a , __a) __snake_case : List[Any] = scheduler.step(__a , __a , __a) __snake_case : str = output.prev_sample __snake_case : Any = torch.sum(torch.abs(__a)) __snake_case : int = torch.mean(torch.abs(__a)) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.47_821_044_921_875) < 1E-2 assert abs(result_mean.item() - 0.2_178_705_964_565_277) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59_352_111_816_406) < 1E-2 assert abs(result_mean.item() - 0.22_342_906_892_299_652) < 1E-3 else: assert abs(result_sum.item() - 162.52_383_422_851_562) < 1E-2 assert abs(result_mean.item() - 0.211_619_570_851_326) < 1E-3 def SCREAMING_SNAKE_CASE__ (self) -> Tuple: """simple docstring""" __snake_case : Tuple = self.scheduler_classes[0] __snake_case : int = self.get_scheduler_config(prediction_type='v_prediction') __snake_case : Dict = scheduler_class(**__a) scheduler.set_timesteps(self.num_inference_steps) __snake_case : Union[str, Any] = self.dummy_model() __snake_case : Any = self.dummy_sample_deter * scheduler.init_noise_sigma __snake_case : Dict = sample.to(__a) for i, t in enumerate(scheduler.timesteps): __snake_case : int = scheduler.scale_model_input(__a , __a) __snake_case : Optional[Any] = model(__a , __a) __snake_case : Tuple = scheduler.step(__a , __a , __a) __snake_case : Optional[int] = output.prev_sample __snake_case : Optional[int] = torch.sum(torch.abs(__a)) __snake_case : Tuple = torch.mean(torch.abs(__a)) if torch_device in ["mps"]: assert abs(result_sum.item() - 124.77_149_200_439_453) < 1E-2 assert abs(result_mean.item() - 0.16_226_289_014_816_284) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 128.1_663_360_595_703) < 1E-2 assert abs(result_mean.item() - 0.16_688_326_001_167_297) < 1E-3 else: assert abs(result_sum.item() - 119.8_487_548_828_125) < 1E-2 assert abs(result_mean.item() - 0.1_560_530_662_536_621) < 1E-3 def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : Dict = self.scheduler_classes[0] __snake_case : Dict = self.get_scheduler_config() __snake_case : List[str] = scheduler_class(**__a) scheduler.set_timesteps(self.num_inference_steps , device=__a) __snake_case : Dict = self.dummy_model() __snake_case : str = self.dummy_sample_deter.to(__a) * scheduler.init_noise_sigma for t in scheduler.timesteps: __snake_case : Optional[int] = scheduler.scale_model_input(__a , __a) __snake_case : Tuple = model(__a , __a) __snake_case : Dict = scheduler.step(__a , __a , __a) __snake_case : Union[str, Any] = output.prev_sample __snake_case : Tuple = torch.sum(torch.abs(__a)) __snake_case : Optional[int] = torch.mean(torch.abs(__a)) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.46_957_397_460_938) < 1E-2 assert abs(result_mean.item() - 0.21_805_934_607_982_635) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59_353_637_695_312) < 1E-2 assert abs(result_mean.item() - 0.22_342_908_382_415_771) < 1E-3 else: assert abs(result_sum.item() - 162.52_383_422_851_562) < 1E-2 assert abs(result_mean.item() - 0.211_619_570_851_326) < 1E-3 def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : Union[str, Any] = self.scheduler_classes[0] __snake_case : str = self.get_scheduler_config() __snake_case : Optional[int] = scheduler_class(**__a , use_karras_sigmas=__a) scheduler.set_timesteps(self.num_inference_steps , device=__a) __snake_case : int = self.dummy_model() __snake_case : List[Any] = self.dummy_sample_deter.to(__a) * scheduler.init_noise_sigma __snake_case : Any = sample.to(__a) for t in scheduler.timesteps: __snake_case : List[Any] = scheduler.scale_model_input(__a , __a) __snake_case : Optional[Any] = model(__a , __a) __snake_case : Union[str, Any] = scheduler.step(__a , __a , __a) __snake_case : List[Any] = output.prev_sample __snake_case : Optional[Any] = torch.sum(torch.abs(__a)) __snake_case : Tuple = torch.mean(torch.abs(__a)) if torch_device in ["mps"]: assert abs(result_sum.item() - 176.66_974_135_742_188) < 1E-2 assert abs(result_mean.item() - 0.23_003_872_730_981_811) < 1E-2 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 177.63_653_564_453_125) < 1E-2 assert abs(result_mean.item() - 0.23_003_872_730_981_811) < 1E-2 else: assert abs(result_sum.item() - 170.3_135_223_388_672) < 1E-2 assert abs(result_mean.item() - 0.23_003_872_730_981_811) < 1E-2
61
'''simple docstring''' import argparse import json from collections import OrderedDict from functools import partial from pathlib import Path import timm import torch from huggingface_hub import hf_hub_download from transformers import LevitConfig, LevitForImageClassificationWithTeacher, LevitImageProcessor from transformers.utils import logging logging.set_verbosity_info() __A = logging.get_logger() def _SCREAMING_SNAKE_CASE ( A : int , A : str , A : LevitConfig , A : Path , A : bool = True ) -> Dict: """simple docstring""" print(F"""Converting {name}...""" ) with torch.no_grad(): if hidden_sizes == 1_28: if name[-1] == "S": __snake_case : Optional[int] = timm.create_model('levit_128s' , pretrained=A ) else: __snake_case : Tuple = timm.create_model('levit_128' , pretrained=A ) if hidden_sizes == 1_92: __snake_case : int = timm.create_model('levit_192' , pretrained=A ) if hidden_sizes == 2_56: __snake_case : List[Any] = timm.create_model('levit_256' , pretrained=A ) if hidden_sizes == 3_84: __snake_case : int = timm.create_model('levit_384' , pretrained=A ) from_model.eval() __snake_case : str = LevitForImageClassificationWithTeacher(A ).eval() __snake_case : int = OrderedDict() __snake_case : Optional[Any] = from_model.state_dict() __snake_case : Tuple = list(from_model.state_dict().keys() ) __snake_case : List[str] = list(our_model.state_dict().keys() ) print(len(A ) , len(A ) ) for i in range(len(A ) ): __snake_case : Optional[int] = weights[og_keys[i]] our_model.load_state_dict(A ) __snake_case : Tuple = torch.randn((2, 3, 2_24, 2_24) ) __snake_case : Union[str, Any] = from_model(A ) __snake_case : List[str] = our_model(A ).logits assert torch.allclose(A , A ), "The model logits don't match the original one." __snake_case : int = name print(A ) if push_to_hub: our_model.save_pretrained(save_directory / checkpoint_name ) __snake_case : int = LevitImageProcessor() image_processor.save_pretrained(save_directory / checkpoint_name ) print(F"""Pushed {checkpoint_name}""" ) def _SCREAMING_SNAKE_CASE ( A : Path , A : str = None , A : bool = True ) -> List[Any]: """simple docstring""" __snake_case : Optional[Any] = 'imagenet-1k-id2label.json' __snake_case : Tuple = 10_00 __snake_case : Dict = (1, num_labels) __snake_case : List[str] = 'huggingface/label-files' __snake_case : Any = num_labels __snake_case : str = json.load(open(hf_hub_download(A , A , repo_type='dataset' ) , 'r' ) ) __snake_case : Any = {int(A ): v for k, v in idalabel.items()} __snake_case : int = idalabel __snake_case : Union[str, Any] = {v: k for k, v in idalabel.items()} __snake_case : Optional[int] = partial(A , num_labels=A , idalabel=A , labelaid=A ) __snake_case : Dict = { 'levit-128S': 1_28, 'levit-128': 1_28, 'levit-192': 1_92, 'levit-256': 2_56, 'levit-384': 3_84, } __snake_case : Union[str, Any] = { 'levit-128S': ImageNetPreTrainedConfig( hidden_sizes=[1_28, 2_56, 3_84] , num_attention_heads=[4, 6, 8] , depths=[2, 3, 4] , key_dim=[16, 16, 16] , drop_path_rate=0 , ), 'levit-128': ImageNetPreTrainedConfig( hidden_sizes=[1_28, 2_56, 3_84] , num_attention_heads=[4, 8, 12] , depths=[4, 4, 4] , key_dim=[16, 16, 16] , drop_path_rate=0 , ), 'levit-192': ImageNetPreTrainedConfig( hidden_sizes=[1_92, 2_88, 3_84] , num_attention_heads=[3, 5, 6] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0 , ), 'levit-256': ImageNetPreTrainedConfig( hidden_sizes=[2_56, 3_84, 5_12] , num_attention_heads=[4, 6, 8] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0 , ), 'levit-384': ImageNetPreTrainedConfig( hidden_sizes=[3_84, 5_12, 7_68] , num_attention_heads=[6, 9, 12] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0.1 , ), } if model_name: convert_weight_and_push( names_to_hidden_sizes[model_name] , A , names_to_config[model_name] , A , A ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(names_to_hidden_sizes[model_name] , A , A , A , A ) return config, expected_shape if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default=None, type=str, help='''The name of the model you wish to convert, it must be one of the supported Levit* architecture,''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default='''levit-dump-folder/''', type=Path, required=False, help='''Path to the output PyTorch model directory.''', ) parser.add_argument('''--push_to_hub''', action='''store_true''', help='''Push model and image processor to the hub''') parser.add_argument( '''--no-push_to_hub''', dest='''push_to_hub''', action='''store_false''', help='''Do not push model and image processor to the hub''', ) __A = parser.parse_args() __A = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
61
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __A = logging.get_logger(__name__) __A = { '''microsoft/focalnet-tiny''': '''https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json''', } class a_ ( UpperCamelCase_ , UpperCamelCase_ ): _snake_case = """focalnet""" def __init__(self , __a=2_2_4 , __a=4 , __a=3 , __a=9_6 , __a=False , __a=[1_9_2, 3_8_4, 7_6_8, 7_6_8] , __a=[2, 2, 6, 2] , __a=[2, 2, 2, 2] , __a=[3, 3, 3, 3] , __a="gelu" , __a=4.0 , __a=0.0 , __a=0.1 , __a=False , __a=1E-4 , __a=False , __a=False , __a=False , __a=0.02 , __a=1E-5 , __a=3_2 , __a=None , __a=None , **__a , ) -> Any: """simple docstring""" super().__init__(**__a) __snake_case : int = image_size __snake_case : Optional[int] = patch_size __snake_case : Optional[int] = num_channels __snake_case : str = embed_dim __snake_case : Optional[Any] = use_conv_embed __snake_case : List[Any] = hidden_sizes __snake_case : Any = depths __snake_case : Tuple = focal_levels __snake_case : int = focal_windows __snake_case : Optional[Any] = hidden_act __snake_case : Optional[int] = mlp_ratio __snake_case : List[str] = hidden_dropout_prob __snake_case : Union[str, Any] = drop_path_rate __snake_case : str = use_layerscale __snake_case : List[Any] = layerscale_value __snake_case : Union[str, Any] = use_post_layernorm __snake_case : Union[str, Any] = use_post_layernorm_in_modulation __snake_case : Optional[int] = normalize_modulator __snake_case : Union[str, Any] = initializer_range __snake_case : Tuple = layer_norm_eps __snake_case : List[str] = encoder_stride __snake_case : List[Any] = ['stem'] + [F"""stage{idx}""" for idx in range(1 , len(self.depths) + 1)] __snake_case ,__snake_case : List[Any] = get_aligned_output_features_output_indices( out_features=__a , out_indices=__a , stage_names=self.stage_names)
61
'''simple docstring''' import inspect import unittest from typing import List import numpy as np from transformers import EfficientFormerConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerModel, ) from transformers.models.efficientformer.modeling_tf_efficientformer import ( TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_vision_available(): from PIL import Image from transformers import EfficientFormerImageProcessor class a_ : def __init__(self , __a , __a = 1_3 , __a = 6_4 , __a = 2 , __a = 3 , __a = 3 , __a = True , __a = True , __a = 1_2_8 , __a=[1_6, 3_2, 6_4, 1_2_8] , __a = 7 , __a = 4 , __a = 3_7 , __a = "gelu" , __a = 0.1 , __a = 0.1 , __a = 1_0 , __a = 0.02 , __a = 2 , __a = 1 , __a = 1_2_8 , __a = [2, 2, 2, 2] , __a = 2 , __a = 2 , ) -> str: """simple docstring""" __snake_case : Optional[Any] = parent __snake_case : Optional[int] = batch_size __snake_case : Optional[Any] = image_size __snake_case : Optional[int] = patch_size __snake_case : Optional[Any] = num_channels __snake_case : Optional[Any] = is_training __snake_case : Tuple = use_labels __snake_case : Optional[int] = hidden_size __snake_case : Any = num_hidden_layers __snake_case : List[str] = num_attention_heads __snake_case : Tuple = intermediate_size __snake_case : List[str] = hidden_act __snake_case : Dict = hidden_dropout_prob __snake_case : Any = attention_probs_dropout_prob __snake_case : Dict = type_sequence_label_size __snake_case : str = initializer_range __snake_case : int = encoder_stride __snake_case : List[str] = num_attention_outputs __snake_case : Optional[Any] = embed_dim __snake_case : Optional[Any] = embed_dim + 1 __snake_case : List[str] = resolution __snake_case : Optional[int] = depths __snake_case : List[Any] = hidden_sizes __snake_case : List[str] = dim __snake_case : Union[str, Any] = mlp_expansion_ratio def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" __snake_case : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) __snake_case : List[str] = None if self.use_labels: __snake_case : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size) __snake_case : Tuple = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" return EfficientFormerConfig( 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=__a , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , resolution=self.resolution , depths=self.depths , hidden_sizes=self.hidden_sizes , dim=self.dim , mlp_expansion_ratio=self.mlp_expansion_ratio , ) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Optional[int]: """simple docstring""" __snake_case : Union[str, Any] = TFEfficientFormerModel(config=__a) __snake_case : int = model(__a , training=__a) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Tuple: """simple docstring""" __snake_case : Dict = self.type_sequence_label_size __snake_case : List[Any] = TFEfficientFormerForImageClassification(__a) __snake_case : Optional[int] = model(__a , labels=__a , training=__a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) # test greyscale images __snake_case : List[Any] = 1 __snake_case : List[Any] = TFEfficientFormerForImageClassification(__a) __snake_case : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) __snake_case : str = model(__a , labels=__a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) def SCREAMING_SNAKE_CASE__ (self) -> Any: """simple docstring""" __snake_case : Union[str, Any] = self.prepare_config_and_inputs() __snake_case ,__snake_case ,__snake_case : Union[str, Any] = config_and_inputs __snake_case : Optional[int] = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class a_ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): _snake_case = ( ( TFEfficientFormerModel, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerForImageClassification, ) if is_tf_available() else () ) _snake_case = ( { """feature-extraction""": TFEfficientFormerModel, """image-classification""": ( TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, ), } if is_tf_available() else {} ) _snake_case = False _snake_case = False _snake_case = False _snake_case = False _snake_case = False def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : Dict = TFEfficientFormerModelTester(self) __snake_case : List[Any] = ConfigTester( self , config_class=__a , has_text_modality=__a , hidden_size=3_7) def SCREAMING_SNAKE_CASE__ (self) -> str: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='EfficientFormer does not use inputs_embeds') def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" pass @unittest.skip(reason='EfficientFormer does not support input and output embeddings') def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self) -> Any: """simple docstring""" __snake_case ,__snake_case : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : Optional[int] = model_class(__a) __snake_case : Union[str, Any] = inspect.signature(model.call) # signature.parameters is an OrderedDict => so arg_names order is deterministic __snake_case : Optional[int] = [*signature.parameters.keys()] __snake_case : Dict = ['pixel_values'] self.assertListEqual(arg_names[:1] , __a) def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" def check_hidden_states_output(__a , __a , __a): __snake_case : str = model_class(__a) __snake_case : List[Any] = model(**self._prepare_for_class(__a , __a) , training=__a) __snake_case : str = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __snake_case : Optional[Any] = getattr( self.model_tester , 'expected_num_hidden_layers' , self.model_tester.num_hidden_layers + 1) self.assertEqual(len(__a) , __a) if hasattr(self.model_tester , 'encoder_seq_length'): __snake_case : List[Any] = self.model_tester.encoder_seq_length if hasattr(self.model_tester , 'chunk_length') and self.model_tester.chunk_length > 1: __snake_case : str = seq_length * self.model_tester.chunk_length else: __snake_case : Optional[int] = self.model_tester.seq_length self.assertListEqual( list(hidden_states[-1].shape[-2:]) , [seq_length, self.model_tester.hidden_size] , ) if config.is_encoder_decoder: __snake_case : List[Any] = outputs.decoder_hidden_states self.asseretIsInstance(__a , (list, tuple)) self.assertEqual(len(__a) , __a) __snake_case : List[str] = getattr(self.model_tester , 'seq_length' , __a) __snake_case : Tuple = getattr(self.model_tester , 'decoder_seq_length' , __a) self.assertListEqual( list(hidden_states[-1].shape[-2:]) , [decoder_seq_length, self.model_tester.hidden_size] , ) __snake_case ,__snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : List[str] = True check_hidden_states_output(__a , __a , __a) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __snake_case : str = True check_hidden_states_output(__a , __a , __a) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a=False) -> int: """simple docstring""" __snake_case : Optional[int] = super()._prepare_for_class(__a , __a , return_labels=__a) if return_labels: if model_class.__name__ == "TFEfficientFormerForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" __snake_case : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a) @unittest.skip(reason='EfficientFormer does not implement masked image modeling yet') def SCREAMING_SNAKE_CASE__ (self) -> Tuple: """simple docstring""" __snake_case : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*__a) def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__a) @slow def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case : Any = TFEfficientFormerModel.from_pretrained(__a) self.assertIsNotNone(__a) def SCREAMING_SNAKE_CASE__ (self) -> Tuple: """simple docstring""" __snake_case ,__snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() __snake_case : Tuple = True __snake_case : Optional[Any] = getattr(self.model_tester , 'seq_length' , __a) __snake_case : List[Any] = getattr(self.model_tester , 'encoder_seq_length' , __a) __snake_case : Tuple = getattr(self.model_tester , 'key_length' , __a) __snake_case : Optional[Any] = getattr(self.model_tester , 'chunk_length' , __a) if chunk_length is not None and hasattr(self.model_tester , 'num_hashes'): __snake_case : str = encoder_seq_length * self.model_tester.num_hashes for model_class in self.all_model_classes: __snake_case : Optional[Any] = True __snake_case : Dict = False __snake_case : Optional[int] = True __snake_case : Dict = model_class(__a) __snake_case : Tuple = model(**self._prepare_for_class(__a , __a) , training=__a) __snake_case : Union[str, Any] = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(__a) , self.model_tester.num_attention_outputs) # check that output_attentions also work using config del inputs_dict["output_attentions"] __snake_case : Dict = True __snake_case : str = model_class(__a) __snake_case : str = model(**self._prepare_for_class(__a , __a) , training=__a) __snake_case : Tuple = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(__a) , self.model_tester.num_attention_outputs) if chunk_length is not None: self.assertListEqual( list(attentions[0].shape[-4:]) , [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length] , ) else: self.assertListEqual( list(attentions[0].shape[-3:]) , [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length] , ) def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case ,__snake_case : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # Prepare our model __snake_case : Tuple = model_class(__a) # These are maximally general inputs for the model, with multiple None dimensions # Hopefully this will catch any conditionals that fail for flexible shapes __snake_case : Optional[Any] = { key: tf.keras.Input(shape=val.shape[1:] , dtype=val.dtype , name=__a) for key, val in model.input_signature.items() if key in model.dummy_inputs } __snake_case : Tuple = model(__a) self.assertTrue(outputs_dict is not None) def _SCREAMING_SNAKE_CASE ( ) -> int: """simple docstring""" __snake_case : Tuple = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class a_ ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" return ( EfficientFormerImageProcessor.from_pretrained('snap-research/efficientformer-l1-300') if is_vision_available() else None ) @slow def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" __snake_case : List[str] = TFEfficientFormerForImageClassification.from_pretrained('snap-research/efficientformer-l1-300') __snake_case : Optional[int] = self.default_image_processor __snake_case : List[Any] = prepare_img() __snake_case : List[Any] = image_processor(images=__a , return_tensors='tf') # forward pass __snake_case : List[str] = model(**__a , training=__a) # verify the logits __snake_case : str = tf.TensorShape((1, 1_0_0_0)) self.assertEqual(outputs.logits.shape , __a) __snake_case : Any = tf.constant([-0.0_555, 0.4_825, -0.0_852]) self.assertTrue(np.allclose(outputs.logits[0, :3] , __a , atol=1E-4)) @slow def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" __snake_case : List[Any] = TFEfficientFormerForImageClassificationWithTeacher.from_pretrained( 'snap-research/efficientformer-l1-300') __snake_case : List[Any] = self.default_image_processor __snake_case : Union[str, Any] = prepare_img() __snake_case : List[Any] = image_processor(images=__a , return_tensors='tf') # forward pass __snake_case : Optional[int] = model(**__a , training=__a) # verify the logits __snake_case : Optional[int] = tf.TensorShape((1, 1_0_0_0)) self.assertEqual(outputs.logits.shape , __a) __snake_case : List[str] = tf.constant([-0.1_312, 0.4_353, -1.0_499]) self.assertTrue(np.allclose(outputs.logits[0, :3] , __a , atol=1E-4))
61
1
'''simple docstring''' import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def _SCREAMING_SNAKE_CASE ( A : Any ) -> Union[str, Any]: """simple docstring""" __snake_case : List[str] = filter(lambda A : p.requires_grad , model.parameters() ) __snake_case : int = sum([np.prod(p.size() ) for p in model_parameters] ) return params __A = logging.getLogger(__name__) def _SCREAMING_SNAKE_CASE ( A : List[Any] , A : int ) -> Any: """simple docstring""" if metric == "rouge2": __snake_case : Tuple = '{val_avg_rouge2:.4f}-{step_count}' elif metric == "bleu": __snake_case : Tuple = '{val_avg_bleu:.4f}-{step_count}' elif metric == "em": __snake_case : Optional[int] = '{val_avg_em:.4f}-{step_count}' elif metric == "loss": __snake_case : Union[str, Any] = '{val_avg_loss:.4f}-{step_count}' else: raise NotImplementedError( F"""seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this""" ' function.' ) __snake_case : str = ModelCheckpoint( dirpath=A , filename=A , monitor=F"""val_{metric}""" , mode='max' , save_top_k=1 , every_n_epochs=1 , ) return checkpoint_callback def _SCREAMING_SNAKE_CASE ( A : Optional[int] , A : Tuple ) -> Dict: """simple docstring""" return EarlyStopping( monitor=F"""val_{metric}""" , mode='min' if 'loss' in metric else 'max' , patience=A , verbose=A , ) class a_ ( pl.Callback ): def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> str: """simple docstring""" __snake_case : int = {F"""lr_group_{i}""": param['lr'] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups)} pl_module.logger.log_metrics(__a) @rank_zero_only def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a , __a=True) -> None: """simple docstring""" logger.info(F"""***** {type_path} results at step {trainer.global_step:05d} *****""") __snake_case : List[str] = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ['log', 'progress_bar', 'preds']}) # Log results __snake_case : int = Path(pl_module.hparams.output_dir) if type_path == "test": __snake_case : Any = od / 'test_results.txt' __snake_case : Any = od / 'test_generations.txt' else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. __snake_case : Optional[Any] = od / F"""{type_path}_results/{trainer.global_step:05d}.txt""" __snake_case : Union[str, Any] = od / F"""{type_path}_generations/{trainer.global_step:05d}.txt""" results_file.parent.mkdir(exist_ok=__a) generations_file.parent.mkdir(exist_ok=__a) with open(__a , 'a+') as writer: for key in sorted(__a): if key in ["log", "progress_bar", "preds"]: continue __snake_case : Dict = metrics[key] if isinstance(__a , torch.Tensor): __snake_case : str = val.item() __snake_case : Tuple = F"""{key}: {val:.6f}\n""" writer.write(__a) if not save_generations: return if "preds" in metrics: __snake_case : Tuple = '\n'.join(metrics['preds']) generations_file.open('w+').write(__a) @rank_zero_only def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> Dict: """simple docstring""" try: __snake_case : List[Any] = pl_module.model.model.num_parameters() except AttributeError: __snake_case : Dict = pl_module.model.num_parameters() __snake_case : Union[str, Any] = count_trainable_parameters(__a) # mp stands for million parameters trainer.logger.log_metrics({'n_params': npars, 'mp': npars / 1E6, 'grad_mp': n_trainable_pars / 1E6}) @rank_zero_only def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> Optional[int]: """simple docstring""" save_json(pl_module.metrics , pl_module.metrics_save_path) return self._write_logs(__a , __a , 'test') @rank_zero_only def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> str: """simple docstring""" save_json(pl_module.metrics , pl_module.metrics_save_path) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
61
'''simple docstring''' __A = {str(digit): digit**5 for digit in range(1_0)} def _SCREAMING_SNAKE_CASE ( A : int ) -> int: """simple docstring""" return sum(DIGITS_FIFTH_POWER[digit] for digit in str(A ) ) def _SCREAMING_SNAKE_CASE ( ) -> int: """simple docstring""" return sum( number for number in range(10_00 , 1_00_00_00 ) if number == digits_fifth_powers_sum(A ) ) if __name__ == "__main__": print(solution())
61
1
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( A : str ) -> bool: """simple docstring""" __snake_case : Optional[Any] = 0 for ch in input_str: __snake_case : str = ord(A ) __snake_case : List[str] = pow(2 , A ) # If we already turned on bit for current character's unicode if bitmap >> ch_unicode & 1 == 1: return False bitmap |= ch_bit_index_on return True if __name__ == "__main__": import doctest doctest.testmod()
61
'''simple docstring''' from __future__ import annotations from collections import deque from collections.abc import Sequence from dataclasses import dataclass from typing import Any @dataclass class a_ : _snake_case = 42 _snake_case = None _snake_case = None def _SCREAMING_SNAKE_CASE ( ) -> Node | None: """simple docstring""" __snake_case : str = Node(1 ) __snake_case : Tuple = Node(2 ) __snake_case : Optional[int] = Node(3 ) __snake_case : List[str] = Node(4 ) __snake_case : List[str] = Node(5 ) return tree def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> list[int]: """simple docstring""" return [root.data, *preorder(root.left ), *preorder(root.right )] if root else [] def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> list[int]: """simple docstring""" return postorder(root.left ) + postorder(root.right ) + [root.data] if root else [] def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> list[int]: """simple docstring""" return [*inorder(root.left ), root.data, *inorder(root.right )] if root else [] def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> int: """simple docstring""" return (max(height(root.left ) , height(root.right ) ) + 1) if root else 0 def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> Sequence[Node | None]: """simple docstring""" __snake_case : list[Any] = [] if root is None: return output __snake_case : Optional[int] = deque([root] ) while process_queue: __snake_case : List[str] = process_queue.popleft() output.append(node.data ) if node.left: process_queue.append(node.left ) if node.right: process_queue.append(node.right ) return output def _SCREAMING_SNAKE_CASE ( A : Node | None , A : int ) -> Sequence[Node | None]: """simple docstring""" __snake_case : list[Any] = [] def populate_output(A : Node | None , A : int ) -> None: if not root: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.left , level - 1 ) populate_output(root.right , level - 1 ) populate_output(A , A ) return output def _SCREAMING_SNAKE_CASE ( A : Node | None , A : int ) -> Sequence[Node | None]: """simple docstring""" __snake_case : list[Any] = [] def populate_output(A : Node | None , A : int ) -> None: if root is None: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.right , level - 1 ) populate_output(root.left , level - 1 ) populate_output(A , A ) return output def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> Sequence[Node | None] | list[Any]: """simple docstring""" if root is None: return [] __snake_case : list[Sequence[Node | None]] = [] __snake_case : List[Any] = 0 __snake_case : int = height(A ) for h in range(1 , height_tree + 1 ): if not flag: output.append(get_nodes_from_left_to_right(A , A ) ) __snake_case : int = 1 else: output.append(get_nodes_from_right_to_left(A , A ) ) __snake_case : Tuple = 0 return output def _SCREAMING_SNAKE_CASE ( ) -> None: # Main function for testing. """simple docstring""" __snake_case : Optional[int] = make_tree() print(F"""In-order Traversal: {inorder(A )}""" ) print(F"""Pre-order Traversal: {preorder(A )}""" ) print(F"""Post-order Traversal: {postorder(A )}""" , '\n' ) print(F"""Height of Tree: {height(A )}""" , '\n' ) print('Complete Level Order Traversal: ' ) print(level_order(A ) , '\n' ) print('Level-wise order Traversal: ' ) for level in range(1 , height(A ) + 1 ): print(F"""Level {level}:""" , get_nodes_from_left_to_right(A , level=A ) ) print('\nZigZag order Traversal: ' ) print(zigzag(A ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
61
1
'''simple docstring''' import io import itertools import json from dataclasses import dataclass from typing import Optional import pyarrow as pa import pyarrow.json as paj import datasets from datasets.table import table_cast from datasets.utils.file_utils import readline __A = datasets.utils.logging.get_logger(__name__) @dataclass class a_ ( datasets.BuilderConfig ): _snake_case = None _snake_case = "utf-8" _snake_case = None _snake_case = None _snake_case = True # deprecated _snake_case = None # deprecated _snake_case = 10 << 20 # 10MB _snake_case = None class a_ ( datasets.ArrowBasedBuilder ): _snake_case = JsonConfig def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" if self.config.block_size is not None: logger.warning('The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead') __snake_case : Tuple = self.config.block_size if self.config.use_threads is not True: logger.warning( 'The JSON loader parameter `use_threads` is deprecated and doesn\'t have any effect anymore.') if self.config.newlines_in_values is not None: raise ValueError('The JSON loader parameter `newlines_in_values` is no longer supported') return datasets.DatasetInfo(features=self.config.features) def SCREAMING_SNAKE_CASE__ (self , __a) -> List[str]: """simple docstring""" if not self.config.data_files: raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}""") __snake_case : Optional[int] = dl_manager.download_and_extract(self.config.data_files) if isinstance(__a , (str, list, tuple)): __snake_case : Tuple = data_files if isinstance(__a , __a): __snake_case : Tuple = [files] __snake_case : Optional[int] = [dl_manager.iter_files(__a) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'files': files})] __snake_case : Dict = [] for split_name, files in data_files.items(): if isinstance(__a , __a): __snake_case : List[str] = [files] __snake_case : Any = [dl_manager.iter_files(__a) for file in files] splits.append(datasets.SplitGenerator(name=__a , gen_kwargs={'files': files})) return splits def SCREAMING_SNAKE_CASE__ (self , __a) -> pa.Table: """simple docstring""" if self.config.features is not None: # adding missing columns for column_name in set(self.config.features) - set(pa_table.column_names): __snake_case : Any = self.config.features.arrow_schema.field(__a).type __snake_case : Any = pa_table.append_column(__a , pa.array([None] * len(__a) , type=__a)) # more expensive cast to support nested structures with keys in a different order # allows str <-> int/float or str to Audio for example __snake_case : Optional[Any] = table_cast(__a , self.config.features.arrow_schema) return pa_table def SCREAMING_SNAKE_CASE__ (self , __a) -> Tuple: """simple docstring""" for file_idx, file in enumerate(itertools.chain.from_iterable(__a)): # If the file is one json object and if we need to look at the list of items in one specific field if self.config.field is not None: with open(__a , encoding=self.config.encoding , errors=self.config.encoding_errors) as f: __snake_case : Union[str, Any] = json.load(__a) # We keep only the field we are interested in __snake_case : Tuple = dataset[self.config.field] # We accept two format: a list of dicts or a dict of lists if isinstance(__a , (list, tuple)): __snake_case : Optional[Any] = set().union(*[row.keys() for row in dataset]) __snake_case : List[str] = {col: [row.get(__a) for row in dataset] for col in keys} else: __snake_case : Tuple = dataset __snake_case : Optional[int] = pa.Table.from_pydict(__a) yield file_idx, self._cast_table(__a) # If the file has one json object per line else: with open(__a , 'rb') as f: __snake_case : Any = 0 # Use block_size equal to the chunk size divided by 32 to leverage multithreading # Set a default minimum value of 16kB if the chunk size is really small __snake_case : List[Any] = max(self.config.chunksize // 3_2 , 1_6 << 1_0) __snake_case : Union[str, Any] = ( self.config.encoding_errors if self.config.encoding_errors is not None else 'strict' ) while True: __snake_case : str = f.read(self.config.chunksize) if not batch: break # Finish current line try: batch += f.readline() except (AttributeError, io.UnsupportedOperation): batch += readline(__a) # PyArrow only accepts utf-8 encoded bytes if self.config.encoding != "utf-8": __snake_case : int = batch.decode(self.config.encoding , errors=__a).encode('utf-8') try: while True: try: __snake_case : Tuple = paj.read_json( io.BytesIO(__a) , read_options=paj.ReadOptions(block_size=__a)) break except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e: if ( isinstance(__a , pa.ArrowInvalid) and "straddling" not in str(__a) or block_size > len(__a) ): raise else: # Increase the block size in case it was too small. # The block size will be reset for the next file. logger.debug( F"""Batch of {len(__a)} bytes couldn't be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.""") block_size *= 2 except pa.ArrowInvalid as e: try: with open( __a , encoding=self.config.encoding , errors=self.config.encoding_errors) as f: __snake_case : str = json.load(__a) except json.JSONDecodeError: logger.error(F"""Failed to read file '{file}' with error {type(__a)}: {e}""") raise e # If possible, parse the file as a list of json objects and exit the loop if isinstance(__a , __a): # list is the only sequence type supported in JSON try: __snake_case : List[Any] = set().union(*[row.keys() for row in dataset]) __snake_case : Union[str, Any] = {col: [row.get(__a) for row in dataset] for col in keys} __snake_case : List[Any] = pa.Table.from_pydict(__a) except (pa.ArrowInvalid, AttributeError) as e: logger.error(F"""Failed to read file '{file}' with error {type(__a)}: {e}""") raise ValueError(F"""Not able to read records in the JSON file at {file}.""") from None yield file_idx, self._cast_table(__a) break else: logger.error(F"""Failed to read file '{file}' with error {type(__a)}: {e}""") raise ValueError( F"""Not able to read records in the JSON file at {file}. """ F"""You should probably indicate the field of the JSON file containing your records. """ F"""This JSON file contain the following fields: {str(list(dataset.keys()))}. """ F"""Select the correct one and provide it as `field='XXX'` to the dataset loading method. """) from None # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(__a) batch_idx += 1
61
'''simple docstring''' from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class a_ : def __init__(self , __a = None) -> None: """simple docstring""" if components is None: __snake_case : List[str] = [] __snake_case : Optional[int] = list(__a) def __len__(self) -> int: """simple docstring""" return len(self.__components) def __str__(self) -> str: """simple docstring""" return "(" + ",".join(map(__a , self.__components)) + ")" def __add__(self , __a) -> Vector: """simple docstring""" __snake_case : Optional[Any] = len(self) if size == len(__a): __snake_case : Optional[int] = [self.__components[i] + other.component(__a) for i in range(__a)] return Vector(__a) else: raise Exception('must have the same size') def __sub__(self , __a) -> Vector: """simple docstring""" __snake_case : Optional[Any] = len(self) if size == len(__a): __snake_case : Optional[int] = [self.__components[i] - other.component(__a) for i in range(__a)] return Vector(__a) else: # error case raise Exception('must have the same size') @overload def __mul__(self , __a) -> Vector: """simple docstring""" ... @overload def __mul__(self , __a) -> float: """simple docstring""" ... def __mul__(self , __a) -> float | Vector: """simple docstring""" if isinstance(__a , (float, int)): __snake_case : str = [c * other for c in self.__components] return Vector(__a) elif isinstance(__a , __a) and len(self) == len(__a): __snake_case : List[Any] = len(self) __snake_case : Dict = [self.__components[i] * other.component(__a) for i in range(__a)] return sum(__a) else: # error case raise Exception('invalid operand!') def SCREAMING_SNAKE_CASE__ (self) -> Vector: """simple docstring""" return Vector(self.__components) def SCREAMING_SNAKE_CASE__ (self , __a) -> float: """simple docstring""" if isinstance(__a , __a) and -len(self.__components) <= i < len(self.__components): return self.__components[i] else: raise Exception('index out of range') def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> None: """simple docstring""" assert -len(self.__components) <= pos < len(self.__components) __snake_case : int = value def SCREAMING_SNAKE_CASE__ (self) -> float: """simple docstring""" if len(self.__components) == 0: raise Exception('Vector is empty') __snake_case : Tuple = [c**2 for c in self.__components] return math.sqrt(sum(__a)) def SCREAMING_SNAKE_CASE__ (self , __a , __a = False) -> float: """simple docstring""" __snake_case : Tuple = self * other __snake_case : Optional[int] = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den)) else: return math.acos(num / den) def _SCREAMING_SNAKE_CASE ( A : int ) -> Vector: """simple docstring""" assert isinstance(A , A ) return Vector([0] * dimension ) def _SCREAMING_SNAKE_CASE ( A : int , A : int ) -> Vector: """simple docstring""" assert isinstance(A , A ) and (isinstance(A , A )) __snake_case : Any = [0] * dimension __snake_case : int = 1 return Vector(A ) def _SCREAMING_SNAKE_CASE ( A : float , A : Vector , A : Vector ) -> Vector: """simple docstring""" assert ( isinstance(A , A ) and isinstance(A , A ) and (isinstance(A , (int, float) )) ) return x * scalar + y def _SCREAMING_SNAKE_CASE ( A : int , A : int , A : int ) -> Vector: """simple docstring""" random.seed(A ) __snake_case : List[Any] = [random.randint(A , A ) for _ in range(A )] return Vector(A ) class a_ : def __init__(self , __a , __a , __a) -> None: """simple docstring""" __snake_case : Union[str, Any] = matrix __snake_case : int = w __snake_case : str = h def __str__(self) -> str: """simple docstring""" __snake_case : Dict = '' for i in range(self.__height): ans += "|" for j in range(self.__width): if j < self.__width - 1: ans += str(self.__matrix[i][j]) + "," else: ans += str(self.__matrix[i][j]) + "|\n" return ans def __add__(self , __a) -> Matrix: """simple docstring""" if self.__width == other.width() and self.__height == other.height(): __snake_case : Tuple = [] for i in range(self.__height): __snake_case : List[Any] = [ self.__matrix[i][j] + other.component(__a , __a) for j in range(self.__width) ] matrix.append(__a) return Matrix(__a , self.__width , self.__height) else: raise Exception('matrix must have the same dimension!') def __sub__(self , __a) -> Matrix: """simple docstring""" if self.__width == other.width() and self.__height == other.height(): __snake_case : str = [] for i in range(self.__height): __snake_case : List[str] = [ self.__matrix[i][j] - other.component(__a , __a) for j in range(self.__width) ] matrix.append(__a) return Matrix(__a , self.__width , self.__height) else: raise Exception('matrices must have the same dimension!') @overload def __mul__(self , __a) -> Matrix: """simple docstring""" ... @overload def __mul__(self , __a) -> Vector: """simple docstring""" ... def __mul__(self , __a) -> Vector | Matrix: """simple docstring""" if isinstance(__a , __a): # matrix-vector if len(__a) == self.__width: __snake_case : Tuple = zero_vector(self.__height) for i in range(self.__height): __snake_case : Union[str, Any] = [ self.__matrix[i][j] * other.component(__a) for j in range(self.__width) ] ans.change_component(__a , sum(__a)) return ans else: raise Exception( 'vector must have the same size as the ' 'number of columns of the matrix!') elif isinstance(__a , (int, float)): # matrix-scalar __snake_case : str = [ [self.__matrix[i][j] * other for j in range(self.__width)] for i in range(self.__height) ] return Matrix(__a , self.__width , self.__height) return None def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" return self.__height def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" return self.__width def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> float: """simple docstring""" if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception('change_component: indices out of bounds') def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> None: """simple docstring""" if 0 <= x < self.__height and 0 <= y < self.__width: __snake_case : List[Any] = value else: raise Exception('change_component: indices out of bounds') def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> float: """simple docstring""" if self.__height != self.__width: raise Exception('Matrix is not square') __snake_case : List[Any] = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(__a)): __snake_case : Tuple = minor[i][:y] + minor[i][y + 1 :] return Matrix(__a , self.__width - 1 , self.__height - 1).determinant() def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> float: """simple docstring""" if self.__height != self.__width: raise Exception('Matrix is not square') if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(__a , __a) else: raise Exception('Indices out of bounds') def SCREAMING_SNAKE_CASE__ (self) -> float: """simple docstring""" if self.__height != self.__width: raise Exception('Matrix is not square') if self.__height < 1: raise Exception('Matrix has no element') elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: __snake_case : Any = [ self.__matrix[0][y] * self.cofactor(0 , __a) for y in range(self.__width) ] return sum(__a) def _SCREAMING_SNAKE_CASE ( A : int ) -> Matrix: """simple docstring""" __snake_case : list[list[float]] = [[0] * n for _ in range(A )] return Matrix(A , A , A ) def _SCREAMING_SNAKE_CASE ( A : int , A : int , A : int , A : int ) -> Matrix: """simple docstring""" random.seed(A ) __snake_case : list[list[float]] = [ [random.randint(A , A ) for _ in range(A )] for _ in range(A ) ] return Matrix(A , A , A )
61
1
'''simple docstring''' import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, TimesformerForVideoClassification, TimesformerModel, ) from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class a_ : def __init__(self , __a , __a=1_3 , __a=1_0 , __a=3 , __a=2 , __a=2 , __a=True , __a=True , __a=3_2 , __a=5 , __a=4 , __a=3_7 , __a="gelu" , __a=0.1 , __a=0.1 , __a=1_0 , __a=0.02 , __a="divided_space_time" , __a=None , ) -> str: """simple docstring""" __snake_case : Optional[int] = parent __snake_case : str = batch_size __snake_case : Tuple = image_size __snake_case : str = num_channels __snake_case : List[Any] = patch_size __snake_case : Optional[int] = num_frames __snake_case : Dict = is_training __snake_case : Optional[int] = use_labels __snake_case : Dict = hidden_size __snake_case : List[str] = num_hidden_layers __snake_case : Any = num_attention_heads __snake_case : Dict = intermediate_size __snake_case : Tuple = hidden_act __snake_case : Tuple = hidden_dropout_prob __snake_case : Optional[Any] = attention_probs_dropout_prob __snake_case : Union[str, Any] = attention_type __snake_case : Any = initializer_range __snake_case : Dict = scope __snake_case : Optional[Any] = num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token __snake_case : Union[str, Any] = (image_size // patch_size) ** 2 __snake_case : int = (num_frames) * self.num_patches_per_frame + 1 def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]: """simple docstring""" __snake_case : List[str] = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]) __snake_case : Any = None if self.use_labels: __snake_case : List[Any] = ids_tensor([self.batch_size] , self.num_labels) __snake_case : int = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]: """simple docstring""" __snake_case : List[Any] = TimesformerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , 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 , initializer_range=self.initializer_range , attention_type=self.attention_type , ) __snake_case : str = self.num_labels return config def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Tuple: """simple docstring""" __snake_case : Optional[Any] = TimesformerModel(config=__a) model.to(__a) model.eval() __snake_case : Optional[int] = model(__a) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Dict: """simple docstring""" __snake_case : str = TimesformerForVideoClassification(__a) model.to(__a) model.eval() __snake_case : Union[str, Any] = model(__a) # verify the logits shape __snake_case : Dict = torch.Size((self.batch_size, self.num_labels)) self.parent.assertEqual(result.logits.shape , __a) def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" __snake_case : int = self.prepare_config_and_inputs() __snake_case ,__snake_case ,__snake_case : Optional[int] = config_and_inputs __snake_case : Dict = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class a_ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): _snake_case = (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else () _snake_case = ( {"""feature-extraction""": TimesformerModel, """video-classification""": TimesformerForVideoClassification} if is_torch_available() else {} ) _snake_case = False _snake_case = False _snake_case = False _snake_case = False def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]: """simple docstring""" __snake_case : Tuple = TimesformerModelTester(self) __snake_case : str = ConfigTester( self , config_class=__a , has_text_modality=__a , hidden_size=3_7) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a=False) -> Tuple: """simple docstring""" __snake_case : Tuple = copy.deepcopy(__a) if return_labels: if model_class in get_values(__a): __snake_case : Tuple = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__a) return inputs_dict def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='TimeSformer does not use inputs_embeds') def SCREAMING_SNAKE_CASE__ (self) -> str: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" __snake_case ,__snake_case : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : Any = model_class(__a) self.assertIsInstance(model.get_input_embeddings() , (nn.Module)) __snake_case : Tuple = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__a , nn.Linear)) def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]: """simple docstring""" __snake_case ,__snake_case : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : Optional[Any] = model_class(__a) __snake_case : int = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic __snake_case : int = [*signature.parameters.keys()] __snake_case : Union[str, Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , __a) def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a) def SCREAMING_SNAKE_CASE__ (self) -> str: """simple docstring""" __snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*__a) @slow def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]: """simple docstring""" for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case : int = TimesformerModel.from_pretrained(__a) self.assertIsNotNone(__a) def SCREAMING_SNAKE_CASE__ (self) -> str: """simple docstring""" if not self.has_attentions: pass else: __snake_case ,__snake_case : Any = self.model_tester.prepare_config_and_inputs_for_common() __snake_case : int = True for model_class in self.all_model_classes: __snake_case : Tuple = self.model_tester.seq_length __snake_case : str = self.model_tester.num_frames __snake_case : Any = True __snake_case : Union[str, Any] = False __snake_case : Any = True __snake_case : List[Any] = model_class(__a) model.to(__a) model.eval() with torch.no_grad(): __snake_case : List[str] = model(**self._prepare_for_class(__a , __a)) __snake_case : Any = outputs.attentions self.assertEqual(len(__a) , self.model_tester.num_hidden_layers) # check that output_attentions also work using config del inputs_dict["output_attentions"] __snake_case : Optional[int] = True __snake_case : List[str] = model_class(__a) model.to(__a) model.eval() with torch.no_grad(): __snake_case : List[str] = model(**self._prepare_for_class(__a , __a)) __snake_case : List[str] = outputs.attentions self.assertEqual(len(__a) , self.model_tester.num_hidden_layers) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(attentions[0].shape[-3:]) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) __snake_case : str = len(__a) # Check attention is always last and order is fine __snake_case : List[str] = True __snake_case : Dict = True __snake_case : int = model_class(__a) model.to(__a) model.eval() with torch.no_grad(): __snake_case : Optional[int] = model(**self._prepare_for_class(__a , __a)) self.assertEqual(out_len + 1 , len(__a)) __snake_case : Optional[Any] = outputs.attentions self.assertEqual(len(__a) , self.model_tester.num_hidden_layers) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(self_attentions[0].shape[-3:]) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" def check_hidden_states_output(__a , __a , __a): __snake_case : List[str] = model_class(__a) model.to(__a) model.eval() with torch.no_grad(): __snake_case : List[Any] = model(**self._prepare_for_class(__a , __a)) __snake_case : int = outputs.hidden_states __snake_case : List[Any] = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(__a) , __a) __snake_case : int = self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:]) , [seq_length, self.model_tester.hidden_size] , ) __snake_case ,__snake_case : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : Optional[Any] = True check_hidden_states_output(__a , __a , __a) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __snake_case : Any = True check_hidden_states_output(__a , __a , __a) def _SCREAMING_SNAKE_CASE ( ) -> Dict: """simple docstring""" __snake_case : Optional[int] = hf_hub_download( repo_id='hf-internal-testing/spaghetti-video' , filename='eating_spaghetti.npy' , repo_type='dataset' ) __snake_case : Dict = np.load(A ) return list(A ) @require_torch @require_vision class a_ ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]: """simple docstring""" return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5]) if is_vision_available() else None ) @slow def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" __snake_case : List[Any] = TimesformerForVideoClassification.from_pretrained('facebook/timesformer-base-finetuned-k400').to( __a) __snake_case : Optional[Any] = self.default_image_processor __snake_case : Optional[Any] = prepare_video() __snake_case : Optional[int] = image_processor(video[:8] , return_tensors='pt').to(__a) # forward pass with torch.no_grad(): __snake_case : Optional[int] = model(**__a) # verify the logits __snake_case : Dict = torch.Size((1, 4_0_0)) self.assertEqual(outputs.logits.shape , __a) __snake_case : Tuple = torch.tensor([-0.3_016, -0.7_713, -0.4_205]).to(__a) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __a , atol=1E-4))
61
'''simple docstring''' import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification if is_tf_available(): from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification if is_flax_available(): from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification __A = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co __A = '''main''' # Default branch name __A = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2''' # One particular commit (not the top of `main`) __A = '''aaaaaaa''' # This commit does not exist, so we should 404. __A = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684''' # Sha-1 of config.json on the top of `main`, for checking purposes __A = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3''' @contextlib.contextmanager def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: """simple docstring""" print('Welcome!' ) yield print('Bye!' ) @contextlib.contextmanager def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]: """simple docstring""" print('Bonjour!' ) yield print('Au revoir!' ) class a_ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" assert transformers.__spec__ is not None assert importlib.util.find_spec('transformers') is not None class a_ ( unittest.TestCase ): @unittest.mock.patch('sys.stdout' , new_callable=io.StringIO) def SCREAMING_SNAKE_CASE__ (self , __a) -> int: """simple docstring""" with ContextManagers([]): print('Transformers are awesome!') # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue() , 'Transformers are awesome!\n') @unittest.mock.patch('sys.stdout' , new_callable=io.StringIO) def SCREAMING_SNAKE_CASE__ (self , __a) -> List[str]: """simple docstring""" with ContextManagers([context_en()]): print('Transformers are awesome!') # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue() , 'Welcome!\nTransformers are awesome!\nBye!\n') @unittest.mock.patch('sys.stdout' , new_callable=io.StringIO) def SCREAMING_SNAKE_CASE__ (self , __a) -> Tuple: """simple docstring""" with ContextManagers([context_fr(), context_en()]): print('Transformers are awesome!') # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue() , 'Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n') @require_torch def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" self.assertEqual(find_labels(__a) , ['labels']) self.assertEqual(find_labels(__a) , ['labels', 'next_sentence_label']) self.assertEqual(find_labels(__a) , ['start_positions', 'end_positions']) class a_ ( UpperCamelCase_ ): pass self.assertEqual(find_labels(__a) , ['labels']) @require_tf def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" self.assertEqual(find_labels(__a) , ['labels']) self.assertEqual(find_labels(__a) , ['labels', 'next_sentence_label']) self.assertEqual(find_labels(__a) , ['start_positions', 'end_positions']) class a_ ( UpperCamelCase_ ): pass self.assertEqual(find_labels(__a) , ['labels']) @require_flax def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" self.assertEqual(find_labels(__a) , []) self.assertEqual(find_labels(__a) , []) self.assertEqual(find_labels(__a) , []) class a_ ( UpperCamelCase_ ): pass self.assertEqual(find_labels(__a) , [])
61
1
'''simple docstring''' from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class a_ : _snake_case = 42 _snake_case = None _snake_case = None __A = namedtuple('''CoinsDistribResult''', '''moves excess''') def _SCREAMING_SNAKE_CASE ( A : TreeNode | None ) -> int: """simple docstring""" if root is None: return 0 # Validation def count_nodes(A : TreeNode | None ) -> int: if node is None: return 0 return count_nodes(node.left ) + count_nodes(node.right ) + 1 def count_coins(A : TreeNode | None ) -> int: if node is None: return 0 return count_coins(node.left ) + count_coins(node.right ) + node.data if count_nodes(A ) != count_coins(A ): raise ValueError('The nodes number should be same as the number of coins' ) # Main calculation def get_distrib(A : TreeNode | None ) -> CoinsDistribResult: if node is None: return CoinsDistribResult(0 , 1 ) __snake_case ,__snake_case : List[str] = get_distrib(node.left ) __snake_case ,__snake_case : Optional[int] = get_distrib(node.right ) __snake_case : Any = 1 - left_distrib_excess __snake_case : str = 1 - right_distrib_excess __snake_case : List[str] = ( left_distrib_moves + right_distrib_moves + abs(A ) + abs(A ) ) __snake_case : List[str] = node.data - coins_to_left - coins_to_right return CoinsDistribResult(A , A ) return get_distrib(A )[0] if __name__ == "__main__": import doctest doctest.testmod()
61
'''simple docstring''' # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A = {'''configuration_timm_backbone''': ['''TimmBackboneConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ['''TimmBackbone'''] if TYPE_CHECKING: from .configuration_timm_backbone import TimmBackboneConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timm_backbone import TimmBackbone else: import sys __A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
61
1
'''simple docstring''' __A = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} __A = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def _SCREAMING_SNAKE_CASE ( A : dict[int, list[int]] , A : int , A : list[bool] ) -> list[int]: """simple docstring""" __snake_case : Any = True __snake_case : Dict = [] for neighbour in graph[vert]: if not visited[neighbour]: order += topology_sort(A , A , A ) order.append(A ) return order def _SCREAMING_SNAKE_CASE ( A : dict[int, list[int]] , A : int , A : list[bool] ) -> list[int]: """simple docstring""" __snake_case : List[str] = True __snake_case : Union[str, Any] = [vert] for neighbour in reversed_graph[vert]: if not visited[neighbour]: component += find_components(A , A , A ) return component def _SCREAMING_SNAKE_CASE ( A : dict[int, list[int]] ) -> list[list[int]]: """simple docstring""" __snake_case : str = len(A ) * [False] __snake_case : dict[int, list[int]] = {vert: [] for vert in range(len(A ) )} for vert, neighbours in graph.items(): for neighbour in neighbours: reversed_graph[neighbour].append(A ) __snake_case : Dict = [] for i, was_visited in enumerate(A ): if not was_visited: order += topology_sort(A , A , A ) __snake_case : Tuple = [] __snake_case : List[Any] = len(A ) * [False] for i in range(len(A ) ): __snake_case : Dict = order[len(A ) - i - 1] if not visited[vert]: __snake_case : Optional[int] = find_components(A , A , A ) components_list.append(A ) return components_list
61
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( A : int ) -> int: """simple docstring""" __snake_case : str = 1 for i in range(1 , num + 1 ): fact *= i return fact def _SCREAMING_SNAKE_CASE ( A : int ) -> int: """simple docstring""" __snake_case : Union[str, Any] = 0 while number > 0: __snake_case : Dict = number % 10 sum_of_digits += last_digit __snake_case : Union[str, Any] = number // 10 # Removing the last_digit from the given number return sum_of_digits def _SCREAMING_SNAKE_CASE ( A : int = 1_00 ) -> int: """simple docstring""" __snake_case : List[Any] = factorial(A ) __snake_case : Dict = split_and_add(A ) return result if __name__ == "__main__": print(solution(int(input('''Enter the Number: ''').strip())))
61
1
'''simple docstring''' import argparse import random import joblib import numpy as np import torch from igf.igf import ( SecondaryLearner, collect_objective_set, compute_perplexity, generate_datasets, load_gpta, recopy_gpta, set_seed, train_secondary_learner, ) from torch.utils.data import DataLoader, RandomSampler from transformers import GPTaLMHeadModel def _SCREAMING_SNAKE_CASE ( A : Tuple=32 , A : Optional[int]=10 , A : Optional[int]=1_00 , A : List[str]=10_26 , A : List[str]=True , A : List[str]="data/tokenized_stories_train_wikitext103.jbl" , A : List[Any]="igf_context_pairs.jbl" , ) -> Optional[Any]: """simple docstring""" set_seed(3 ) # generate train_data and objective_set __snake_case ,__snake_case : str = generate_datasets( A , A , number=A , min_len=10_26 , trim=A ) # keeps model same across runs set_seed(4 ) # model, lm_optimizer, lm_scheduler = recopy_gpt2(model, device, max_steps) # store original model weights # can we train on GPU? __snake_case : int = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu' ) # load pretrained model __snake_case : str = load_gpta('gpt2' ).to(A ) print('computing perplexity on objective set' ) __snake_case : List[str] = compute_perplexity(A , A , A ).item() print('perplexity on objective set:' , A ) # collect igf pairs and save to file demo.jbl collect_objective_set(A , A , A , A , A , A , A , A ) # clean up, delete model and data we don't need anymore del model, train_data, objective_set torch.cuda.empty_cache() def _SCREAMING_SNAKE_CASE ( A : Tuple , A : Optional[int]=15 , A : List[Any]=1_28 , A : Tuple=1_00 , A : Tuple="igf_model.pt" , ) -> Dict: """simple docstring""" set_seed(42 ) # Load pre-trained model __snake_case : Dict = GPTaLMHeadModel.from_pretrained('gpt2' ) # Initialize secondary learner to use embedding weights of model __snake_case : List[Any] = SecondaryLearner(A ) # Train secondary learner __snake_case : str = train_secondary_learner( A , A , max_epochs=A , batch_size=A , eval_freq=1_00 , igf_model_path=A , ) del model, secondary_learner_train_data torch.cuda.empty_cache() return secondary_learner def _SCREAMING_SNAKE_CASE ( A : List[Any] , A : List[str] , A : Dict , A : Any=32 , A : Dict=10_00 , A : List[Any]=16 , A : Dict=1.0 , A : Union[str, Any]=recopy_gpta , A : int=None , A : Optional[int]=10 , A : Tuple="gpt2_finetuned.pt" , ) -> Dict: """simple docstring""" __snake_case : Optional[int] = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu' ) __snake_case : Any = RandomSampler(A ) __snake_case : List[Any] = DataLoader(A , sampler=A ) __snake_case : int = max_steps // (len(A )) + 1 __snake_case : Union[str, Any] = 0 __snake_case : List[str] = torch.zeros((1, context_len) , dtype=torch.long , device=A ) __snake_case ,__snake_case ,__snake_case : str = recopy_model(A , A , A ) model.train() if secondary_learner is not None: secondary_learner.to(A ) secondary_learner.eval() __snake_case : Dict = [] __snake_case : Dict = 0 __snake_case : Any = [] __snake_case : Optional[int] = [] # Compute the performance of the transformer model at the beginning __snake_case : List[str] = compute_perplexity(A , A , A ) test_perps.append(A ) print('Test perplexity, step' , A , ':' , A ) for epoch in range(int(A ) ): for step, example in enumerate(A ): torch.cuda.empty_cache() __snake_case : Optional[int] = random.randint(0 , example.size(2 ) - context_len - 1 ) __snake_case : int = example[0, 0, start : start + context_len] lm_optimizer.zero_grad() __snake_case : Any = model(A , labels=A ) __snake_case : Tuple = True if secondary_learner is not None: __snake_case : Optional[int] = secondary_learner.forward( torch.tensor(A , dtype=torch.long , device=A ).unsqueeze(0 ) )[0].item() observed_qs.append(float(A ) ) # Here we implement the simple non-constant threshold for the predicted IG(X) value # We will decay the selectivity of our secondary learner filter from # 1 standard deviation above average to 1 below average after 10 batches. if global_step == 10: __snake_case : Dict = -1 if predicted_q < threshold: __snake_case : Tuple = False # If we passed the filter, add the context to the batch! if do_backprop: contexts.append(np.array(context.cpu() ) ) __snake_case : Optional[int] = outputs[0] lm_loss.backward() examples += 1 del outputs # Once the batch is filled with enough contexts, backprop on the batch. if examples == batch_size: torch.cuda.empty_cache() __snake_case : Any = 0 # Do LM backprop torch.nn.utils.clip_grad_norm_(model.parameters() , 3.0 ) lm_optimizer.step() lm_scheduler.step() # Update learning rate schedule global_step += 1 # Compute the performance of the transformer model at this batch if global_step % eval_interval == 0: __snake_case : Tuple = compute_perplexity(A , A , A ) test_perps.append(A ) print('Test perplexity, step' , A , ':' , A ) # Break out of the loop after 60 batches if max_steps > 0 and global_step > 60: break if max_steps > 0 and global_step > 60: break # save finetuned transformer model torch.save(model.state_dict() , A ) torch.cuda.empty_cache() # Do some cleaning up so we can reinitialize for the next run of this function del lm_optimizer del lm_scheduler return model def _SCREAMING_SNAKE_CASE ( ) -> Dict: """simple docstring""" __snake_case : str = argparse.ArgumentParser(description='Fine-tune a transformer model with IGF on a language modeling task' ) # Required parameters parser.add_argument( '--data_dir' , default=A , type=A , required=A , help='The input data dir. Should contain data files for WikiText.' , ) parser.add_argument( '--model_name_or_path' , default=A , type=A , required=A , help='Path to pretrained model or model identifier from huggingface.co/models' , ) parser.add_argument( '--data_file' , type=A , default=A , help=( 'A jbl file containing tokenized data which can be split as objective dataset, ' 'train_dataset and test_dataset.' ) , ) parser.add_argument( '--igf_data_file' , type=A , default=A , help='A jbl file containing the context and information gain pairs to train secondary learner.' , ) parser.add_argument( '--output_dir' , default=A , type=A , required=A , help='The output directory where the final fine-tuned model is stored.' , ) parser.add_argument( '--tokenizer_name' , default=A , type=A , help='Pretrained tokenizer name or path if not the same as model_name' , ) parser.add_argument('--seed' , type=A , default=A , help='A seed for reproducible training.' ) parser.add_argument( '--context_len' , default=32 , type=A , help=( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) , ) parser.add_argument( '--size_objective_set' , default=1_00 , type=A , help='number of articles that are long enough to be used as our objective set' , ) parser.add_argument( '--eval_freq' , default=1_00 , type=A , help='secondary model evaluation is triggered at eval_freq' ) parser.add_argument('--max_steps' , default=10_00 , type=A , help='To calculate training epochs' ) parser.add_argument( '--secondary_learner_batch_size' , default=1_28 , type=A , help='batch size of training data for secondary learner' , ) parser.add_argument( '--batch_size' , default=16 , type=A , help='batch size of training data of language model(gpt2) ' ) parser.add_argument( '--eval_interval' , default=10 , type=A , help=( 'decay the selectivity of our secondary learner filter from' '1 standard deviation above average to 1 below average after 10 batches' ) , ) parser.add_argument( '--number' , default=1_00 , type=A , help='The number of examples split to be used as objective_set/test_data' ) parser.add_argument( '--min_len' , default=10_26 , type=A , help='The minimum length of the article to be used as objective set' ) parser.add_argument( '--secondary_learner_max_epochs' , default=15 , type=A , help='number of epochs to train secondary learner' ) parser.add_argument('--trim' , default=A , type=A , help='truncate the example if it exceeds context length' ) parser.add_argument( '--threshold' , default=1.0 , type=A , help=( 'The threshold value used by secondary learner to filter the train_data and allow only' ' informative data as input to the model' ) , ) parser.add_argument('--finetuned_model_name' , default='gpt2_finetuned.pt' , type=A , help='finetuned_model_name' ) parser.add_argument( '--recopy_model' , default=A , type=A , help='Reset the model to the original pretrained GPT-2 weights after each iteration' , ) # function calls # Collecting *n* pairs of context and information gain(X, IG(X)) for training the secondary learner generate_n_pairs( context_len=32 , max_steps=10 , size_objective_set=1_00 , min_len=10_26 , trim=A , data_file='data/tokenized_stories_train_wikitext103.jbl' , igf_data_file='igf_context_pairs.jbl' , ) # Load train data for secondary learner __snake_case : Tuple = joblib.load('data/IGF_values.jbl' ) # Train secondary learner __snake_case : Tuple = training_secondary_learner( A , secondary_learner_max_epochs=15 , secondary_learner_batch_size=1_28 , eval_freq=1_00 , igf_model_path='igf_model.pt' , ) # load pretrained gpt2 model __snake_case : List[Any] = GPTaLMHeadModel.from_pretrained('gpt2' ) set_seed(42 ) # Generate train and test data to train and evaluate gpt2 model __snake_case ,__snake_case : Dict = generate_datasets( context_len=32 , file='data/tokenized_stories_train_wikitext103.jbl' , number=1_00 , min_len=10_26 , trim=A ) # fine-tuning of the gpt2 model using igf (Information Gain Filtration) finetune( A , A , A , context_len=32 , max_steps=10_00 , batch_size=16 , threshold=1.0 , recopy_model=A , secondary_learner=A , eval_interval=10 , finetuned_model_name='gpt2_finetuned.pt' , ) if __name__ == "__main__": main()
61
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor class a_ ( unittest.TestCase ): def __init__(self , __a , __a=7 , __a=3 , __a=1_8 , __a=3_0 , __a=4_0_0 , __a=True , __a=None , __a=True , __a=None , __a=True , __a=[0.48_145_466, 0.4_578_275, 0.40_821_073] , __a=[0.26_862_954, 0.26_130_258, 0.27_577_711] , __a=True , ) -> List[Any]: """simple docstring""" __snake_case : Tuple = size if size is not None else {'height': 2_2_4, 'width': 2_2_4} __snake_case : Any = crop_size if crop_size is not None else {'height': 1_8, 'width': 1_8} __snake_case : Optional[int] = parent __snake_case : Dict = batch_size __snake_case : str = num_channels __snake_case : Optional[Any] = image_size __snake_case : Optional[int] = min_resolution __snake_case : Tuple = max_resolution __snake_case : Optional[int] = do_resize __snake_case : Optional[int] = size __snake_case : Union[str, Any] = do_center_crop __snake_case : List[Any] = crop_size __snake_case : int = do_normalize __snake_case : Optional[Any] = image_mean __snake_case : str = image_std __snake_case : Optional[Any] = do_convert_rgb def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def SCREAMING_SNAKE_CASE__ (self , __a=False , __a=False , __a=False) -> List[str]: """simple docstring""" assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" if equal_resolution: __snake_case : Optional[int] = [] for i in range(self.batch_size): image_inputs.append( np.random.randint( 2_5_5 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta)) else: __snake_case : Dict = [] for i in range(self.batch_size): __snake_case ,__snake_case : Optional[Any] = np.random.choice(np.arange(self.min_resolution , self.max_resolution) , 2) image_inputs.append(np.random.randint(2_5_5 , size=(self.num_channels, width, height) , dtype=np.uinta)) if not numpify and not torchify: # PIL expects the channel dimension as last dimension __snake_case : int = [Image.fromarray(np.moveaxis(__a , 0 , -1)) for x in image_inputs] if torchify: __snake_case : List[Any] = [torch.from_numpy(__a) for x in image_inputs] return image_inputs @require_torch @require_vision class a_ ( UpperCamelCase_ , unittest.TestCase ): _snake_case = ChineseCLIPImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : Union[str, Any] = ChineseCLIPImageProcessingTester(self , do_center_crop=__a) @property def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : int = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(__a , 'do_resize')) self.assertTrue(hasattr(__a , 'size')) self.assertTrue(hasattr(__a , 'do_center_crop')) self.assertTrue(hasattr(__a , 'center_crop')) self.assertTrue(hasattr(__a , 'do_normalize')) self.assertTrue(hasattr(__a , 'image_mean')) self.assertTrue(hasattr(__a , 'image_std')) self.assertTrue(hasattr(__a , 'do_convert_rgb')) def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size , {'height': 2_2_4, 'width': 2_2_4}) self.assertEqual(image_processor.crop_size , {'height': 1_8, 'width': 1_8}) __snake_case : List[str] = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 , crop_size=8_4) self.assertEqual(image_processor.size , {'shortest_edge': 4_2}) self.assertEqual(image_processor.crop_size , {'height': 8_4, 'width': 8_4}) def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" __snake_case : List[Any] = self.image_processing_class(**self.image_processor_dict) # create random PIL images __snake_case : Optional[Any] = self.image_processor_tester.prepare_inputs(equal_resolution=__a) for image in image_inputs: self.assertIsInstance(__a , Image.Image) # Test not batched input __snake_case : 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __snake_case : List[Any] = image_processing(__a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" __snake_case : Union[str, Any] = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors __snake_case : Optional[int] = self.image_processor_tester.prepare_inputs(equal_resolution=__a , numpify=__a) for image in image_inputs: self.assertIsInstance(__a , np.ndarray) # Test not batched input __snake_case : List[Any] = image_processing(image_inputs[0] , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __snake_case : int = image_processing(__a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : Any = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors __snake_case : Tuple = self.image_processor_tester.prepare_inputs(equal_resolution=__a , torchify=__a) for image in image_inputs: self.assertIsInstance(__a , torch.Tensor) # Test not batched input __snake_case : Any = image_processing(image_inputs[0] , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __snake_case : Union[str, Any] = image_processing(__a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) @require_torch @require_vision class a_ ( UpperCamelCase_ , unittest.TestCase ): _snake_case = ChineseCLIPImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" __snake_case : Optional[Any] = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=__a) __snake_case : List[Any] = 3 @property def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : Any = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(__a , 'do_resize')) self.assertTrue(hasattr(__a , 'size')) self.assertTrue(hasattr(__a , 'do_center_crop')) self.assertTrue(hasattr(__a , 'center_crop')) self.assertTrue(hasattr(__a , 'do_normalize')) self.assertTrue(hasattr(__a , 'image_mean')) self.assertTrue(hasattr(__a , 'image_std')) self.assertTrue(hasattr(__a , 'do_convert_rgb')) def SCREAMING_SNAKE_CASE__ (self) -> Tuple: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : List[Any] = self.image_processing_class(**self.image_processor_dict) # create random PIL images __snake_case : Union[str, Any] = self.image_processor_tester.prepare_inputs(equal_resolution=__a) for image in image_inputs: self.assertIsInstance(__a , Image.Image) # Test not batched input __snake_case : Optional[int] = image_processing(image_inputs[0] , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __snake_case : Optional[int] = image_processing(__a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , )
61
1
'''simple docstring''' # Copyright 2021 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from packaging import version from .. import __version__ from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD from .doc import ( add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, copy_func, replace_return_docstrings, ) from .generic import ( ContextManagers, ExplicitEnum, ModelOutput, PaddingStrategy, TensorType, add_model_info_to_auto_map, cached_property, can_return_loss, expand_dims, find_labels, flatten_dict, infer_framework, is_jax_tensor, is_numpy_array, is_tensor, is_tf_symbolic_tensor, is_tf_tensor, is_torch_device, is_torch_dtype, is_torch_tensor, reshape, squeeze, strtobool, tensor_size, to_numpy, to_py_obj, transpose, working_or_temp_dir, ) from .hub import ( CLOUDFRONT_DISTRIB_PREFIX, DISABLE_TELEMETRY, HF_MODULES_CACHE, HUGGINGFACE_CO_PREFIX, HUGGINGFACE_CO_RESOLVE_ENDPOINT, PYTORCH_PRETRAINED_BERT_CACHE, PYTORCH_TRANSFORMERS_CACHE, S3_BUCKET_PREFIX, TRANSFORMERS_CACHE, TRANSFORMERS_DYNAMIC_MODULE_NAME, EntryNotFoundError, PushToHubMixin, RepositoryNotFoundError, RevisionNotFoundError, cached_file, default_cache_path, define_sagemaker_information, download_url, extract_commit_hash, get_cached_models, get_file_from_repo, get_full_repo_name, has_file, http_user_agent, is_offline_mode, is_remote_url, move_cache, send_example_telemetry, try_to_load_from_cache, ) from .import_utils import ( ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, TORCH_FX_REQUIRED_VERSION, USE_JAX, USE_TF, USE_TORCH, DummyObject, OptionalDependencyNotAvailable, _LazyModule, ccl_version, direct_transformers_import, get_torch_version, is_accelerate_available, is_apex_available, is_bitsandbytes_available, is_bsa_available, is_coloredlogs_available, is_cython_available, is_datasets_available, is_decord_available, is_detectrona_available, is_faiss_available, is_flax_available, is_ftfy_available, is_in_notebook, is_ipex_available, is_jieba_available, is_jumanpp_available, is_kenlm_available, is_keras_nlp_available, is_librosa_available, is_natten_available, is_ninja_available, is_onnx_available, is_openai_available, is_optimum_available, is_pandas_available, is_peft_available, is_phonemizer_available, is_protobuf_available, is_psutil_available, is_pyanvml_available, is_pyctcdecode_available, is_pytesseract_available, is_pytest_available, is_pytorch_quantization_available, is_rjieba_available, is_sacremoses_available, is_safetensors_available, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_scipy_available, is_sentencepiece_available, is_seqio_available, is_sklearn_available, is_soundfile_availble, is_spacy_available, is_speech_available, is_sudachi_available, is_tensorflow_probability_available, is_tensorflow_text_available, is_tfaonnx_available, is_tf_available, is_timm_available, is_tokenizers_available, is_torch_available, is_torch_bfaa_available, is_torch_bfaa_cpu_available, is_torch_bfaa_gpu_available, is_torch_compile_available, is_torch_cuda_available, is_torch_fx_available, is_torch_fx_proxy, is_torch_mps_available, is_torch_neuroncore_available, is_torch_tensorrt_fx_available, is_torch_tfaa_available, is_torch_tpu_available, is_torchaudio_available, is_torchdistx_available, is_torchdynamo_available, is_torchvision_available, is_training_run_on_sagemaker, is_vision_available, requires_backends, torch_only_method, ) __A = '''pytorch_model.bin''' __A = '''pytorch_model.bin.index.json''' __A = '''adapter_config.json''' __A = '''adapter_model.bin''' __A = '''adapter_model.safetensors''' __A = '''tf_model.h5''' __A = '''tf_model.h5.index.json''' __A = '''model.ckpt''' __A = '''flax_model.msgpack''' __A = '''flax_model.msgpack.index.json''' __A = '''model.safetensors''' __A = '''model.safetensors.index.json''' __A = '''config.json''' __A = '''preprocessor_config.json''' __A = FEATURE_EXTRACTOR_NAME __A = '''generation_config.json''' __A = '''modelcard.json''' __A = '''▁''' __A = SENTENCEPIECE_UNDERLINE # Kept for backward compatibility __A = [ [[0, 1, 0, 1], [1, 0, 0, 1]] ] * 2 # Needs to have 0s and 1s only since XLM uses it for langs too. __A = [[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]] __A = [[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]] def _SCREAMING_SNAKE_CASE ( A : Optional[int] ) -> List[Any]: """simple docstring""" if version.parse(A ) < version.parse(A ): if "dev" in min_version: __snake_case : Optional[Any] = ( 'This example requires a source install from HuggingFace Transformers (see ' '`https://huggingface.co/docs/transformers/installation#install-from-source`),' ) else: __snake_case : Union[str, Any] = F"""This example requires a minimum version of {min_version},""" error_message += F""" but the version found is {__version__}.\n""" raise ImportError( error_message + 'Check out https://github.com/huggingface/transformers/tree/main/examples#important-note for the examples corresponding to other ' 'versions of HuggingFace Transformers.' )
61
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { '''sayakpaul/vit-msn-base''': '''https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json''', # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class a_ ( UpperCamelCase_ ): _snake_case = """vit_msn""" def __init__(self , __a=7_6_8 , __a=1_2 , __a=1_2 , __a=3_0_7_2 , __a="gelu" , __a=0.0 , __a=0.0 , __a=0.02 , __a=1E-06 , __a=2_2_4 , __a=1_6 , __a=3 , __a=True , **__a , ) -> Any: """simple docstring""" super().__init__(**__a) __snake_case : List[str] = hidden_size __snake_case : Optional[int] = num_hidden_layers __snake_case : Optional[Any] = num_attention_heads __snake_case : str = intermediate_size __snake_case : List[str] = hidden_act __snake_case : List[Any] = hidden_dropout_prob __snake_case : Tuple = attention_probs_dropout_prob __snake_case : List[str] = initializer_range __snake_case : Optional[int] = layer_norm_eps __snake_case : Dict = image_size __snake_case : int = patch_size __snake_case : Dict = num_channels __snake_case : Tuple = qkv_bias
61
1
'''simple docstring''' from math import factorial def _SCREAMING_SNAKE_CASE ( A : int = 20 ) -> int: """simple docstring""" __snake_case : Union[str, Any] = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... __snake_case : Tuple = n // 2 return int(factorial(A ) / (factorial(A ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(2_0)) else: try: __A = int(sys.argv[1]) print(solution(n)) except ValueError: print('''Invalid entry - please enter a number.''')
61
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( A : float , A : list[float] ) -> float: """simple docstring""" if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) __snake_case : List[str] = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(A ) ) return round(A , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
61
1
'''simple docstring''' from __future__ import annotations def _SCREAMING_SNAKE_CASE ( A : list , A : int , A : int , A : int ) -> list: """simple docstring""" __snake_case : List[Any] = [] __snake_case ,__snake_case : Optional[int] = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0 ) ) __snake_case : Optional[int] = result + left + right return input_list def _SCREAMING_SNAKE_CASE ( A : list ) -> list: """simple docstring""" if len(A ) <= 1: return input_list __snake_case : Any = list(A ) # iteration for two-way merging __snake_case : Tuple = 2 while p <= len(A ): # getting low, high and middle value for merge-sort of single list for i in range(0 , len(A ) , A ): __snake_case : Union[str, Any] = i __snake_case : Tuple = i + p - 1 __snake_case : Dict = (low + high + 1) // 2 __snake_case : int = merge(A , A , A , A ) # final merge of last two parts if p * 2 >= len(A ): __snake_case : str = i __snake_case : Any = merge(A , 0 , A , len(A ) - 1 ) break p *= 2 return input_list if __name__ == "__main__": __A = input('''Enter numbers separated by a comma:\n''').strip() if user_input == "": __A = [] else: __A = [int(item.strip()) for item in user_input.split(''',''')] print(iter_merge_sort(unsorted))
61
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __A = { '''configuration_distilbert''': [ '''DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DistilBertConfig''', '''DistilBertOnnxConfig''', ], '''tokenization_distilbert''': ['''DistilBertTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ['''DistilBertTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ '''DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''DistilBertForMaskedLM''', '''DistilBertForMultipleChoice''', '''DistilBertForQuestionAnswering''', '''DistilBertForSequenceClassification''', '''DistilBertForTokenClassification''', '''DistilBertModel''', '''DistilBertPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ '''TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFDistilBertForMaskedLM''', '''TFDistilBertForMultipleChoice''', '''TFDistilBertForQuestionAnswering''', '''TFDistilBertForSequenceClassification''', '''TFDistilBertForTokenClassification''', '''TFDistilBertMainLayer''', '''TFDistilBertModel''', '''TFDistilBertPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ '''FlaxDistilBertForMaskedLM''', '''FlaxDistilBertForMultipleChoice''', '''FlaxDistilBertForQuestionAnswering''', '''FlaxDistilBertForSequenceClassification''', '''FlaxDistilBertForTokenClassification''', '''FlaxDistilBertModel''', '''FlaxDistilBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_distilbert import ( DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DistilBertConfig, DistilBertOnnxConfig, ) from .tokenization_distilbert import DistilBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_distilbert_fast import DistilBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_distilbert import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, DistilBertPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertMainLayer, TFDistilBertModel, TFDistilBertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, FlaxDistilBertPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
61
1
'''simple docstring''' import re def _SCREAMING_SNAKE_CASE ( A : str ) -> str: """simple docstring""" if len(re.findall('[ATCG]' , A ) ) != len(A ): raise ValueError('Invalid Strand' ) return dna.translate(dna.maketrans('ATCG' , 'TAGC' ) ) if __name__ == "__main__": import doctest doctest.testmod()
61
'''simple docstring''' # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. __A = abspath(join(dirname(dirname(__file__)), '''src''')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='''ignore''', category=FutureWarning) def _SCREAMING_SNAKE_CASE ( A : Tuple ) -> str: """simple docstring""" from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(A ) def _SCREAMING_SNAKE_CASE ( A : int ) -> Optional[int]: """simple docstring""" from diffusers.utils.testing_utils import pytest_terminal_summary_main __snake_case : Any = terminalreporter.config.getoption('--make-reports' ) if make_reports: pytest_terminal_summary_main(A , id=A )
61
1
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process __A = logging.getLogger(__name__) @dataclass class a_ : _snake_case = field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} ) _snake_case = field( default=UpperCamelCase_ , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) _snake_case = field( default="""NER""" , metadata={"""help""": """Task type to fine tune in training (e.g. NER, POS, etc)"""} ) _snake_case = field( default=UpperCamelCase_ , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} ) _snake_case = field(default=UpperCamelCase_ , metadata={"""help""": """Set this flag to use fast tokenization."""} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. _snake_case = field( default=UpperCamelCase_ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) @dataclass class a_ : _snake_case = field( metadata={"""help""": """The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."""} ) _snake_case = field( default=UpperCamelCase_ , metadata={"""help""": """Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."""} , ) _snake_case = field( default=128 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) _snake_case = field( default=UpperCamelCase_ , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} ) def _SCREAMING_SNAKE_CASE ( ) -> int: """simple docstring""" # 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. __snake_case : List[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. __snake_case ,__snake_case ,__snake_case : List[str] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __snake_case ,__snake_case ,__snake_case : int = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. Use""" ' --overwrite_output_dir to overcome.' ) __snake_case : List[str] = import_module('tasks' ) try: __snake_case : Any = getattr(A , model_args.task_type ) __snake_case : TokenClassificationTask = token_classification_task_clazz() except AttributeError: raise ValueError( F"""Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. """ F"""Available tasks classes are: {TokenClassificationTask.__subclasses__()}""" ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( 'Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('Training/evaluation parameters %s' , A ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task __snake_case : Optional[Any] = token_classification_task.get_labels(data_args.labels ) __snake_case : Dict[int, str] = dict(enumerate(A ) ) __snake_case : Optional[Any] = len(A ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __snake_case : Any = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=A , idalabel=A , labelaid={label: i for i, label in enumerate(A )} , cache_dir=model_args.cache_dir , ) __snake_case : List[str] = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast , ) __snake_case : Optional[int] = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=A , cache_dir=model_args.cache_dir , ) # Get datasets __snake_case : List[Any] = ( TokenClassificationDataset( token_classification_task=A , data_dir=data_args.data_dir , tokenizer=A , labels=A , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) __snake_case : int = ( TokenClassificationDataset( token_classification_task=A , data_dir=data_args.data_dir , tokenizer=A , labels=A , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def align_predictions(A : np.ndarray , A : np.ndarray ) -> Tuple[List[int], List[int]]: __snake_case : str = np.argmax(A , axis=2 ) __snake_case ,__snake_case : int = preds.shape __snake_case : Dict = [[] for _ in range(A )] __snake_case : Union[str, Any] = [[] for _ in range(A )] for i in range(A ): for j in range(A ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(A : EvalPrediction ) -> Dict: __snake_case ,__snake_case : Any = align_predictions(p.predictions , p.label_ids ) return { "accuracy_score": accuracy_score(A , A ), "precision": precision_score(A , A ), "recall": recall_score(A , A ), "f1": fa_score(A , A ), } # Data collator __snake_case : Optional[int] = DataCollatorWithPadding(A , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer __snake_case : Optional[Any] = Trainer( model=A , args=A , train_dataset=A , eval_dataset=A , compute_metrics=A , data_collator=A , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation __snake_case : List[Any] = {} if training_args.do_eval: logger.info('*** Evaluate ***' ) __snake_case : List[str] = trainer.evaluate() __snake_case : Tuple = os.path.join(training_args.output_dir , 'eval_results.txt' ) if trainer.is_world_process_zero(): with open(A , 'w' ) as writer: logger.info('***** Eval results *****' ) for key, value in result.items(): logger.info(' %s = %s' , A , A ) writer.write('%s = %s\n' % (key, value) ) results.update(A ) # Predict if training_args.do_predict: __snake_case : str = TokenClassificationDataset( token_classification_task=A , data_dir=data_args.data_dir , tokenizer=A , labels=A , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , ) __snake_case ,__snake_case ,__snake_case : str = trainer.predict(A ) __snake_case ,__snake_case : List[str] = align_predictions(A , A ) __snake_case : Optional[int] = os.path.join(training_args.output_dir , 'test_results.txt' ) if trainer.is_world_process_zero(): with open(A , 'w' ) as writer: for key, value in metrics.items(): logger.info(' %s = %s' , A , A ) writer.write('%s = %s\n' % (key, value) ) # Save predictions __snake_case : List[str] = os.path.join(training_args.output_dir , 'test_predictions.txt' ) if trainer.is_world_process_zero(): with open(A , 'w' ) as writer: with open(os.path.join(data_args.data_dir , 'test.txt' ) , 'r' ) as f: token_classification_task.write_predictions_to_file(A , A , A ) return results def _SCREAMING_SNAKE_CASE ( A : int ) -> Any: """simple docstring""" # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
61
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __A = { '''configuration_biogpt''': ['''BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BioGptConfig'''], '''tokenization_biogpt''': ['''BioGptTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ '''BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BioGptForCausalLM''', '''BioGptForTokenClassification''', '''BioGptForSequenceClassification''', '''BioGptModel''', '''BioGptPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
61
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) __A = {'''configuration_deit''': ['''DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DeiTConfig''', '''DeiTOnnxConfig''']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ['''DeiTFeatureExtractor'''] __A = ['''DeiTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ '''DEIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''DeiTForImageClassification''', '''DeiTForImageClassificationWithTeacher''', '''DeiTForMaskedImageModeling''', '''DeiTModel''', '''DeiTPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ '''TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFDeiTForImageClassification''', '''TFDeiTForImageClassificationWithTeacher''', '''TFDeiTForMaskedImageModeling''', '''TFDeiTModel''', '''TFDeiTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_deit import DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, DeiTConfig, DeiTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_deit import DeiTFeatureExtractor from .image_processing_deit import DeiTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deit import ( DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, DeiTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deit import ( TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, TFDeiTPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
61
'''simple docstring''' from packaging import version from .import_utils import is_accelerate_available if is_accelerate_available(): import accelerate def _SCREAMING_SNAKE_CASE ( A : Optional[Any] ) -> int: """simple docstring""" if not is_accelerate_available(): return method __snake_case : Optional[Any] = version.parse(accelerate.__version__ ).base_version if version.parse(A ) < version.parse('0.17.0' ): return method def wrapper(self : Optional[Any] , *A : Optional[Any] , **A : Optional[int] ): if hasattr(self , '_hf_hook' ) and hasattr(self._hf_hook , 'pre_forward' ): self._hf_hook.pre_forward(self ) return method(self , *A , **A ) return wrapper
61
1