code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
"""simple docstring""" import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append('''.''') def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( "`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got " f"""{test_file} instead.""" ) __SCREAMING_SNAKE_CASE = components[-1] if not test_fn.endswith("py" ): raise ValueError(f"""`test_file` should be a python file. Got {test_fn} instead.""" ) if not test_fn.startswith("test_modeling_" ): raise ValueError( f"""`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.""" ) __SCREAMING_SNAKE_CASE = components[:-1] + [test_fn.replace(".py" , "" )] __SCREAMING_SNAKE_CASE = ".".join(lowerCAmelCase_ ) return test_module_path def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_module_path(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = importlib.import_module(lowerCAmelCase_ ) return test_module def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = get_test_module(lowerCAmelCase_ ) for attr in dir(lowerCAmelCase_ ): if attr.endswith("ModelTester" ): tester_classes.append(getattr(lowerCAmelCase_ , lowerCAmelCase_ ) ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = get_test_module(lowerCAmelCase_ ) for attr in dir(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = getattr(lowerCAmelCase_ , lowerCAmelCase_ ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). __SCREAMING_SNAKE_CASE = getattr(lowerCAmelCase_ , "all_model_classes" , [] ) if len(lowerCAmelCase_ ) > 0: test_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = test_class() if hasattr(lowerCAmelCase_ , "setUp" ): test.setUp() __SCREAMING_SNAKE_CASE = None if hasattr(lowerCAmelCase_ , "model_tester" ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: __SCREAMING_SNAKE_CASE = test.model_tester.__class__ return model_tester def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [] for test_class in test_classes: __SCREAMING_SNAKE_CASE = get_model_tester_from_test_class(lowerCAmelCase_ ) if tester_class is not None: tester_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = {test_class: get_model_tester_from_test_class(lowerCAmelCase_ ) for test_class in test_classes} return test_tester_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_model_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { model_class: get_test_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) for model_class in model_classes } return model_test_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_model_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { model_class: get_tester_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) for model_class in model_classes } return model_to_tester_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return o elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return o.__name__ elif isinstance(lowerCAmelCase_ , (list, tuple) ): return [to_json(lowerCAmelCase_ ) for x in o] elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return {to_json(lowerCAmelCase_ ): to_json(lowerCAmelCase_ ) for k, v in o.items()} else: return o
54
"""simple docstring""" import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device a__ : Tuple = False class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" pass @slow @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = VersatileDiffusionImageVariationPipeline.from_pretrained("shi-labs/versatile-diffusion" ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( image=UpperCAmelCase__ , generator=UpperCAmelCase__ , guidance_scale=7.5 , num_inference_steps=5_0 , output_type="numpy" , ).images __SCREAMING_SNAKE_CASE = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __SCREAMING_SNAKE_CASE = np.array([0.0_441, 0.0_469, 0.0_507, 0.0_575, 0.0_632, 0.0_650, 0.0_865, 0.0_909, 0.0_945] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
54
1
"""simple docstring""" a__ : Any = frozenset( [ '''prompt''', '''height''', '''width''', '''guidance_scale''', '''negative_prompt''', '''prompt_embeds''', '''negative_prompt_embeds''', '''cross_attention_kwargs''', ] ) a__ : Optional[int] = frozenset(['''prompt''', '''negative_prompt''']) a__ : Dict = frozenset([]) a__ : int = frozenset(['''image''']) a__ : Union[str, Any] = frozenset( [ '''image''', '''height''', '''width''', '''guidance_scale''', ] ) a__ : Optional[Any] = frozenset(['''image''']) a__ : List[Any] = frozenset( [ '''prompt''', '''image''', '''height''', '''width''', '''guidance_scale''', '''negative_prompt''', '''prompt_embeds''', '''negative_prompt_embeds''', ] ) a__ : str = frozenset(['''prompt''', '''image''', '''negative_prompt''']) a__ : int = frozenset( [ # Text guided image variation with an image mask '''prompt''', '''image''', '''mask_image''', '''height''', '''width''', '''guidance_scale''', '''negative_prompt''', '''prompt_embeds''', '''negative_prompt_embeds''', ] ) a__ : Any = frozenset(['''prompt''', '''image''', '''mask_image''', '''negative_prompt''']) a__ : Optional[int] = frozenset( [ # image variation with an image mask '''image''', '''mask_image''', '''height''', '''width''', '''guidance_scale''', ] ) a__ : Optional[int] = frozenset(['''image''', '''mask_image''']) a__ : str = frozenset( [ '''example_image''', '''image''', '''mask_image''', '''height''', '''width''', '''guidance_scale''', ] ) a__ : str = frozenset(['''example_image''', '''image''', '''mask_image''']) a__ : List[str] = frozenset(['''class_labels''']) a__ : Any = frozenset(['''class_labels''']) a__ : List[str] = frozenset(['''batch_size''']) a__ : Optional[int] = frozenset([]) a__ : List[Any] = frozenset(['''batch_size''']) a__ : List[Any] = frozenset([]) a__ : int = frozenset( [ '''prompt''', '''audio_length_in_s''', '''guidance_scale''', '''negative_prompt''', '''prompt_embeds''', '''negative_prompt_embeds''', '''cross_attention_kwargs''', ] ) a__ : Union[str, Any] = frozenset(['''prompt''', '''negative_prompt''']) a__ : str = frozenset(['''input_tokens''']) a__ : Optional[int] = frozenset(['''input_tokens'''])
54
"""simple docstring""" import importlib.util import json import os import warnings from dataclasses import dataclass, field import torch from ..training_args import TrainingArguments from ..utils import cached_property, is_sagemaker_dp_enabled, logging a__ : Union[str, Any] = logging.get_logger(__name__) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = os.getenv("SM_HP_MP_PARAMETERS" , "{}" ) try: # Parse it and check the field "partitions" is included, it is required for model parallel. __SCREAMING_SNAKE_CASE = json.loads(lowerCAmelCase_ ) if "partitions" not in smp_options: return False except json.JSONDecodeError: return False # Get the sagemaker specific framework parameters from mpi_options variable. __SCREAMING_SNAKE_CASE = os.getenv("SM_FRAMEWORK_PARAMS" , "{}" ) try: # Parse it and check the field "sagemaker_distributed_dataparallel_enabled". __SCREAMING_SNAKE_CASE = json.loads(lowerCAmelCase_ ) if not mpi_options.get("sagemaker_mpi_enabled" , lowerCAmelCase_ ): return False except json.JSONDecodeError: return False # Lastly, check if the `smdistributed` module is present. return importlib.util.find_spec("smdistributed" ) is not None if is_sagemaker_model_parallel_available(): import smdistributed.modelparallel.torch as smp smp.init() @dataclass class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = field( default="" , metadata={"help": "Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer"} , ) def UpperCAmelCase_ ( self : List[str] ) -> Any: super().__post_init__() warnings.warn( "`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use " "`TrainingArguments` instead." , UpperCAmelCase__ , ) @cached_property def UpperCAmelCase_ ( self : List[str] ) -> "torch.device": logger.info("PyTorch: setting up devices" ) if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1: logger.warning( "torch.distributed process group is initialized, but local_rank == -1. " "In order to use Torch DDP, launch your script with `python -m torch.distributed.launch" ) if self.no_cuda: __SCREAMING_SNAKE_CASE = torch.device("cpu" ) __SCREAMING_SNAKE_CASE = 0 elif is_sagemaker_model_parallel_available(): __SCREAMING_SNAKE_CASE = smp.local_rank() __SCREAMING_SNAKE_CASE = torch.device("cuda" , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = 1 elif is_sagemaker_dp_enabled(): import smdistributed.dataparallel.torch.torch_smddp # noqa: F401 torch.distributed.init_process_group(backend="smddp" , timeout=self.ddp_timeout_delta ) __SCREAMING_SNAKE_CASE = int(os.getenv("SMDATAPARALLEL_LOCAL_RANK" ) ) __SCREAMING_SNAKE_CASE = torch.device("cuda" , self.local_rank ) __SCREAMING_SNAKE_CASE = 1 elif self.local_rank == -1: # if n_gpu is > 1 we'll use nn.DataParallel. # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0` # Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will # trigger an error that a device index is missing. Index 0 takes into account the # GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0` # will use the first GPU in that env, i.e. GPU#1 __SCREAMING_SNAKE_CASE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" ) # Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at # the default value. __SCREAMING_SNAKE_CASE = torch.cuda.device_count() else: # Here, we'll use torch.distributed. # Initializes the distributed backend which will take care of synchronizing nodes/GPUs if not torch.distributed.is_initialized(): torch.distributed.init_process_group(backend="nccl" , timeout=self.ddp_timeout_delta ) __SCREAMING_SNAKE_CASE = torch.device("cuda" , self.local_rank ) __SCREAMING_SNAKE_CASE = 1 if device.type == "cuda": torch.cuda.set_device(UpperCAmelCase__ ) return device @property def UpperCAmelCase_ ( self : Dict ) -> Any: if is_sagemaker_model_parallel_available(): return smp.dp_size() return super().world_size @property def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[Any]: return not is_sagemaker_model_parallel_available() @property def UpperCAmelCase_ ( self : Tuple ) -> int: return False
54
1
"""simple docstring""" import mpmath # for roots of unity import numpy as np class UpperCamelCase_ : """simple docstring""" def __init__( self : List[Any] , UpperCAmelCase__ : Optional[Any]=None , UpperCAmelCase__ : int=None ) -> str: # Input as list __SCREAMING_SNAKE_CASE = list(poly_a or [0] )[:] __SCREAMING_SNAKE_CASE = list(poly_b or [0] )[:] # Remove leading zero coefficients while self.polyA[-1] == 0: self.polyA.pop() __SCREAMING_SNAKE_CASE = len(self.polyA ) while self.polyB[-1] == 0: self.polyB.pop() __SCREAMING_SNAKE_CASE = len(self.polyB ) # Add 0 to make lengths equal a power of 2 __SCREAMING_SNAKE_CASE = int( 2 ** np.ceil(np.loga(len(self.polyA ) + len(self.polyB ) - 1 ) ) ) while len(self.polyA ) < self.c_max_length: self.polyA.append(0 ) while len(self.polyB ) < self.c_max_length: self.polyB.append(0 ) # A complex root used for the fourier transform __SCREAMING_SNAKE_CASE = complex(mpmath.root(x=1 , n=self.c_max_length , k=1 ) ) # The product __SCREAMING_SNAKE_CASE = self.__multiply() def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Optional[Any] ) -> str: __SCREAMING_SNAKE_CASE = [[x] for x in self.polyA] if which == "A" else [[x] for x in self.polyB] # Corner case if len(UpperCAmelCase__ ) <= 1: return dft[0] # __SCREAMING_SNAKE_CASE = self.c_max_length // 2 while next_ncol > 0: __SCREAMING_SNAKE_CASE = [[] for i in range(UpperCAmelCase__ )] __SCREAMING_SNAKE_CASE = self.root**next_ncol # First half of next step __SCREAMING_SNAKE_CASE = 1 for j in range(self.c_max_length // (next_ncol * 2) ): for i in range(UpperCAmelCase__ ): new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j] ) current_root *= root # Second half of next step __SCREAMING_SNAKE_CASE = 1 for j in range(self.c_max_length // (next_ncol * 2) ): for i in range(UpperCAmelCase__ ): new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j] ) current_root *= root # Update __SCREAMING_SNAKE_CASE = new_dft __SCREAMING_SNAKE_CASE = next_ncol // 2 return dft[0] def UpperCAmelCase_ ( self : Union[str, Any] ) -> Any: __SCREAMING_SNAKE_CASE = self.__dft("A" ) __SCREAMING_SNAKE_CASE = self.__dft("B" ) __SCREAMING_SNAKE_CASE = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length )]] del dft_a del dft_b # Corner Case if len(inverce_c[0] ) <= 1: return inverce_c[0] # Inverse DFT __SCREAMING_SNAKE_CASE = 2 while next_ncol <= self.c_max_length: __SCREAMING_SNAKE_CASE = [[] for i in range(UpperCAmelCase__ )] __SCREAMING_SNAKE_CASE = self.root ** (next_ncol // 2) __SCREAMING_SNAKE_CASE = 1 # First half of next step for j in range(self.c_max_length // next_ncol ): for i in range(next_ncol // 2 ): # Even positions new_inverse_c[i].append( ( inverce_c[i][j] + inverce_c[i][j + self.c_max_length // next_ncol] ) / 2 ) # Odd positions new_inverse_c[i + next_ncol // 2].append( ( inverce_c[i][j] - inverce_c[i][j + self.c_max_length // next_ncol] ) / (2 * current_root) ) current_root *= root # Update __SCREAMING_SNAKE_CASE = new_inverse_c next_ncol *= 2 # Unpack __SCREAMING_SNAKE_CASE = [round(x[0].real , 8 ) + round(x[0].imag , 8 ) * 1J for x in inverce_c] # Remove leading 0's while inverce_c[-1] == 0: inverce_c.pop() return inverce_c def __str__( self : Optional[int] ) -> Any: __SCREAMING_SNAKE_CASE = "A = " + " + ".join( F"""{coef}*x^{i}""" for coef, i in enumerate(self.polyA[: self.len_A] ) ) __SCREAMING_SNAKE_CASE = "B = " + " + ".join( F"""{coef}*x^{i}""" for coef, i in enumerate(self.polyB[: self.len_B] ) ) __SCREAMING_SNAKE_CASE = "A*B = " + " + ".join( F"""{coef}*x^{i}""" for coef, i in enumerate(self.product ) ) return F"""{a}\n{b}\n{c}""" # Unit tests if __name__ == "__main__": import doctest doctest.testmod()
54
"""simple docstring""" import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Optional[int] ) -> List[str]: # For consistency across different places the DisjunctiveConstraint is called, # dc.token_ids is a list of integers. It is also initialized only by integers. __SCREAMING_SNAKE_CASE = [[1, 2, 4], [1, 2, 3, 4]] __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(UpperCAmelCase__ ) self.assertTrue(isinstance(dc.token_ids , UpperCAmelCase__ ) ) with self.assertRaises(UpperCAmelCase__ ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(UpperCAmelCase__ ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def UpperCAmelCase_ ( self : Any ) -> int: # We can't have constraints that are complete subsets of another. This leads to a preverse # interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint? # It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially # fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm # will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it). __SCREAMING_SNAKE_CASE = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(UpperCAmelCase__ ): DisjunctiveConstraint(UpperCAmelCase__ ) # fails here def UpperCAmelCase_ ( self : List[Any] ) -> Any: __SCREAMING_SNAKE_CASE = [[1, 2, 3], [1, 2, 4]] __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) __SCREAMING_SNAKE_CASE = stepped is True and completed is False and reset is False self.assertTrue(UpperCAmelCase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) __SCREAMING_SNAKE_CASE = stepped is True and completed is False and reset is False self.assertTrue(UpperCAmelCase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(3 ) __SCREAMING_SNAKE_CASE = stepped is True and completed is True and reset is False self.assertTrue(UpperCAmelCase__ ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def UpperCAmelCase_ ( self : str ) -> List[str]: __SCREAMING_SNAKE_CASE = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
54
1
"""simple docstring""" import unittest from huggingface_hub import hf_hub_download from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor from transformers.pipelines import VideoClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_decord, require_tf, require_torch, require_torch_or_tf, require_vision, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf @require_vision @require_decord class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" snake_case__ : List[str] = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : Dict , UpperCAmelCase__ : str , UpperCAmelCase__ : Dict ) -> str: __SCREAMING_SNAKE_CASE = hf_hub_download( repo_id="nateraw/video-demo" , filename="archery.mp4" , repo_type="dataset" ) __SCREAMING_SNAKE_CASE = VideoClassificationPipeline(model=UpperCAmelCase__ , image_processor=UpperCAmelCase__ , top_k=2 ) __SCREAMING_SNAKE_CASE = [ example_video_filepath, "https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4", ] return video_classifier, examples def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any ) -> Optional[int]: for example in examples: __SCREAMING_SNAKE_CASE = video_classifier(UpperCAmelCase__ ) self.assertEqual( UpperCAmelCase__ , [ {"score": ANY(UpperCAmelCase__ ), "label": ANY(UpperCAmelCase__ )}, {"score": ANY(UpperCAmelCase__ ), "label": ANY(UpperCAmelCase__ )}, ] , ) @require_torch def UpperCAmelCase_ ( self : Tuple ) -> Tuple: __SCREAMING_SNAKE_CASE = "hf-internal-testing/tiny-random-VideoMAEForVideoClassification" __SCREAMING_SNAKE_CASE = VideoMAEFeatureExtractor( size={"shortest_edge": 1_0} , crop_size={"height": 1_0, "width": 1_0} ) __SCREAMING_SNAKE_CASE = pipeline( "video-classification" , model=UpperCAmelCase__ , feature_extractor=UpperCAmelCase__ , frame_sampling_rate=4 ) __SCREAMING_SNAKE_CASE = hf_hub_download(repo_id="nateraw/video-demo" , filename="archery.mp4" , repo_type="dataset" ) __SCREAMING_SNAKE_CASE = video_classifier(UpperCAmelCase__ , top_k=2 ) self.assertEqual( nested_simplify(UpperCAmelCase__ , decimals=4 ) , [{"score": 0.5_199, "label": "LABEL_0"}, {"score": 0.4_801, "label": "LABEL_1"}] , ) __SCREAMING_SNAKE_CASE = video_classifier( [ video_file_path, video_file_path, ] , top_k=2 , ) self.assertEqual( nested_simplify(UpperCAmelCase__ , decimals=4 ) , [ [{"score": 0.5_199, "label": "LABEL_0"}, {"score": 0.4_801, "label": "LABEL_1"}], [{"score": 0.5_199, "label": "LABEL_0"}, {"score": 0.4_801, "label": "LABEL_1"}], ] , ) @require_tf def UpperCAmelCase_ ( self : List[str] ) -> List[str]: pass
54
"""simple docstring""" from __future__ import annotations def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = None ): '''simple docstring''' if start is None: __SCREAMING_SNAKE_CASE = 0 if end is None: __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) - 1 if start >= end: return __SCREAMING_SNAKE_CASE = (start + end) // 2 slowsort(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) slowsort(lowerCAmelCase_ , mid + 1 , lowerCAmelCase_ ) if sequence[end] < sequence[mid]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = sequence[mid], sequence[end] slowsort(lowerCAmelCase_ , lowerCAmelCase_ , end - 1 ) if __name__ == "__main__": from doctest import testmod testmod()
54
1
"""simple docstring""" import importlib.util import json import os import warnings from dataclasses import dataclass, field import torch from ..training_args import TrainingArguments from ..utils import cached_property, is_sagemaker_dp_enabled, logging a__ : Union[str, Any] = logging.get_logger(__name__) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = os.getenv("SM_HP_MP_PARAMETERS" , "{}" ) try: # Parse it and check the field "partitions" is included, it is required for model parallel. __SCREAMING_SNAKE_CASE = json.loads(lowerCAmelCase_ ) if "partitions" not in smp_options: return False except json.JSONDecodeError: return False # Get the sagemaker specific framework parameters from mpi_options variable. __SCREAMING_SNAKE_CASE = os.getenv("SM_FRAMEWORK_PARAMS" , "{}" ) try: # Parse it and check the field "sagemaker_distributed_dataparallel_enabled". __SCREAMING_SNAKE_CASE = json.loads(lowerCAmelCase_ ) if not mpi_options.get("sagemaker_mpi_enabled" , lowerCAmelCase_ ): return False except json.JSONDecodeError: return False # Lastly, check if the `smdistributed` module is present. return importlib.util.find_spec("smdistributed" ) is not None if is_sagemaker_model_parallel_available(): import smdistributed.modelparallel.torch as smp smp.init() @dataclass class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = field( default="" , metadata={"help": "Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer"} , ) def UpperCAmelCase_ ( self : List[str] ) -> Any: super().__post_init__() warnings.warn( "`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use " "`TrainingArguments` instead." , UpperCAmelCase__ , ) @cached_property def UpperCAmelCase_ ( self : List[str] ) -> "torch.device": logger.info("PyTorch: setting up devices" ) if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1: logger.warning( "torch.distributed process group is initialized, but local_rank == -1. " "In order to use Torch DDP, launch your script with `python -m torch.distributed.launch" ) if self.no_cuda: __SCREAMING_SNAKE_CASE = torch.device("cpu" ) __SCREAMING_SNAKE_CASE = 0 elif is_sagemaker_model_parallel_available(): __SCREAMING_SNAKE_CASE = smp.local_rank() __SCREAMING_SNAKE_CASE = torch.device("cuda" , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = 1 elif is_sagemaker_dp_enabled(): import smdistributed.dataparallel.torch.torch_smddp # noqa: F401 torch.distributed.init_process_group(backend="smddp" , timeout=self.ddp_timeout_delta ) __SCREAMING_SNAKE_CASE = int(os.getenv("SMDATAPARALLEL_LOCAL_RANK" ) ) __SCREAMING_SNAKE_CASE = torch.device("cuda" , self.local_rank ) __SCREAMING_SNAKE_CASE = 1 elif self.local_rank == -1: # if n_gpu is > 1 we'll use nn.DataParallel. # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0` # Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will # trigger an error that a device index is missing. Index 0 takes into account the # GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0` # will use the first GPU in that env, i.e. GPU#1 __SCREAMING_SNAKE_CASE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" ) # Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at # the default value. __SCREAMING_SNAKE_CASE = torch.cuda.device_count() else: # Here, we'll use torch.distributed. # Initializes the distributed backend which will take care of synchronizing nodes/GPUs if not torch.distributed.is_initialized(): torch.distributed.init_process_group(backend="nccl" , timeout=self.ddp_timeout_delta ) __SCREAMING_SNAKE_CASE = torch.device("cuda" , self.local_rank ) __SCREAMING_SNAKE_CASE = 1 if device.type == "cuda": torch.cuda.set_device(UpperCAmelCase__ ) return device @property def UpperCAmelCase_ ( self : Dict ) -> Any: if is_sagemaker_model_parallel_available(): return smp.dp_size() return super().world_size @property def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[Any]: return not is_sagemaker_model_parallel_available() @property def UpperCAmelCase_ ( self : Tuple ) -> int: return False
54
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if number > 0: raise ValueError("input must be a negative integer" ) __SCREAMING_SNAKE_CASE = len(bin(lowerCAmelCase_ )[3:] ) __SCREAMING_SNAKE_CASE = bin(abs(lowerCAmelCase_ ) - (1 << binary_number_length) )[3:] __SCREAMING_SNAKE_CASE = ( ( "1" + "0" * (binary_number_length - len(lowerCAmelCase_ )) + twos_complement_number ) if number < 0 else "0" ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
54
1
"""simple docstring""" import json import os import unittest from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Dict = BioGptTokenizer snake_case__ : List[str] = False def UpperCAmelCase_ ( self : Dict ) -> int: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __SCREAMING_SNAKE_CASE = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "w</w>", "r</w>", "t</w>", "lo", "low", "er</w>", "low</w>", "lowest</w>", "newer</w>", "wider</w>", "<unk>", ] __SCREAMING_SNAKE_CASE = dict(zip(UpperCAmelCase__ , range(len(UpperCAmelCase__ ) ) ) ) __SCREAMING_SNAKE_CASE = ["l o 123", "lo w 1456", "e r</w> 1789", ""] __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" ) as fp: fp.write(json.dumps(UpperCAmelCase__ ) ) with open(self.merges_file , "w" ) as fp: fp.write("\n".join(UpperCAmelCase__ ) ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : str ) -> Dict: __SCREAMING_SNAKE_CASE = "lower newer" __SCREAMING_SNAKE_CASE = "lower newer" return input_text, output_text def UpperCAmelCase_ ( self : Tuple ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = BioGptTokenizer(self.vocab_file , self.merges_file ) __SCREAMING_SNAKE_CASE = "lower" __SCREAMING_SNAKE_CASE = ["low", "er</w>"] __SCREAMING_SNAKE_CASE = tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokens + ["<unk>"] __SCREAMING_SNAKE_CASE = [1_4, 1_5, 2_0] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : Dict ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = BioGptTokenizer.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = tokenizer.encode("sequence builders" , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.encode("multi-sequence build" , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertTrue(encoded_sentence == [2] + text ) self.assertTrue(encoded_pair == [2] + text + [2] + text_a )
54
"""simple docstring""" import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Any = CLIPTokenizer snake_case__ : Dict = CLIPTokenizerFast snake_case__ : List[Any] = True snake_case__ : Optional[Any] = {} snake_case__ : Dict = False def UpperCAmelCase_ ( self : Any ) -> Any: super().setUp() # fmt: off __SCREAMING_SNAKE_CASE = ["l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"] # fmt: on __SCREAMING_SNAKE_CASE = dict(zip(UpperCAmelCase__ , range(len(UpperCAmelCase__ ) ) ) ) __SCREAMING_SNAKE_CASE = ["#version: 0.2", "l o", "lo w</w>", "e r</w>"] __SCREAMING_SNAKE_CASE = {"unk_token": "<unk>"} __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(UpperCAmelCase__ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(UpperCAmelCase__ ) ) def UpperCAmelCase_ ( self : List[Any] , **UpperCAmelCase__ : Tuple ) -> List[Any]: kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any , **UpperCAmelCase__ : Optional[Any] ) -> List[str]: kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = "lower newer" __SCREAMING_SNAKE_CASE = "lower newer" return input_text, output_text def UpperCAmelCase_ ( self : int ) -> List[str]: __SCREAMING_SNAKE_CASE = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __SCREAMING_SNAKE_CASE = "lower newer" __SCREAMING_SNAKE_CASE = ["lo", "w", "er</w>", "n", "e", "w", "er</w>"] __SCREAMING_SNAKE_CASE = tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokens + [tokenizer.unk_token] __SCREAMING_SNAKE_CASE = [1_0, 2, 1_6, 9, 3, 2, 1_6, 2_0] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , UpperCAmelCase__ ) @require_ftfy def UpperCAmelCase_ ( self : Optional[Any] ) -> int: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = "A\n'll 11p223RF☆ho!!to?'d'd''d of a cat to-$''d." __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways __SCREAMING_SNAKE_CASE = "xa\u0303y" + " " + "x\xe3y" __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Test that the tokenization is identical on unicode of space type __SCREAMING_SNAKE_CASE = [ "\u0009", # (horizontal tab, '\t') "\u000B", # (vertical tab) "\u000C", # (form feed) "\u0020", # (space, ' ') "\u200E", # (left-to-right mark):w "\u200F", # (right-to-left mark) ] for unicode_seq in spaces_unicodes: __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Test that the tokenization is identical on unicode of line break type __SCREAMING_SNAKE_CASE = [ "\u000A", # (line feed, '\n') "\r\n", # (carriage return and line feed, '\r\n') "\u000D", # (carriage return, '\r') "\r", # (carriage return, '\r') "\u000D", # (carriage return, '\r') "\u2028", # (line separator) "\u2029", # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Optional[Any]: # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = "hello" # `hello` is a token in the vocabulary of `pretrained_name` __SCREAMING_SNAKE_CASE = F"""{text_of_1_token} {text_of_1_token}""" __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(UpperCAmelCase__ ) + 1, len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , ) __SCREAMING_SNAKE_CASE = F""" {text}""" __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(UpperCAmelCase__ ) + 1, 1 + len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , ) def UpperCAmelCase_ ( self : str ) -> Optional[int]: # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(UpperCAmelCase__ ) as context: self.rust_tokenizer_class.from_pretrained("robot-test/old-clip-tokenizer" ) self.assertTrue( context.exception.args[0].startswith( "The `backend_tokenizer` provided does not match the expected format." ) ) @require_ftfy def UpperCAmelCase_ ( self : Optional[int] ) -> int: super().test_tokenization_python_rust_equals() def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[Any]: # CLIP always lower cases letters pass
54
1
"""simple docstring""" import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Tuple = logging.get_logger(__name__) a__ : Tuple = { '''xlnet-base-cased''': '''https://huggingface.co/xlnet-base-cased/resolve/main/config.json''', '''xlnet-large-cased''': '''https://huggingface.co/xlnet-large-cased/resolve/main/config.json''', } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : List[Any] = "xlnet" snake_case__ : Tuple = ["mems"] snake_case__ : Optional[Any] = { "n_token": "vocab_size", # Backward compatibility "hidden_size": "d_model", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : str , UpperCAmelCase__ : int=3_2_0_0_0 , UpperCAmelCase__ : List[str]=1_0_2_4 , UpperCAmelCase__ : Union[str, Any]=2_4 , UpperCAmelCase__ : str=1_6 , UpperCAmelCase__ : int=4_0_9_6 , UpperCAmelCase__ : Dict="gelu" , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : Dict="bi" , UpperCAmelCase__ : Tuple=0.02 , UpperCAmelCase__ : Optional[Any]=1E-12 , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : Optional[Any]=5_1_2 , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : List[str]=False , UpperCAmelCase__ : Optional[Any]=False , UpperCAmelCase__ : Optional[Any]=-1 , UpperCAmelCase__ : Optional[Any]=False , UpperCAmelCase__ : str="last" , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : Dict="tanh" , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : Dict=5 , UpperCAmelCase__ : List[Any]=5 , UpperCAmelCase__ : Optional[Any]=5 , UpperCAmelCase__ : Optional[int]=1 , UpperCAmelCase__ : Dict=2 , **UpperCAmelCase__ : str , ) -> Dict: __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = d_model __SCREAMING_SNAKE_CASE = n_layer __SCREAMING_SNAKE_CASE = n_head if d_model % n_head != 0: raise ValueError(F"""'d_model % n_head' ({d_model % n_head}) should be equal to 0""" ) if "d_head" in kwargs: if kwargs["d_head"] != d_model // n_head: raise ValueError( F"""`d_head` ({kwargs['d_head']}) should be equal to `d_model // n_head` ({d_model // n_head})""" ) __SCREAMING_SNAKE_CASE = d_model // n_head __SCREAMING_SNAKE_CASE = ff_activation __SCREAMING_SNAKE_CASE = d_inner __SCREAMING_SNAKE_CASE = untie_r __SCREAMING_SNAKE_CASE = attn_type __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = dropout __SCREAMING_SNAKE_CASE = mem_len __SCREAMING_SNAKE_CASE = reuse_len __SCREAMING_SNAKE_CASE = bi_data __SCREAMING_SNAKE_CASE = clamp_len __SCREAMING_SNAKE_CASE = same_length __SCREAMING_SNAKE_CASE = summary_type __SCREAMING_SNAKE_CASE = summary_use_proj __SCREAMING_SNAKE_CASE = summary_activation __SCREAMING_SNAKE_CASE = summary_last_dropout __SCREAMING_SNAKE_CASE = start_n_top __SCREAMING_SNAKE_CASE = end_n_top __SCREAMING_SNAKE_CASE = bos_token_id __SCREAMING_SNAKE_CASE = pad_token_id __SCREAMING_SNAKE_CASE = eos_token_id if "use_cache" in kwargs: warnings.warn( "The `use_cache` argument is deprecated and will be removed in a future version, use `use_mems_eval`" " instead." , UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = kwargs["use_cache"] __SCREAMING_SNAKE_CASE = use_mems_eval __SCREAMING_SNAKE_CASE = use_mems_train super().__init__(pad_token_id=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , **UpperCAmelCase__ ) @property def UpperCAmelCase_ ( self : List[str] ) -> str: logger.info(F"""The model {self.model_type} is one of the few models that has no sequence length limit.""" ) return -1 @max_position_embeddings.setter def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : str ) -> str: # Message copied from Transformer-XL documentation raise NotImplementedError( F"""The model {self.model_type} is one of the few models that has no sequence length limit.""" )
54
"""simple docstring""" import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( "kwargs, expected" , [ ({"num_shards": 0, "max_num_jobs": 1}, []), ({"num_shards": 10, "max_num_jobs": 1}, [range(10 )]), ({"num_shards": 10, "max_num_jobs": 10}, [range(lowerCAmelCase_ , i + 1 ) for i in range(10 )]), ({"num_shards": 1, "max_num_jobs": 10}, [range(1 )]), ({"num_shards": 10, "max_num_jobs": 3}, [range(0 , 4 ), range(4 , 7 ), range(7 , 10 )]), ({"num_shards": 3, "max_num_jobs": 10}, [range(0 , 1 ), range(1 , 2 ), range(2 , 3 )]), ] , ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = _distribute_shards(**lowerCAmelCase_ ) assert out == expected @pytest.mark.parametrize( "gen_kwargs, max_num_jobs, expected" , [ ({"foo": 0}, 10, [{"foo": 0}]), ({"shards": [0, 1, 2, 3]}, 1, [{"shards": [0, 1, 2, 3]}]), ({"shards": [0, 1, 2, 3]}, 4, [{"shards": [0]}, {"shards": [1]}, {"shards": [2]}, {"shards": [3]}]), ({"shards": [0, 1]}, 4, [{"shards": [0]}, {"shards": [1]}]), ({"shards": [0, 1, 2, 3]}, 2, [{"shards": [0, 1]}, {"shards": [2, 3]}]), ] , ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = _split_gen_kwargs(lowerCAmelCase_ , lowerCAmelCase_ ) assert out == expected @pytest.mark.parametrize( "gen_kwargs, expected" , [ ({"foo": 0}, 1), ({"shards": [0]}, 1), ({"shards": [0, 1, 2, 3]}, 4), ({"shards": [0, 1, 2, 3], "foo": 0}, 4), ({"shards": [0, 1, 2, 3], "other": (0, 1)}, 4), ({"shards": [0, 1, 2, 3], "shards2": [0, 1]}, RuntimeError), ] , ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if expected is RuntimeError: with pytest.raises(lowerCAmelCase_ ): _number_of_shards_in_gen_kwargs(lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = _number_of_shards_in_gen_kwargs(lowerCAmelCase_ ) assert out == expected
54
1
"""simple docstring""" from abc import ABC, abstractmethod from argparse import ArgumentParser class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @staticmethod @abstractmethod def UpperCAmelCase_ ( UpperCAmelCase__ : ArgumentParser ) -> int: raise NotImplementedError() @abstractmethod def UpperCAmelCase_ ( self : int ) -> Optional[int]: raise NotImplementedError()
54
"""simple docstring""" import unittest from transformers.testing_utils import CaptureStdout from transformers.tools.python_interpreter import evaluate def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return x + 2 class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Any ) -> Any: __SCREAMING_SNAKE_CASE = "x = 3" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result == 3 self.assertDictEqual(UpperCAmelCase__ , {"x": 3} ) __SCREAMING_SNAKE_CASE = "x = y" __SCREAMING_SNAKE_CASE = {"y": 5} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 5, "y": 5} ) def UpperCAmelCase_ ( self : Dict ) -> List[str]: __SCREAMING_SNAKE_CASE = "y = add_two(x)" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 5} ) # Won't work without the tool with CaptureStdout() as out: __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result is None assert "tried to execute add_two" in out.out def UpperCAmelCase_ ( self : List[Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = "x = 3" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result == 3 self.assertDictEqual(UpperCAmelCase__ , {"x": 3} ) def UpperCAmelCase_ ( self : str ) -> Any: __SCREAMING_SNAKE_CASE = "test_dict = {'x': x, 'y': add_two(x)}" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 5} ) self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_dict": {"x": 3, "y": 5}} ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = "x = 3\ny = 5" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 5} ) def UpperCAmelCase_ ( self : Any ) -> Any: __SCREAMING_SNAKE_CASE = "text = f'This is x: {x}.'" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == "This is x: 3." self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "text": "This is x: 3."} ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = "if x <= 3:\n y = 2\nelse:\n y = 5" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 2 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 2} ) __SCREAMING_SNAKE_CASE = {"x": 8} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 8, "y": 5} ) def UpperCAmelCase_ ( self : Tuple ) -> str: __SCREAMING_SNAKE_CASE = "test_list = [x, add_two(x)]" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , [3, 5] ) self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_list": [3, 5]} ) def UpperCAmelCase_ ( self : Any ) -> int: __SCREAMING_SNAKE_CASE = "y = x" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result == 3 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 3} ) def UpperCAmelCase_ ( self : Tuple ) -> int: __SCREAMING_SNAKE_CASE = "test_list = [x, add_two(x)]\ntest_list[1]" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_list": [3, 5]} ) __SCREAMING_SNAKE_CASE = "test_dict = {'x': x, 'y': add_two(x)}\ntest_dict['y']" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_dict": {"x": 3, "y": 5}} ) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = "x = 0\nfor i in range(3):\n x = i" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"range": range} , state=UpperCAmelCase__ ) assert result == 2 self.assertDictEqual(UpperCAmelCase__ , {"x": 2, "i": 2} )
54
1
"""simple docstring""" a__ : int = '''Tobias Carryer''' from time import time class UpperCamelCase_ : """simple docstring""" def __init__( self : List[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int=int(time() ) ) -> int: # noqa: B008 __SCREAMING_SNAKE_CASE = multiplier __SCREAMING_SNAKE_CASE = increment __SCREAMING_SNAKE_CASE = modulo __SCREAMING_SNAKE_CASE = seed def UpperCAmelCase_ ( self : List[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = (self.multiplier * self.seed + self.increment) % self.modulo return self.seed if __name__ == "__main__": # Show the LCG in action. a__ : Optional[int] = LinearCongruentialGenerator(1_6_6_4_5_2_5, 1_0_1_3_9_0_4_2_2_3, 2 << 3_1) while True: print(lcg.next_number())
54
"""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__ : str = { '''configuration_roformer''': ['''ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''RoFormerConfig''', '''RoFormerOnnxConfig'''], '''tokenization_roformer''': ['''RoFormerTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = ['''RoFormerTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''RoFormerForCausalLM''', '''RoFormerForMaskedLM''', '''RoFormerForMultipleChoice''', '''RoFormerForQuestionAnswering''', '''RoFormerForSequenceClassification''', '''RoFormerForTokenClassification''', '''RoFormerLayer''', '''RoFormerModel''', '''RoFormerPreTrainedModel''', '''load_tf_weights_in_roformer''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = [ '''TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFRoFormerForCausalLM''', '''TFRoFormerForMaskedLM''', '''TFRoFormerForMultipleChoice''', '''TFRoFormerForQuestionAnswering''', '''TFRoFormerForSequenceClassification''', '''TFRoFormerForTokenClassification''', '''TFRoFormerLayer''', '''TFRoFormerModel''', '''TFRoFormerPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FlaxRoFormerForMaskedLM''', '''FlaxRoFormerForMultipleChoice''', '''FlaxRoFormerForQuestionAnswering''', '''FlaxRoFormerForSequenceClassification''', '''FlaxRoFormerForTokenClassification''', '''FlaxRoFormerModel''', '''FlaxRoFormerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys a__ : int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
54
1
"""simple docstring""" import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [ "encoder.version", "decoder.version", "model.encoder.version", "model.decoder.version", "_float_tensor", "decoder.output_projection.weight", ] for k in ignore_keys: state_dict.pop(lowerCAmelCase_ , lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = emb.weight.shape __SCREAMING_SNAKE_CASE = nn.Linear(lowerCAmelCase_ , lowerCAmelCase_ , bias=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = emb.weight.data return lin_layer def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_="facebook/mbart-large-en-ro" , lowerCAmelCase_=False , lowerCAmelCase_=False ): '''simple docstring''' __SCREAMING_SNAKE_CASE = torch.load(lowerCAmelCase_ , map_location="cpu" )["model"] remove_ignore_keys_(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = state_dict["encoder.embed_tokens.weight"].shape[0] __SCREAMING_SNAKE_CASE = MBartConfig.from_pretrained(lowerCAmelCase_ , vocab_size=lowerCAmelCase_ ) if mbart_aa and finetuned: __SCREAMING_SNAKE_CASE = "relu" __SCREAMING_SNAKE_CASE = state_dict["decoder.embed_tokens.weight"] __SCREAMING_SNAKE_CASE = MBartForConditionalGeneration(lowerCAmelCase_ ) model.model.load_state_dict(lowerCAmelCase_ ) if finetuned: __SCREAMING_SNAKE_CASE = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": a__ : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''fairseq_path''', type=str, help='''bart.large, bart.large.cnn or a path to a model.pt on local filesystem.''' ) parser.add_argument('''pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument( '''--hf_config''', default='''facebook/mbart-large-cc25''', type=str, help='''Which huggingface architecture to use: mbart-large''', ) parser.add_argument('''--mbart_50''', action='''store_true''', help='''whether the model is mMART-50 checkpoint''') parser.add_argument('''--finetuned''', action='''store_true''', help='''whether the model is a fine-tuned checkpoint''') a__ : List[str] = parser.parse_args() a__ : int = convert_fairseq_mbart_checkpoint_from_disk( args.fairseq_path, hf_config_path=args.hf_config, finetuned=args.finetuned, mbart_aa=args.mbart_aa ) model.save_pretrained(args.pytorch_dump_folder_path)
54
"""simple docstring""" # Copyright 2022 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. import argparse import os import subprocess from packaging.version import Version, parse from accelerate.commands.config.config_args import default_config_file, load_config_from_file a__ : Tuple = '''Run commands across TPU VMs for initial setup before running `accelerate launch`.''' def UpperCAmelCase__ (lowerCAmelCase_=None ): '''simple docstring''' if subparsers is not None: __SCREAMING_SNAKE_CASE = subparsers.add_parser("tpu-config" , description=_description ) else: __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("Accelerate tpu-config command" , description=_description ) # Core arguments __SCREAMING_SNAKE_CASE = parser.add_argument_group( "Config Arguments" , "Arguments that can be configured through `accelerate config`." ) config_args.add_argument( "--config_file" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , help="Path to the config file to use for accelerate." , ) config_args.add_argument( "--tpu_name" , default=lowerCAmelCase_ , help="The name of the TPU to use. If not specified, will use the TPU specified in the config file." , ) config_args.add_argument( "--tpu_zone" , default=lowerCAmelCase_ , help="The zone of the TPU to use. If not specified, will use the zone specified in the config file." , ) __SCREAMING_SNAKE_CASE = parser.add_argument_group("TPU Arguments" , "Arguments for options ran inside the TPU." ) pod_args.add_argument( "--use_alpha" , action="store_true" , help="Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`." , ) pod_args.add_argument( "--command_file" , default=lowerCAmelCase_ , help="The path to the file containing the commands to run on the pod on startup." , ) pod_args.add_argument( "--command" , action="append" , nargs="+" , help="A command to run on the pod. Can be passed multiple times." , ) pod_args.add_argument( "--install_accelerate" , action="store_true" , help="Whether to install accelerate on the pod. Defaults to False." , ) pod_args.add_argument( "--accelerate_version" , default="latest" , help="The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify 'dev' to install from GitHub." , ) pod_args.add_argument( "--debug" , action="store_true" , help="If set, will print the command that would be run instead of running it." ) if subparsers is not None: parser.set_defaults(func=lowerCAmelCase_ ) return parser def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = None # Get the default from the config file if it exists. if args.config_file is not None or os.path.isfile(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = load_config_from_file(args.config_file ) if not args.command_file and defaults.command_file is not None and not args.command: __SCREAMING_SNAKE_CASE = defaults.command_file if not args.command and defaults.commands is not None: __SCREAMING_SNAKE_CASE = defaults.commands if not args.tpu_name: __SCREAMING_SNAKE_CASE = defaults.tpu_name if not args.tpu_zone: __SCREAMING_SNAKE_CASE = defaults.tpu_zone if args.accelerate_version == "dev": __SCREAMING_SNAKE_CASE = "git+https://github.com/huggingface/accelerate.git" elif args.accelerate_version == "latest": __SCREAMING_SNAKE_CASE = "accelerate -U" elif isinstance(parse(args.accelerate_version ) , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = f"""accelerate=={args.accelerate_version}""" if not args.command_file and not args.command: raise ValueError("You must specify either a command file or a command to run on the pod." ) if args.command_file: with open(args.command_file , "r" ) as f: __SCREAMING_SNAKE_CASE = [f.read().splitlines()] # To turn list of lists into list of strings if isinstance(args.command[0] , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = [line for cmd in args.command for line in cmd] # Default to the shared folder and install accelerate __SCREAMING_SNAKE_CASE = ["cd /usr/share"] if args.install_accelerate: new_cmd += [f"""pip install {args.accelerate_version}"""] new_cmd += args.command __SCREAMING_SNAKE_CASE = "; ".join(lowerCAmelCase_ ) # Then send it to gcloud # Eventually try to use google-api-core to do this instead of subprocess __SCREAMING_SNAKE_CASE = ["gcloud"] if args.use_alpha: cmd += ["alpha"] cmd += [ "compute", "tpus", "tpu-vm", "ssh", args.tpu_name, "--zone", args.tpu_zone, "--command", args.command, "--worker", "all", ] if args.debug: print(f"""Running {' '.join(lowerCAmelCase_ )}""" ) return subprocess.run(lowerCAmelCase_ ) print("Successfully setup pod." ) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = tpu_command_parser() __SCREAMING_SNAKE_CASE = parser.parse_args() tpu_command_launcher(lowerCAmelCase_ )
54
1
"""simple docstring""" import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device a__ : Tuple = False class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" pass @slow @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = VersatileDiffusionImageVariationPipeline.from_pretrained("shi-labs/versatile-diffusion" ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( image=UpperCAmelCase__ , generator=UpperCAmelCase__ , guidance_scale=7.5 , num_inference_steps=5_0 , output_type="numpy" , ).images __SCREAMING_SNAKE_CASE = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __SCREAMING_SNAKE_CASE = np.array([0.0_441, 0.0_469, 0.0_507, 0.0_575, 0.0_632, 0.0_650, 0.0_865, 0.0_909, 0.0_945] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
54
"""simple docstring""" from abc import ABC, abstractmethod from argparse import ArgumentParser class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @staticmethod @abstractmethod def UpperCAmelCase_ ( UpperCAmelCase__ : ArgumentParser ) -> int: raise NotImplementedError() @abstractmethod def UpperCAmelCase_ ( self : int ) -> Optional[int]: raise NotImplementedError()
54
1
"""simple docstring""" from ..utils import DummyObject, requires_backends class UpperCamelCase_ ( metaclass=UpperCamelCase): """simple docstring""" snake_case__ : Optional[Any] = ["keras_nlp"] def __init__( self : Optional[Any] , *UpperCAmelCase__ : List[Any] , **UpperCAmelCase__ : Union[str, Any] ) -> Optional[int]: requires_backends(self , ["keras_nlp"] )
54
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def UpperCAmelCase__ (lowerCAmelCase_ = 100_0000 , lowerCAmelCase_ = 10 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = defaultdict(lowerCAmelCase_ ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: __SCREAMING_SNAKE_CASE = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: __SCREAMING_SNAKE_CASE = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(lowerCAmelCase_ , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 10 ) if __name__ == "__main__": print(F"{solution() = }")
54
1
"""simple docstring""" import importlib.metadata import operator import re import sys from typing import Optional from packaging import version a__ : str = { '''<''': operator.lt, '''<=''': operator.le, '''==''': operator.eq, '''!=''': operator.ne, '''>=''': operator.ge, '''>''': operator.gt, } def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if got_ver is None or want_ver is None: raise ValueError( f"""Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider""" f""" reinstalling {pkg}.""" ) if not ops[op](version.parse(lowerCAmelCase_ ) , version.parse(lowerCAmelCase_ ) ): raise ImportError( f"""{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}""" ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = None ): '''simple docstring''' __SCREAMING_SNAKE_CASE = f"""\n{hint}""" if hint is not None else "" # non-versioned check if re.match(R"^[\w_\-\d]+$" , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = requirement, None, None else: __SCREAMING_SNAKE_CASE = re.findall(R"^([^!=<>\s]+)([\s!=<>]{1,2}.+)" , lowerCAmelCase_ ) if not match: raise ValueError( "requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but" f""" got {requirement}""" ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = match[0] __SCREAMING_SNAKE_CASE = want_full.split("," ) # there could be multiple requirements __SCREAMING_SNAKE_CASE = {} for w in want_range: __SCREAMING_SNAKE_CASE = re.findall(R"^([\s!=<>]{1,2})(.+)" , lowerCAmelCase_ ) if not match: raise ValueError( "requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23," f""" but got {requirement}""" ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = match[0] __SCREAMING_SNAKE_CASE = want_ver if op not in ops: raise ValueError(f"""{requirement}: need one of {list(ops.keys() )}, but got {op}""" ) # special case if pkg == "python": __SCREAMING_SNAKE_CASE = ".".join([str(lowerCAmelCase_ ) for x in sys.version_info[:3]] ) for op, want_ver in wanted.items(): _compare_versions(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return # check if any version is installed try: __SCREAMING_SNAKE_CASE = importlib.metadata.version(lowerCAmelCase_ ) except importlib.metadata.PackageNotFoundError: raise importlib.metadata.PackageNotFoundError( f"""The '{requirement}' distribution was not found and is required by this application. {hint}""" ) # check that the right version is installed if version number or a range was provided if want_ver is not None: for op, want_ver in wanted.items(): _compare_versions(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = "Try: pip install transformers -U or pip install -e '.[dev]' if you're working with git main" return require_version(lowerCAmelCase_ , lowerCAmelCase_ )
54
"""simple docstring""" import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html a__ : List[str] = '''platform''' import jax import jax.numpy as jnp import numpy as np from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel @require_flax class UpperCamelCase_ : """simple docstring""" snake_case__ : Dict = PegasusConfig snake_case__ : Union[str, Any] = {} snake_case__ : Any = "gelu" def __init__( self : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int=1_3 , UpperCAmelCase__ : Optional[int]=7 , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : Any=False , UpperCAmelCase__ : List[Any]=9_9 , UpperCAmelCase__ : int=3_2 , UpperCAmelCase__ : Dict=5 , UpperCAmelCase__ : Optional[int]=4 , UpperCAmelCase__ : List[Any]=3_7 , UpperCAmelCase__ : int=0.1 , UpperCAmelCase__ : int=0.1 , UpperCAmelCase__ : List[Any]=2_0 , UpperCAmelCase__ : int=2 , UpperCAmelCase__ : List[Any]=1 , UpperCAmelCase__ : Optional[Any]=0 , ) -> Any: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = eos_token_id __SCREAMING_SNAKE_CASE = pad_token_id __SCREAMING_SNAKE_CASE = bos_token_id def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ).clip(3 , self.vocab_size ) __SCREAMING_SNAKE_CASE = np.expand_dims(np.array([self.eos_token_id] * self.batch_size ) , 1 ) __SCREAMING_SNAKE_CASE = np.concatenate([input_ids, eos_tensor] , axis=1 ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) __SCREAMING_SNAKE_CASE = prepare_pegasus_inputs_dict(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) return config, inputs_dict def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] ) -> str: __SCREAMING_SNAKE_CASE = 2_0 __SCREAMING_SNAKE_CASE = model_class_name(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.encode(inputs_dict["input_ids"] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) __SCREAMING_SNAKE_CASE = model.init_cache(decoder_input_ids.shape[0] , UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="i4" ) __SCREAMING_SNAKE_CASE = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, :-1] , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, -1:] , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , past_key_values=outputs_cache.past_key_values , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = 2_0 __SCREAMING_SNAKE_CASE = model_class_name(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.encode(inputs_dict["input_ids"] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) __SCREAMING_SNAKE_CASE = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) __SCREAMING_SNAKE_CASE = model.init_cache(decoder_input_ids.shape[0] , UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, :-1] , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, -1:] , UpperCAmelCase__ , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=UpperCAmelCase__ , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=None , lowerCAmelCase_=None , ): '''simple docstring''' if attention_mask is None: __SCREAMING_SNAKE_CASE = np.not_equal(lowerCAmelCase_ , config.pad_token_id ).astype(np.inta ) if decoder_attention_mask is None: __SCREAMING_SNAKE_CASE = np.concatenate( [ np.ones(decoder_input_ids[:, :1].shape , dtype=np.inta ), np.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ).astype(np.inta ), ] , axis=-1 , ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, } @require_flax class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Tuple = ( ( FlaxPegasusForConditionalGeneration, FlaxPegasusModel, ) if is_flax_available() else () ) snake_case__ : Union[str, Any] = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else () snake_case__ : Tuple = True snake_case__ : Union[str, Any] = False snake_case__ : int = False snake_case__ : List[Any] = False def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = FlaxPegasusModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : Tuple ) -> Optional[int]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Tuple: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __SCREAMING_SNAKE_CASE = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) @jax.jit def encode_jitted(UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : int=None , **UpperCAmelCase__ : int ): return model.encode(input_ids=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) with self.subTest("JIT Enabled" ): __SCREAMING_SNAKE_CASE = encode_jitted(**UpperCAmelCase__ ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): __SCREAMING_SNAKE_CASE = encode_jitted(**UpperCAmelCase__ ).to_tuple() self.assertEqual(len(UpperCAmelCase__ ) , len(UpperCAmelCase__ ) ) for jitted_output, output in zip(UpperCAmelCase__ , UpperCAmelCase__ ): self.assertEqual(jitted_output.shape , output.shape ) def UpperCAmelCase_ ( self : Tuple ) -> Any: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.encode(inputs_dict["input_ids"] , inputs_dict["attention_mask"] ) __SCREAMING_SNAKE_CASE = { "decoder_input_ids": inputs_dict["decoder_input_ids"], "decoder_attention_mask": inputs_dict["decoder_attention_mask"], "encoder_outputs": encoder_outputs, } @jax.jit def decode_jitted(UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] ): return model.decode( decoder_input_ids=UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , encoder_outputs=UpperCAmelCase__ , ) with self.subTest("JIT Enabled" ): __SCREAMING_SNAKE_CASE = decode_jitted(**UpperCAmelCase__ ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): __SCREAMING_SNAKE_CASE = decode_jitted(**UpperCAmelCase__ ).to_tuple() self.assertEqual(len(UpperCAmelCase__ ) , len(UpperCAmelCase__ ) ) for jitted_output, output in zip(UpperCAmelCase__ , UpperCAmelCase__ ): self.assertEqual(jitted_output.shape , output.shape ) @slow def UpperCAmelCase_ ( self : Dict ) -> Tuple: for model_class_name in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class_name.from_pretrained("google/pegasus-large" , from_pt=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.ones((1, 1) ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : Optional[int] ) -> List[Any]: __SCREAMING_SNAKE_CASE = FlaxPegasusForConditionalGeneration.from_pretrained("google/pegasus-xsum" ) __SCREAMING_SNAKE_CASE = PegasusTokenizer.from_pretrained("google/pegasus-xsum" ) __SCREAMING_SNAKE_CASE = [ " PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.", " The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" ", ] __SCREAMING_SNAKE_CASE = [ "California's largest electricity provider has turned off power to hundreds of thousands of customers.", "Pop group N-Dubz have revealed they were surprised to get four nominations for this year's Mobo Awards.", ] __SCREAMING_SNAKE_CASE = tokenizer(UpperCAmelCase__ , return_tensors="np" , truncation=UpperCAmelCase__ , max_length=5_1_2 , padding=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate(**UpperCAmelCase__ , num_beams=2 ).sequences __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ ) assert tgt_text == decoded
54
1
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pathlib import Path import torch from ...utils import is_npu_available, is_xpu_available from .config_args import ClusterConfig, default_json_config_file from .config_utils import SubcommandHelpFormatter a__ : Tuple = '''Create a default config file for Accelerate with only a few flags set.''' def UpperCAmelCase__ (lowerCAmelCase_="no" , lowerCAmelCase_ = default_json_config_file , lowerCAmelCase_ = False ): '''simple docstring''' __SCREAMING_SNAKE_CASE = Path(lowerCAmelCase_ ) path.parent.mkdir(parents=lowerCAmelCase_ , exist_ok=lowerCAmelCase_ ) if path.exists(): print( f"""Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.""" ) return False __SCREAMING_SNAKE_CASE = mixed_precision.lower() if mixed_precision not in ["no", "fp16", "bf16", "fp8"]: raise ValueError( f"""`mixed_precision` should be one of 'no', 'fp16', 'bf16', or 'fp8'. Received {mixed_precision}""" ) __SCREAMING_SNAKE_CASE = { "compute_environment": "LOCAL_MACHINE", "mixed_precision": mixed_precision, } if torch.cuda.is_available(): __SCREAMING_SNAKE_CASE = torch.cuda.device_count() __SCREAMING_SNAKE_CASE = num_gpus __SCREAMING_SNAKE_CASE = False if num_gpus > 1: __SCREAMING_SNAKE_CASE = "MULTI_GPU" else: __SCREAMING_SNAKE_CASE = "NO" elif is_xpu_available() and use_xpu: __SCREAMING_SNAKE_CASE = torch.xpu.device_count() __SCREAMING_SNAKE_CASE = num_xpus __SCREAMING_SNAKE_CASE = False if num_xpus > 1: __SCREAMING_SNAKE_CASE = "MULTI_XPU" else: __SCREAMING_SNAKE_CASE = "NO" elif is_npu_available(): __SCREAMING_SNAKE_CASE = torch.npu.device_count() __SCREAMING_SNAKE_CASE = num_npus __SCREAMING_SNAKE_CASE = False if num_npus > 1: __SCREAMING_SNAKE_CASE = "MULTI_NPU" else: __SCREAMING_SNAKE_CASE = "NO" else: __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = "NO" __SCREAMING_SNAKE_CASE = ClusterConfig(**lowerCAmelCase_ ) config.to_json_file(lowerCAmelCase_ ) return path def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = parser.add_parser("default" , parents=lowerCAmelCase_ , help=lowerCAmelCase_ , formatter_class=lowerCAmelCase_ ) parser.add_argument( "--config_file" , default=lowerCAmelCase_ , help=( "The path to use to store the config file. Will default to a file named default_config.yaml in the cache " "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " "with 'huggingface'." ) , dest="save_location" , ) parser.add_argument( "--mixed_precision" , choices=["no", "fp16", "bf16"] , type=lowerCAmelCase_ , help="Whether or not to use mixed precision training. " "Choose between FP16 and BF16 (bfloat16) training. " "BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later." , default="no" , ) parser.set_defaults(func=lowerCAmelCase_ ) return parser def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = write_basic_config(args.mixed_precision , args.save_location ) if config_file: print(f"""accelerate configuration saved at {config_file}""" )
54
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ = 100_0000 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = set(range(3 , lowerCAmelCase_ , 2 ) ) primes.add(2 ) for p in range(3 , lowerCAmelCase_ , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , lowerCAmelCase_ , lowerCAmelCase_ ) ) ) __SCREAMING_SNAKE_CASE = [float(lowerCAmelCase_ ) for n in range(limit + 1 )] for p in primes: for n in range(lowerCAmelCase_ , limit + 1 , lowerCAmelCase_ ): phi[n] *= 1 - 1 / p return int(sum(phi[2:] ) ) if __name__ == "__main__": print(F"{solution() = }")
54
1
"""simple docstring""" import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel from transformers.models.esm.modeling_esm import ( ESM_PRETRAINED_MODEL_ARCHIVE_LIST, EsmEmbeddings, create_position_ids_from_input_ids, ) class UpperCamelCase_ : """simple docstring""" def __init__( self : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[Any]=1_3 , UpperCAmelCase__ : int=7 , UpperCAmelCase__ : Optional[int]=False , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : int=False , UpperCAmelCase__ : Any=True , UpperCAmelCase__ : List[str]=3_3 , UpperCAmelCase__ : Dict=3_2 , UpperCAmelCase__ : Optional[Any]=5 , UpperCAmelCase__ : Union[str, Any]=4 , UpperCAmelCase__ : Optional[int]=3_7 , UpperCAmelCase__ : List[str]="gelu" , UpperCAmelCase__ : List[Any]=0.1 , UpperCAmelCase__ : Optional[int]=0.1 , UpperCAmelCase__ : str=5_1_2 , UpperCAmelCase__ : Dict=1_6 , UpperCAmelCase__ : List[str]=2 , UpperCAmelCase__ : str=0.02 , UpperCAmelCase__ : str=3 , UpperCAmelCase__ : List[Any]=4 , UpperCAmelCase__ : str=None , ) -> Optional[int]: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = scope def UpperCAmelCase_ ( self : str ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self : Union[str, Any] ) -> Dict: return EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , pad_token_id=1 , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : Any , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict ) -> List[Any]: __SCREAMING_SNAKE_CASE = EsmModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = EsmForMaskedLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = EsmForTokenClassification(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self : Tuple ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : int = False snake_case__ : List[str] = ( ( EsmForMaskedLM, EsmModel, EsmForSequenceClassification, EsmForTokenClassification, ) if is_torch_available() else () ) snake_case__ : str = () snake_case__ : List[str] = ( { "feature-extraction": EsmModel, "fill-mask": EsmForMaskedLM, "text-classification": EsmForSequenceClassification, "token-classification": EsmForTokenClassification, "zero-shot": EsmForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : List[str] = True def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = EsmModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : Optional[int] ) -> str: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] ) -> Tuple: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __SCREAMING_SNAKE_CASE = type self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : Optional[Any] ) -> List[str]: for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = EsmModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs()[0] __SCREAMING_SNAKE_CASE = EsmEmbeddings(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.as_tensor([[1_2, 3_1, 1_3, model.padding_idx]] ) __SCREAMING_SNAKE_CASE = torch.as_tensor( [ [ 0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx, ] ] ) __SCREAMING_SNAKE_CASE = create_position_ids_from_input_ids(UpperCAmelCase__ , model.padding_idx ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(UpperCAmelCase__ , UpperCAmelCase__ ) ) ) def UpperCAmelCase_ ( self : Optional[int] ) -> Any: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs()[0] __SCREAMING_SNAKE_CASE = EsmEmbeddings(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.empty(2 , 4 , 3_0 ) __SCREAMING_SNAKE_CASE = [ 0 + embeddings.padding_idx + 1, 1 + embeddings.padding_idx + 1, 2 + embeddings.padding_idx + 1, 3 + embeddings.padding_idx + 1, ] __SCREAMING_SNAKE_CASE = torch.as_tensor([expected_single_positions, expected_single_positions] ) __SCREAMING_SNAKE_CASE = embeddings.create_position_ids_from_inputs_embeds(UpperCAmelCase__ ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(UpperCAmelCase__ , UpperCAmelCase__ ) ) ) @unittest.skip("Esm does not support embedding resizing" ) def UpperCAmelCase_ ( self : List[Any] ) -> Union[str, Any]: pass @unittest.skip("Esm does not support embedding resizing" ) def UpperCAmelCase_ ( self : Optional[int] ) -> Any: pass @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def UpperCAmelCase_ ( self : Dict ) -> Tuple: pass @require_torch class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @slow def UpperCAmelCase_ ( self : Dict ) -> Dict: with torch.no_grad(): __SCREAMING_SNAKE_CASE = EsmForMaskedLM.from_pretrained("facebook/esm2_t6_8M_UR50D" ) model.eval() __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = 3_3 __SCREAMING_SNAKE_CASE = torch.Size((1, 6, vocab_size) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor( [[[8.9_215, -10.5_898, -6.4_671], [-6.3_967, -13.9_114, -1.1_212], [-7.7_812, -13.9_516, -3.7_406]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=1E-4 ) ) @slow def UpperCAmelCase_ ( self : Tuple ) -> Optional[Any]: with torch.no_grad(): __SCREAMING_SNAKE_CASE = EsmModel.from_pretrained("facebook/esm2_t6_8M_UR50D" ) model.eval() __SCREAMING_SNAKE_CASE = torch.tensor([[0, 6, 4, 1_3, 5, 4, 1_6, 1_2, 1_1, 7, 2]] ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ )[0] # compare the actual values for a slice. __SCREAMING_SNAKE_CASE = torch.tensor( [[[0.1_444, 0.5_413, 0.3_248], [0.3_034, 0.0_053, 0.3_108], [0.3_228, -0.2_499, 0.3_415]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=1E-4 ) )
54
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if upper_limit < 0: raise ValueError("Limit for the Catalan sequence must be ≥ 0" ) __SCREAMING_SNAKE_CASE = [0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 __SCREAMING_SNAKE_CASE = 1 if upper_limit > 0: __SCREAMING_SNAKE_CASE = 1 # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i for i in range(2 , upper_limit + 1 ): for j in range(lowerCAmelCase_ ): catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1] return catalan_list if __name__ == "__main__": print('''\n********* Catalan Numbers Using Dynamic Programming ************\n''') print('''\n*** Enter -1 at any time to quit ***''') print('''\nEnter the upper limit (≥ 0) for the Catalan number sequence: ''', end='''''') try: while True: a__ : List[str] = int(input().strip()) if N < 0: print('''\n********* Goodbye!! ************''') break else: print(F"The Catalan numbers from 0 through {N} are:") print(catalan_numbers(N)) print('''Try another upper limit for the sequence: ''', end='''''') except (NameError, ValueError): print('''\n********* Invalid input, goodbye! ************\n''') import doctest doctest.testmod()
54
1
"""simple docstring""" from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import TensorType, logging if TYPE_CHECKING: from ...onnx.config import PatchingSpec from ...tokenization_utils_base import PreTrainedTokenizerBase a__ : List[str] = logging.get_logger(__name__) a__ : Dict = { '''allenai/longformer-base-4096''': '''https://huggingface.co/allenai/longformer-base-4096/resolve/main/config.json''', '''allenai/longformer-large-4096''': '''https://huggingface.co/allenai/longformer-large-4096/resolve/main/config.json''', '''allenai/longformer-large-4096-finetuned-triviaqa''': ( '''https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/config.json''' ), '''allenai/longformer-base-4096-extra.pos.embd.only''': ( '''https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/config.json''' ), '''allenai/longformer-large-4096-extra.pos.embd.only''': ( '''https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/config.json''' ), } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : List[str] = "longformer" def __init__( self : Tuple , UpperCAmelCase__ : Union[List[int], int] = 5_1_2 , UpperCAmelCase__ : int = 2 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : int = 0 , UpperCAmelCase__ : int = 2 , UpperCAmelCase__ : int = 3_0_5_2_2 , UpperCAmelCase__ : int = 7_6_8 , UpperCAmelCase__ : int = 1_2 , UpperCAmelCase__ : int = 1_2 , UpperCAmelCase__ : int = 3_0_7_2 , UpperCAmelCase__ : str = "gelu" , UpperCAmelCase__ : float = 0.1 , UpperCAmelCase__ : float = 0.1 , UpperCAmelCase__ : int = 5_1_2 , UpperCAmelCase__ : int = 2 , UpperCAmelCase__ : float = 0.02 , UpperCAmelCase__ : float = 1E-12 , UpperCAmelCase__ : bool = False , **UpperCAmelCase__ : List[str] , ) -> Union[str, Any]: super().__init__(pad_token_id=UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = attention_window __SCREAMING_SNAKE_CASE = sep_token_id __SCREAMING_SNAKE_CASE = bos_token_id __SCREAMING_SNAKE_CASE = eos_token_id __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = onnx_export class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : List[str] , UpperCAmelCase__ : "PretrainedConfig" , UpperCAmelCase__ : str = "default" , UpperCAmelCase__ : "List[PatchingSpec]" = None ) -> str: super().__init__(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = True @property def UpperCAmelCase_ ( self : List[Any] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": __SCREAMING_SNAKE_CASE = {0: "batch", 1: "choice", 2: "sequence"} else: __SCREAMING_SNAKE_CASE = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ("global_attention_mask", dynamic_axis), ] ) @property def UpperCAmelCase_ ( self : Union[str, Any] ) -> Mapping[str, Mapping[int, str]]: __SCREAMING_SNAKE_CASE = super().outputs if self.task == "default": __SCREAMING_SNAKE_CASE = {0: "batch"} return outputs @property def UpperCAmelCase_ ( self : Dict ) -> float: return 1E-4 @property def UpperCAmelCase_ ( self : str ) -> int: # needs to be >= 14 to support tril operator return max(super().default_onnx_opset , 1_4 ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : "PreTrainedTokenizerBase" , UpperCAmelCase__ : int = -1 , UpperCAmelCase__ : int = -1 , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : Optional[TensorType] = None , ) -> Mapping[str, Any]: __SCREAMING_SNAKE_CASE = super().generate_dummy_inputs( preprocessor=UpperCAmelCase__ , batch_size=UpperCAmelCase__ , seq_length=UpperCAmelCase__ , is_pair=UpperCAmelCase__ , framework=UpperCAmelCase__ ) import torch # for some reason, replacing this code by inputs["global_attention_mask"] = torch.randint(2, inputs["input_ids"].shape, dtype=torch.int64) # makes the export fail randomly __SCREAMING_SNAKE_CASE = torch.zeros_like(inputs["input_ids"] ) # make every second token global __SCREAMING_SNAKE_CASE = 1 return inputs
54
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from itertools import chain from typing import Optional, Union import datasets import numpy as np import torch from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.tokenization_utils_base import PreTrainedTokenizerBase from transformers.trainer_utils import get_last_checkpoint from transformers.utils import PaddingStrategy, check_min_version, send_example_telemetry # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('''4.31.0''') a__ : Tuple = logging.getLogger(__name__) @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Pretrained config name or path if not the same as model_name"}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} , ) snake_case__ : str = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : Optional[str] = field(default=UpperCamelCase , metadata={"help": "The input training data file (a text file)."}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."} , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={"help": "Overwrite the cached training and evaluation sets"}) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={"help": "The number of processes to use for the preprocessing."} , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "The maximum total input sequence length after tokenization. If passed, sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={ "help": ( "Whether to pad all samples to the maximum sentence length. " "If False, will pad the samples dynamically when batching to the maximum length in the batch. More " "efficient on GPU but very bad for TPU." ) } , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: if self.train_file is not None: __SCREAMING_SNAKE_CASE = self.train_file.split("." )[-1] assert extension in ["csv", "json"], "`train_file` should be a csv or a json file." if self.validation_file is not None: __SCREAMING_SNAKE_CASE = self.validation_file.split("." )[-1] assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file." @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : PreTrainedTokenizerBase snake_case__ : Union[bool, str, PaddingStrategy] = True snake_case__ : Optional[int] = None snake_case__ : Optional[int] = None def __call__( self : int , UpperCAmelCase__ : Any ) -> str: __SCREAMING_SNAKE_CASE = "label" if "label" in features[0].keys() else "labels" __SCREAMING_SNAKE_CASE = [feature.pop(UpperCAmelCase__ ) for feature in features] __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = len(features[0]["input_ids"] ) __SCREAMING_SNAKE_CASE = [ [{k: v[i] for k, v in feature.items()} for i in range(UpperCAmelCase__ )] for feature in features ] __SCREAMING_SNAKE_CASE = list(chain(*UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = self.tokenizer.pad( UpperCAmelCase__ , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="pt" , ) # Un-flatten __SCREAMING_SNAKE_CASE = {k: v.view(UpperCAmelCase__ , UpperCAmelCase__ , -1 ) for k, v in batch.items()} # Add back labels __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ , dtype=torch.intaa ) return batch def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("run_swag" , lowerCAmelCase_ , lowerCAmelCase_ ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() __SCREAMING_SNAKE_CASE = training_args.get_process_log_level() logger.setLevel(lowerCAmelCase_ ) datasets.utils.logging.set_verbosity(lowerCAmelCase_ ) transformers.utils.logging.set_verbosity(lowerCAmelCase_ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + f"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(f"""Training/evaluation parameters {training_args}""" ) # Detecting last checkpoint. __SCREAMING_SNAKE_CASE = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: __SCREAMING_SNAKE_CASE = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. """ "Use --overwrite_output_dir to overcome." ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.train_file is not None or data_args.validation_file is not None: __SCREAMING_SNAKE_CASE = {} if data_args.train_file is not None: __SCREAMING_SNAKE_CASE = data_args.train_file if data_args.validation_file is not None: __SCREAMING_SNAKE_CASE = data_args.validation_file __SCREAMING_SNAKE_CASE = data_args.train_file.split("." )[-1] __SCREAMING_SNAKE_CASE = load_dataset( lowerCAmelCase_ , data_files=lowerCAmelCase_ , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) else: # Downloading and loading the swag dataset from the hub. __SCREAMING_SNAKE_CASE = load_dataset( "swag" , "regular" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) __SCREAMING_SNAKE_CASE = 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_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) __SCREAMING_SNAKE_CASE = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # When using your own dataset or a different dataset from swag, you will probably need to change this. __SCREAMING_SNAKE_CASE = [f"""ending{i}""" for i in range(4 )] __SCREAMING_SNAKE_CASE = "sent1" __SCREAMING_SNAKE_CASE = "sent2" if data_args.max_seq_length is None: __SCREAMING_SNAKE_CASE = tokenizer.model_max_length if max_seq_length > 1024: logger.warning( "The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value" " of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can" " override this default with `--block_size xxx`." ) __SCREAMING_SNAKE_CASE = 1024 else: if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( f"""The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the""" f"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.""" ) __SCREAMING_SNAKE_CASE = min(data_args.max_seq_length , tokenizer.model_max_length ) # Preprocessing the datasets. def preprocess_function(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = [[context] * 4 for context in examples[context_name]] __SCREAMING_SNAKE_CASE = examples[question_header_name] __SCREAMING_SNAKE_CASE = [ [f"""{header} {examples[end][i]}""" for end in ending_names] for i, header in enumerate(lowerCAmelCase_ ) ] # Flatten out __SCREAMING_SNAKE_CASE = list(chain(*lowerCAmelCase_ ) ) __SCREAMING_SNAKE_CASE = list(chain(*lowerCAmelCase_ ) ) # Tokenize __SCREAMING_SNAKE_CASE = tokenizer( lowerCAmelCase_ , lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=lowerCAmelCase_ , padding="max_length" if data_args.pad_to_max_length else False , ) # Un-flatten return {k: [v[i : i + 4] for i in range(0 , len(lowerCAmelCase_ ) , 4 )] for k, v in tokenized_examples.items()} if training_args.do_train: if "train" not in raw_datasets: raise ValueError("--do_train requires a train dataset" ) __SCREAMING_SNAKE_CASE = raw_datasets["train"] if data_args.max_train_samples is not None: __SCREAMING_SNAKE_CASE = min(len(lowerCAmelCase_ ) , data_args.max_train_samples ) __SCREAMING_SNAKE_CASE = train_dataset.select(range(lowerCAmelCase_ ) ) with training_args.main_process_first(desc="train dataset map pre-processing" ): __SCREAMING_SNAKE_CASE = train_dataset.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , ) if training_args.do_eval: if "validation" not in raw_datasets: raise ValueError("--do_eval requires a validation dataset" ) __SCREAMING_SNAKE_CASE = raw_datasets["validation"] if data_args.max_eval_samples is not None: __SCREAMING_SNAKE_CASE = min(len(lowerCAmelCase_ ) , data_args.max_eval_samples ) __SCREAMING_SNAKE_CASE = eval_dataset.select(range(lowerCAmelCase_ ) ) with training_args.main_process_first(desc="validation dataset map pre-processing" ): __SCREAMING_SNAKE_CASE = eval_dataset.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , ) # Data collator __SCREAMING_SNAKE_CASE = ( default_data_collator if data_args.pad_to_max_length else DataCollatorForMultipleChoice(tokenizer=lowerCAmelCase_ , pad_to_multiple_of=8 if training_args.fpaa else None ) ) # Metric def compute_metrics(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = eval_predictions __SCREAMING_SNAKE_CASE = np.argmax(lowerCAmelCase_ , axis=1 ) return {"accuracy": (preds == label_ids).astype(np.floataa ).mean().item()} # Initialize our Trainer __SCREAMING_SNAKE_CASE = Trainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , tokenizer=lowerCAmelCase_ , data_collator=lowerCAmelCase_ , compute_metrics=lowerCAmelCase_ , ) # Training if training_args.do_train: __SCREAMING_SNAKE_CASE = None if training_args.resume_from_checkpoint is not None: __SCREAMING_SNAKE_CASE = training_args.resume_from_checkpoint elif last_checkpoint is not None: __SCREAMING_SNAKE_CASE = last_checkpoint __SCREAMING_SNAKE_CASE = trainer.train(resume_from_checkpoint=lowerCAmelCase_ ) trainer.save_model() # Saves the tokenizer too for easy upload __SCREAMING_SNAKE_CASE = train_result.metrics __SCREAMING_SNAKE_CASE = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(lowerCAmelCase_ ) ) __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ , len(lowerCAmelCase_ ) ) trainer.log_metrics("train" , lowerCAmelCase_ ) trainer.save_metrics("train" , lowerCAmelCase_ ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("*** Evaluate ***" ) __SCREAMING_SNAKE_CASE = trainer.evaluate() __SCREAMING_SNAKE_CASE = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ , len(lowerCAmelCase_ ) ) trainer.log_metrics("eval" , lowerCAmelCase_ ) trainer.save_metrics("eval" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { "finetuned_from": model_args.model_name_or_path, "tasks": "multiple-choice", "dataset_tags": "swag", "dataset_args": "regular", "dataset": "SWAG", "language": "en", } if training_args.push_to_hub: trainer.push_to_hub(**lowerCAmelCase_ ) else: trainer.create_model_card(**lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' main() if __name__ == "__main__": main()
54
1
"""simple docstring""" import argparse import os from pathlib import Path import fairseq import torch from packaging import version from torch import nn from transformers import ( BartConfig, BartForConditionalGeneration, BartForSequenceClassification, BartModel, BartTokenizer, ) from transformers.utils import logging a__ : List[str] = ['''bart.large''', '''bart.large.mnli''', '''bart.large.cnn''', '''bart_xsum/model.pt'''] a__ : str = {'''bart.large''': BartModel, '''bart.large.mnli''': BartForSequenceClassification} if version.parse(fairseq.__version__) < version.parse('''0.9.0'''): raise Exception('''requires fairseq >= 0.9.0''') logging.set_verbosity_info() a__ : List[str] = logging.get_logger(__name__) a__ : Any = ''' Hello world! cécé herlolip''' a__ : Optional[Any] = [ ('''model.classification_heads.mnli.dense.weight''', '''classification_head.dense.weight'''), ('''model.classification_heads.mnli.dense.bias''', '''classification_head.dense.bias'''), ('''model.classification_heads.mnli.out_proj.weight''', '''classification_head.out_proj.weight'''), ('''model.classification_heads.mnli.out_proj.bias''', '''classification_head.out_proj.bias'''), ] def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [ "encoder.version", "decoder.version", "model.encoder.version", "model.decoder.version", "_float_tensor", ] for k in ignore_keys: state_dict.pop(lowerCAmelCase_ , lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = dct.pop(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = val def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = torch.load(lowerCAmelCase_ , map_location="cpu" ) __SCREAMING_SNAKE_CASE = torch.hub.load("pytorch/fairseq" , "bart.large.cnn" ).eval() hub_interface.model.load_state_dict(sd["model"] ) return hub_interface def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = emb.weight.shape __SCREAMING_SNAKE_CASE = nn.Linear(lowerCAmelCase_ , lowerCAmelCase_ , bias=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = emb.weight.data return lin_layer @torch.no_grad() def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=None ): '''simple docstring''' if not os.path.exists(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = torch.hub.load("pytorch/fairseq" , lowerCAmelCase_ ).eval() else: __SCREAMING_SNAKE_CASE = load_xsum_checkpoint(lowerCAmelCase_ ) bart.model.upgrade_state_dict(bart.model.state_dict() ) if hf_checkpoint_name is None: __SCREAMING_SNAKE_CASE = checkpoint_path.replace("." , "-" ) __SCREAMING_SNAKE_CASE = BartConfig.from_pretrained(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = bart.encode(lowerCAmelCase_ ).unsqueeze(0 ) __SCREAMING_SNAKE_CASE = BartTokenizer.from_pretrained(lowerCAmelCase_ ).encode(lowerCAmelCase_ , return_tensors="pt" ).unsqueeze(0 ) if not torch.eq(lowerCAmelCase_ , lowerCAmelCase_ ).all(): raise ValueError( f"""converted tokenizer and pretrained tokenizer returned different output: {tokens} != {tokensa}""" ) if checkpoint_path == "bart.large.mnli": __SCREAMING_SNAKE_CASE = bart.state_dict() remove_ignore_keys_(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = state_dict["model.decoder.embed_tokens.weight"] for src, dest in mnli_rename_keys: rename_key(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = BartForSequenceClassification(lowerCAmelCase_ ).eval() model.load_state_dict(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = bart.predict("mnli" , lowerCAmelCase_ , return_logits=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = model(lowerCAmelCase_ )[0] # logits else: # no classification heads to worry about __SCREAMING_SNAKE_CASE = bart.model.state_dict() remove_ignore_keys_(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = state_dict["decoder.embed_tokens.weight"] __SCREAMING_SNAKE_CASE = bart.extract_features(lowerCAmelCase_ ) if hf_checkpoint_name == "facebook/bart-large": __SCREAMING_SNAKE_CASE = BartModel(lowerCAmelCase_ ).eval() model.load_state_dict(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = model(lowerCAmelCase_ ).model[0] else: __SCREAMING_SNAKE_CASE = BartForConditionalGeneration(lowerCAmelCase_ ).eval() # an existing summarization ckpt model.model.load_state_dict(lowerCAmelCase_ ) if hasattr(lowerCAmelCase_ , "lm_head" ): __SCREAMING_SNAKE_CASE = make_linear_from_emb(model.model.shared ) __SCREAMING_SNAKE_CASE = model.model(lowerCAmelCase_ )[0] # Check results if fairseq_output.shape != new_model_outputs.shape: raise ValueError( f"""`fairseq_output` shape and `new_model_output` shape are different: {fairseq_output.shape=}, {new_model_outputs.shape}""" ) if (fairseq_output != new_model_outputs).any().item(): raise ValueError("Some values in `fairseq_output` are different from `new_model_outputs`" ) Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": a__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( '''fairseq_path''', type=str, help='''bart.large, bart.large.cnn or a path to a model.pt on local filesystem.''' ) parser.add_argument('''pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument( '''--hf_config''', default=None, type=str, help='''Which huggingface architecture to use: bart-large-xsum''' ) a__ : Tuple = parser.parse_args() convert_bart_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, hf_checkpoint_name=args.hf_config)
54
"""simple docstring""" from PIL import Image def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = image.size __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = image.load() for i in range(lowerCAmelCase_ ): for j in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = pixels[j, i] mean += pixel mean //= width * height for j in range(lowerCAmelCase_ ): for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = 255 if pixels[i, j] > mean else 0 return image if __name__ == "__main__": a__ : List[str] = mean_threshold(Image.open('''path_to_image''').convert('''L''')) image.save('''output_image_path''')
54
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) a__ : int = {'''configuration_unispeech''': ['''UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''UniSpeechConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : str = [ '''UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST''', '''UniSpeechForCTC''', '''UniSpeechForPreTraining''', '''UniSpeechForSequenceClassification''', '''UniSpeechModel''', '''UniSpeechPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys a__ : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
54
"""simple docstring""" from jiwer import compute_measures import datasets a__ : Optional[int] = '''\ @inproceedings{inproceedings, author = {Morris, Andrew and Maier, Viktoria and Green, Phil}, year = {2004}, month = {01}, pages = {}, title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.} } ''' a__ : List[str] = '''\ Word error rate (WER) is a common metric of the performance of an automatic speech recognition system. The general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort. This problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate. Word error rate can then be computed as: WER = (S + D + I) / N = (S + D + I) / (S + D + C) where S is the number of substitutions, D is the number of deletions, I is the number of insertions, C is the number of correct words, N is the number of words in the reference (N=S+D+C). This value indicates the average number of errors per reference word. The lower the value, the better the performance of the ASR system with a WER of 0 being a perfect score. ''' a__ : Dict = ''' Compute WER score of transcribed segments against references. Args: references: List of references for each speech input. predictions: List of transcriptions to score. concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively. Returns: (float): the word error rate Examples: >>> predictions = ["this is the prediction", "there is an other sample"] >>> references = ["this is the reference", "there is another one"] >>> wer = datasets.load_metric("wer") >>> wer_score = wer.compute(predictions=predictions, references=references) >>> print(wer_score) 0.5 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class UpperCamelCase_ ( datasets.Metric): """simple docstring""" def UpperCAmelCase_ ( self : List[Any] ) -> str: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , codebase_urls=["https://github.com/jitsi/jiwer/"] , reference_urls=[ "https://en.wikipedia.org/wiki/Word_error_rate", ] , ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : Any=False ) -> Optional[int]: if concatenate_texts: return compute_measures(UpperCAmelCase__ , UpperCAmelCase__ )["wer"] else: __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for prediction, reference in zip(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = compute_measures(UpperCAmelCase__ , UpperCAmelCase__ ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
54
1
"""simple docstring""" from __future__ import annotations a__ : Any = [ [-1, 0], # left [0, -1], # down [1, 0], # right [0, 1], # up ] def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [ [0 for col in range(len(grid[0] ) )] for row in range(len(lowerCAmelCase_ ) ) ] # the reference grid __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = [ [0 for col in range(len(grid[0] ) )] for row in range(len(lowerCAmelCase_ ) ) ] # the action grid __SCREAMING_SNAKE_CASE = init[0] __SCREAMING_SNAKE_CASE = init[1] __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = g + heuristic[x][y] # cost from starting cell to destination cell __SCREAMING_SNAKE_CASE = [[f, g, x, y]] __SCREAMING_SNAKE_CASE = False # flag that is set when search is complete __SCREAMING_SNAKE_CASE = False # flag set if we can't find expand while not found and not resign: if len(lowerCAmelCase_ ) == 0: raise ValueError("Algorithm is unable to find solution" ) else: # to choose the least costliest action so as to move closer to the goal cell.sort() cell.reverse() __SCREAMING_SNAKE_CASE = cell.pop() __SCREAMING_SNAKE_CASE = next_cell[2] __SCREAMING_SNAKE_CASE = next_cell[3] __SCREAMING_SNAKE_CASE = next_cell[1] if x == goal[0] and y == goal[1]: __SCREAMING_SNAKE_CASE = True else: for i in range(len(lowerCAmelCase_ ) ): # to try out different valid actions __SCREAMING_SNAKE_CASE = x + DIRECTIONS[i][0] __SCREAMING_SNAKE_CASE = y + DIRECTIONS[i][1] if xa >= 0 and xa < len(lowerCAmelCase_ ) and ya >= 0 and ya < len(grid[0] ): if closed[xa][ya] == 0 and grid[xa][ya] == 0: __SCREAMING_SNAKE_CASE = g + cost __SCREAMING_SNAKE_CASE = ga + heuristic[xa][ya] cell.append([fa, ga, xa, ya] ) __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = goal[0] __SCREAMING_SNAKE_CASE = goal[1] invpath.append([x, y] ) # we get the reverse path from here while x != init[0] or y != init[1]: __SCREAMING_SNAKE_CASE = x - DIRECTIONS[action[x][y]][0] __SCREAMING_SNAKE_CASE = y - DIRECTIONS[action[x][y]][1] __SCREAMING_SNAKE_CASE = xa __SCREAMING_SNAKE_CASE = ya invpath.append([x, y] ) __SCREAMING_SNAKE_CASE = [] for i in range(len(lowerCAmelCase_ ) ): path.append(invpath[len(lowerCAmelCase_ ) - 1 - i] ) return path, action if __name__ == "__main__": a__ : Tuple = [ [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0], ] a__ : List[str] = [0, 0] # all coordinates are given in format [y,x] a__ : str = [len(grid) - 1, len(grid[0]) - 1] a__ : int = 1 # the cost map which pushes the path closer to the goal a__ : Optional[int] = [[0 for row in range(len(grid[0]))] for col in range(len(grid))] for i in range(len(grid)): for j in range(len(grid[0])): a__ : Tuple = abs(i - goal[0]) + abs(j - goal[1]) if grid[i][j] == 1: # added extra penalty in the heuristic map a__ : List[Any] = 9_9 a__ , a__ : List[Any] = search(grid, init, goal, cost, heuristic) print('''ACTION MAP''') for i in range(len(action)): print(action[i]) for i in range(len(path)): print(path[i])
54
"""simple docstring""" from __future__ import annotations import pandas as pd def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [0] * no_of_processes __SCREAMING_SNAKE_CASE = [0] * no_of_processes # Copy the burst time into remaining_time[] for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = burst_time[i] __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 9_9999_9999 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = False # Process until all processes are completed while complete != no_of_processes: for j in range(lowerCAmelCase_ ): if arrival_time[j] <= increment_time and remaining_time[j] > 0: if remaining_time[j] < minm: __SCREAMING_SNAKE_CASE = remaining_time[j] __SCREAMING_SNAKE_CASE = j __SCREAMING_SNAKE_CASE = True if not check: increment_time += 1 continue remaining_time[short] -= 1 __SCREAMING_SNAKE_CASE = remaining_time[short] if minm == 0: __SCREAMING_SNAKE_CASE = 9_9999_9999 if remaining_time[short] == 0: complete += 1 __SCREAMING_SNAKE_CASE = False # Find finish time of current process __SCREAMING_SNAKE_CASE = increment_time + 1 # Calculate waiting time __SCREAMING_SNAKE_CASE = finish_time - arrival_time[short] __SCREAMING_SNAKE_CASE = finar - burst_time[short] if waiting_time[short] < 0: __SCREAMING_SNAKE_CASE = 0 # Increment time increment_time += 1 return waiting_time def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [0] * no_of_processes for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = burst_time[i] + waiting_time[i] return turn_around_time def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = total_waiting_time + waiting_time[i] __SCREAMING_SNAKE_CASE = total_turn_around_time + turn_around_time[i] print(f"""Average waiting time = {total_waiting_time / no_of_processes:.5f}""" ) print("Average turn around time =" , total_turn_around_time / no_of_processes ) if __name__ == "__main__": print('''Enter how many process you want to analyze''') a__ : Optional[Any] = int(input()) a__ : Optional[int] = [0] * no_of_processes a__ : int = [0] * no_of_processes a__ : List[Any] = list(range(1, no_of_processes + 1)) for i in range(no_of_processes): print('''Enter the arrival time and burst time for process:--''' + str(i + 1)) a__ , a__ : Tuple = map(int, input().split()) a__ : int = calculate_waitingtime(arrival_time, burst_time, no_of_processes) a__ : Dict = burst_time a__ : Any = no_of_processes a__ : Optional[int] = waiting_time a__ : Union[str, Any] = calculate_turnaroundtime(bt, n, wt) calculate_average_times(waiting_time, turn_around_time, no_of_processes) a__ : str = pd.DataFrame( list(zip(processes, burst_time, arrival_time, waiting_time, turn_around_time)), columns=[ '''Process''', '''BurstTime''', '''ArrivalTime''', '''WaitingTime''', '''TurnAroundTime''', ], ) # Printing the dataFrame pd.set_option('''display.max_rows''', fcfs.shape[0] + 1) print(fcfs)
54
1
"""simple docstring""" from ..utils import DummyObject, requires_backends class UpperCamelCase_ ( metaclass=UpperCamelCase): """simple docstring""" snake_case__ : Optional[int] = ["torch", "scipy"] def __init__( self : Tuple , *UpperCAmelCase__ : List[str] , **UpperCAmelCase__ : Optional[int] ) -> Optional[int]: requires_backends(self , ["torch", "scipy"] ) @classmethod def UpperCAmelCase_ ( cls : Any , *UpperCAmelCase__ : Tuple , **UpperCAmelCase__ : Dict ) -> Optional[int]: requires_backends(cls , ["torch", "scipy"] ) @classmethod def UpperCAmelCase_ ( cls : List[Any] , *UpperCAmelCase__ : str , **UpperCAmelCase__ : Union[str, Any] ) -> List[str]: requires_backends(cls , ["torch", "scipy"] )
54
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy a__ : Union[str, Any] = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : float , **UpperCAmelCase__ : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = feature_size __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = padding_value __SCREAMING_SNAKE_CASE = kwargs.pop("padding_side" , "right" ) __SCREAMING_SNAKE_CASE = kwargs.pop("return_attention_mask" , UpperCAmelCase__ ) super().__init__(**UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[ BatchFeature, List[BatchFeature], Dict[str, BatchFeature], Dict[str, List[BatchFeature]], List[Dict[str, BatchFeature]], ] , UpperCAmelCase__ : Union[bool, str, PaddingStrategy] = True , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[Union[str, TensorType]] = None , ) -> BatchFeature: # If we have a list of dicts, let's convert it in a dict of lists # We do this to allow using this method as a collate_fn function in PyTorch Dataloader if isinstance(UpperCAmelCase__ , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): __SCREAMING_SNAKE_CASE = { key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( "You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`" F""" to this method that includes {self.model_input_names[0]}, but you provided""" F""" {list(processed_features.keys() )}""" ) __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] __SCREAMING_SNAKE_CASE = ( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(UpperCAmelCase__ ) == 0: if return_attention_mask: __SCREAMING_SNAKE_CASE = [] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch __SCREAMING_SNAKE_CASE = required_input[0] if isinstance(UpperCAmelCase__ , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. __SCREAMING_SNAKE_CASE = 0 while len(required_input[index] ) == 0: index += 1 if index < len(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = required_input[index][0] if return_tensors is None: if is_tf_tensor(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = "tf" elif is_torch_tensor(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = "pt" elif isinstance(UpperCAmelCase__ , (int, float, list, tuple, np.ndarray) ): __SCREAMING_SNAKE_CASE = "np" else: raise ValueError( F"""type of {first_element} unknown: {type(UpperCAmelCase__ )}. """ "Should be one of a python, numpy, pytorch or tensorflow object." ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): __SCREAMING_SNAKE_CASE = to_numpy(UpperCAmelCase__ ) else: __SCREAMING_SNAKE_CASE = [to_numpy(UpperCAmelCase__ ) for v in value] # Convert padding_strategy in PaddingStrategy __SCREAMING_SNAKE_CASE = self._get_padding_strategies(padding=UpperCAmelCase__ , max_length=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) if not all(len(UpperCAmelCase__ ) == batch_size for v in processed_features.values() ): raise ValueError("Some items in the output dictionary have a different batch size than others." ) __SCREAMING_SNAKE_CASE = [] for i in range(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = {k: v[i] for k, v in processed_features.items()} # truncation __SCREAMING_SNAKE_CASE = self._truncate( UpperCAmelCase__ , max_length=UpperCAmelCase__ , pad_to_multiple_of=UpperCAmelCase__ , truncation=UpperCAmelCase__ , ) truncated_inputs.append(UpperCAmelCase__ ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length __SCREAMING_SNAKE_CASE = max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) __SCREAMING_SNAKE_CASE = PaddingStrategy.MAX_LENGTH __SCREAMING_SNAKE_CASE = {} for i in range(UpperCAmelCase__ ): # padding __SCREAMING_SNAKE_CASE = self._pad( truncated_inputs[i] , max_length=UpperCAmelCase__ , padding_strategy=UpperCAmelCase__ , pad_to_multiple_of=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , ) for key, value in outputs.items(): if key not in batch_outputs: __SCREAMING_SNAKE_CASE = [] if value.dtype is np.dtype(np.floataa ): __SCREAMING_SNAKE_CASE = value.astype(np.floataa ) batch_outputs[key].append(UpperCAmelCase__ ) return BatchFeature(UpperCAmelCase__ , tensor_type=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[Dict[str, np.ndarray], BatchFeature] , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , ) -> dict: __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __SCREAMING_SNAKE_CASE = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __SCREAMING_SNAKE_CASE = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(UpperCAmelCase__ ) < max_length if return_attention_mask and "attention_mask" not in processed_features: __SCREAMING_SNAKE_CASE = np.ones(len(UpperCAmelCase__ ) , dtype=np.intaa ) if needs_to_be_padded: __SCREAMING_SNAKE_CASE = max_length - len(UpperCAmelCase__ ) if self.padding_side == "right": if return_attention_mask: __SCREAMING_SNAKE_CASE = np.pad( processed_features["attention_mask"] , (0, difference) ) __SCREAMING_SNAKE_CASE = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) __SCREAMING_SNAKE_CASE = np.pad( UpperCAmelCase__ , UpperCAmelCase__ , "constant" , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: __SCREAMING_SNAKE_CASE = np.pad( processed_features["attention_mask"] , (difference, 0) ) __SCREAMING_SNAKE_CASE = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) __SCREAMING_SNAKE_CASE = np.pad( UpperCAmelCase__ , UpperCAmelCase__ , "constant" , constant_values=self.padding_value ) else: raise ValueError("Invalid padding strategy:" + str(self.padding_side ) ) return processed_features def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Union[Dict[str, np.ndarray], BatchFeature] , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , ) -> str: if not truncation: return processed_features elif truncation and max_length is None: raise ValueError("When setting ``truncation=True``, make sure that ``max_length`` is defined." ) __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __SCREAMING_SNAKE_CASE = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) > max_length if needs_to_be_truncated: __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: __SCREAMING_SNAKE_CASE = processed_features["attention_mask"][:max_length] return processed_features def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Optional[Any]=False , UpperCAmelCase__ : Optional[int]=None ) -> str: # Get padding strategy if padding is not False: if padding is True: __SCREAMING_SNAKE_CASE = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = PaddingStrategy(UpperCAmelCase__ ) elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = padding else: __SCREAMING_SNAKE_CASE = PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( F"""When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined""" ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( "Asking to pad but the feature_extractor does not have a padding value. Please select a value to use" " as `padding_value`. For example: `feature_extractor.padding_value = 0.0`." ) return padding_strategy
54
1
"""simple docstring""" # Lint as: python3 # pylint: enable=line-too-long # pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position a__ : Dict = '''2.13.1''' import platform import pyarrow from packaging import version if version.parse(platform.python_version()) < version.parse('''3.7'''): raise ImportWarning( '''To use `datasets`, Python>=3.7 is required, and the current version of Python doesn\'t match this condition.''' ) if version.parse(pyarrow.__version__).major < 8: raise ImportWarning( '''To use `datasets`, the module `pyarrow>=8.0.0` is required, and the current version of `pyarrow` doesn\'t match this condition.\n''' '''If you are running this in a Google Colab, you should probably just restart the runtime to use the right version of `pyarrow`.''' ) del platform del pyarrow del version from .arrow_dataset import Dataset from .arrow_reader import ReadInstruction from .builder import ArrowBasedBuilder, BeamBasedBuilder, BuilderConfig, DatasetBuilder, GeneratorBasedBuilder from .combine import concatenate_datasets, interleave_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .download import * from .features import * from .fingerprint import disable_caching, enable_caching, is_caching_enabled, set_caching_enabled from .info import DatasetInfo, MetricInfo from .inspect import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, list_datasets, list_metrics, ) from .iterable_dataset import IterableDataset from .load import load_dataset, load_dataset_builder, load_from_disk, load_metric from .metric import Metric from .splits import ( NamedSplit, NamedSplitAll, Split, SplitBase, SplitDict, SplitGenerator, SplitInfo, SubSplitInfo, percent, ) from .tasks import * from .utils import * from .utils import logging # deprecated modules from datasets import arrow_dataset as _arrow_dataset # isort:skip from datasets import utils as _utils # isort:skip from datasets.utils import download_manager as _deprecated_download_manager # isort:skip a__ : List[Any] = concatenate_datasets a__ : List[str] = DownloadConfig a__ : Optional[Any] = DownloadManager a__ : Dict = DownloadMode a__ : List[str] = DownloadConfig a__ : List[str] = DownloadMode a__ : Tuple = DownloadManager del _arrow_dataset, _utils, _deprecated_download_manager
54
"""simple docstring""" import warnings from ...utils import is_sklearn_available, requires_backends if is_sklearn_available(): from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef a__ : Any = ( '''This metric will be removed from the library soon, metrics should be handled with the 🤗 Evaluate ''' '''library. You can have a look at this example script for pointers: ''' '''https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py''' ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) return (preds == labels).mean() def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) __SCREAMING_SNAKE_CASE = simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = fa_score(y_true=lowerCAmelCase_ , y_pred=lowerCAmelCase_ ) return { "acc": acc, "f1": fa, "acc_and_f1": (acc + fa) / 2, } def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) __SCREAMING_SNAKE_CASE = pearsonr(lowerCAmelCase_ , lowerCAmelCase_ )[0] __SCREAMING_SNAKE_CASE = spearmanr(lowerCAmelCase_ , lowerCAmelCase_ )[0] return { "pearson": pearson_corr, "spearmanr": spearman_corr, "corr": (pearson_corr + spearman_corr) / 2, } def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) assert len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ), f"""Predictions and labels have mismatched lengths {len(lowerCAmelCase_ )} and {len(lowerCAmelCase_ )}""" if task_name == "cola": return {"mcc": matthews_corrcoef(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "sst-2": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "mrpc": return acc_and_fa(lowerCAmelCase_ , lowerCAmelCase_ ) elif task_name == "sts-b": return pearson_and_spearman(lowerCAmelCase_ , lowerCAmelCase_ ) elif task_name == "qqp": return acc_and_fa(lowerCAmelCase_ , lowerCAmelCase_ ) elif task_name == "mnli": return {"mnli/acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "mnli-mm": return {"mnli-mm/acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "qnli": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "rte": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "wnli": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "hans": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} else: raise KeyError(lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) if len(lowerCAmelCase_ ) != len(lowerCAmelCase_ ): raise ValueError(f"""Predictions and labels have mismatched lengths {len(lowerCAmelCase_ )} and {len(lowerCAmelCase_ )}""" ) if task_name == "xnli": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} else: raise KeyError(lowerCAmelCase_ )
54
1
"""simple docstring""" import argparse import json import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinConfig, SwinForImageClassification def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = SwinConfig() __SCREAMING_SNAKE_CASE = swin_name.split("_" ) __SCREAMING_SNAKE_CASE = name_split[1] __SCREAMING_SNAKE_CASE = int(name_split[4] ) __SCREAMING_SNAKE_CASE = int(name_split[3][-1] ) if model_size == "tiny": __SCREAMING_SNAKE_CASE = 96 __SCREAMING_SNAKE_CASE = (2, 2, 6, 2) __SCREAMING_SNAKE_CASE = (3, 6, 12, 24) elif model_size == "small": __SCREAMING_SNAKE_CASE = 96 __SCREAMING_SNAKE_CASE = (2, 2, 18, 2) __SCREAMING_SNAKE_CASE = (3, 6, 12, 24) elif model_size == "base": __SCREAMING_SNAKE_CASE = 128 __SCREAMING_SNAKE_CASE = (2, 2, 18, 2) __SCREAMING_SNAKE_CASE = (4, 8, 16, 32) else: __SCREAMING_SNAKE_CASE = 192 __SCREAMING_SNAKE_CASE = (2, 2, 18, 2) __SCREAMING_SNAKE_CASE = (6, 12, 24, 48) if "in22k" in swin_name: __SCREAMING_SNAKE_CASE = 2_1841 else: __SCREAMING_SNAKE_CASE = 1000 __SCREAMING_SNAKE_CASE = "huggingface/label-files" __SCREAMING_SNAKE_CASE = "imagenet-1k-id2label.json" __SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(lowerCAmelCase_ , lowerCAmelCase_ , repo_type="dataset" ) , "r" ) ) __SCREAMING_SNAKE_CASE = {int(lowerCAmelCase_ ): v for k, v in idalabel.items()} __SCREAMING_SNAKE_CASE = idalabel __SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} __SCREAMING_SNAKE_CASE = img_size __SCREAMING_SNAKE_CASE = num_classes __SCREAMING_SNAKE_CASE = embed_dim __SCREAMING_SNAKE_CASE = depths __SCREAMING_SNAKE_CASE = num_heads __SCREAMING_SNAKE_CASE = window_size return config def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if "patch_embed.proj" in name: __SCREAMING_SNAKE_CASE = name.replace("patch_embed.proj" , "embeddings.patch_embeddings.projection" ) if "patch_embed.norm" in name: __SCREAMING_SNAKE_CASE = name.replace("patch_embed.norm" , "embeddings.norm" ) if "layers" in name: __SCREAMING_SNAKE_CASE = "encoder." + name if "attn.proj" in name: __SCREAMING_SNAKE_CASE = name.replace("attn.proj" , "attention.output.dense" ) if "attn" in name: __SCREAMING_SNAKE_CASE = name.replace("attn" , "attention.self" ) if "norm1" in name: __SCREAMING_SNAKE_CASE = name.replace("norm1" , "layernorm_before" ) if "norm2" in name: __SCREAMING_SNAKE_CASE = name.replace("norm2" , "layernorm_after" ) if "mlp.fc1" in name: __SCREAMING_SNAKE_CASE = name.replace("mlp.fc1" , "intermediate.dense" ) if "mlp.fc2" in name: __SCREAMING_SNAKE_CASE = name.replace("mlp.fc2" , "output.dense" ) if name == "norm.weight": __SCREAMING_SNAKE_CASE = "layernorm.weight" if name == "norm.bias": __SCREAMING_SNAKE_CASE = "layernorm.bias" if "head" in name: __SCREAMING_SNAKE_CASE = name.replace("head" , "classifier" ) else: __SCREAMING_SNAKE_CASE = "swin." + name return name def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' for key in orig_state_dict.copy().keys(): __SCREAMING_SNAKE_CASE = orig_state_dict.pop(lowerCAmelCase_ ) if "mask" in key: continue elif "qkv" in key: __SCREAMING_SNAKE_CASE = key.split("." ) __SCREAMING_SNAKE_CASE = int(key_split[1] ) __SCREAMING_SNAKE_CASE = int(key_split[3] ) __SCREAMING_SNAKE_CASE = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: __SCREAMING_SNAKE_CASE = val[:dim, :] __SCREAMING_SNAKE_CASE = val[ dim : dim * 2, : ] __SCREAMING_SNAKE_CASE = val[-dim:, :] else: __SCREAMING_SNAKE_CASE = val[ :dim ] __SCREAMING_SNAKE_CASE = val[ dim : dim * 2 ] __SCREAMING_SNAKE_CASE = val[ -dim: ] else: __SCREAMING_SNAKE_CASE = val return orig_state_dict def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = timm.create_model(lowerCAmelCase_ , pretrained=lowerCAmelCase_ ) timm_model.eval() __SCREAMING_SNAKE_CASE = get_swin_config(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = SwinForImageClassification(lowerCAmelCase_ ) model.eval() __SCREAMING_SNAKE_CASE = convert_state_dict(timm_model.state_dict() , lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = "http://images.cocodataset.org/val2017/000000039769.jpg" __SCREAMING_SNAKE_CASE = AutoImageProcessor.from_pretrained("microsoft/{}".format(swin_name.replace("_" , "-" ) ) ) __SCREAMING_SNAKE_CASE = Image.open(requests.get(lowerCAmelCase_ , stream=lowerCAmelCase_ ).raw ) __SCREAMING_SNAKE_CASE = image_processor(images=lowerCAmelCase_ , return_tensors="pt" ) __SCREAMING_SNAKE_CASE = timm_model(inputs["pixel_values"] ) __SCREAMING_SNAKE_CASE = model(**lowerCAmelCase_ ).logits assert torch.allclose(lowerCAmelCase_ , lowerCAmelCase_ , atol=1E-3 ) print(f"""Saving model {swin_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(lowerCAmelCase_ ) print(f"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": a__ : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--swin_name''', default='''swin_tiny_patch4_window7_224''', type=str, help='''Name of the Swin timm model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) a__ : Union[str, Any] = parser.parse_args() convert_swin_checkpoint(args.swin_name, args.pytorch_dump_folder_path)
54
"""simple docstring""" import math import random def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = False ): '''simple docstring''' if deriv: return value * (1 - value) return 1 / (1 + math.exp(-value )) # Initial Value a__ : Tuple = 0.02 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = float(2 * (random.randint(1 , 100 )) - 1 ) for _ in range(lowerCAmelCase_ ): # Forward propagation __SCREAMING_SNAKE_CASE = sigmoid_function(INITIAL_VALUE * weight ) # How much did we miss? __SCREAMING_SNAKE_CASE = (expected / 100) - layer_a # Error delta __SCREAMING_SNAKE_CASE = layer_1_error * sigmoid_function(lowerCAmelCase_ , lowerCAmelCase_ ) # Update weight weight += INITIAL_VALUE * layer_1_delta return layer_a * 100 if __name__ == "__main__": import doctest doctest.testmod() a__ : List[str] = int(input('''Expected value: ''')) a__ : str = int(input('''Number of propagations: ''')) print(forward_propagation(expected, number_propagations))
54
1
"""simple docstring""" from typing import Callable, List, Optional, Tuple, Union import torch from transformers import CLIPTextModel, CLIPTokenizer from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin, TransformeraDModel, VQModel from ...schedulers import VQDiffusionScheduler from ...utils import logging from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput a__ : Any = logging.get_logger(__name__) # pylint: disable=invalid-name class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase): """simple docstring""" @register_to_config def __init__( self : Tuple , UpperCAmelCase__ : bool , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[int] = None ) -> Tuple: super().__init__() __SCREAMING_SNAKE_CASE = learnable if self.learnable: assert hidden_size is not None, "learnable=True requires `hidden_size` to be set" assert length is not None, "learnable=True requires `length` to be set" __SCREAMING_SNAKE_CASE = torch.zeros(UpperCAmelCase__ , UpperCAmelCase__ ) else: __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = torch.nn.Parameter(UpperCAmelCase__ ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : VQModel snake_case__ : CLIPTextModel snake_case__ : CLIPTokenizer snake_case__ : TransformeraDModel snake_case__ : LearnedClassifierFreeSamplingEmbeddings snake_case__ : VQDiffusionScheduler def __init__( self : Union[str, Any] , UpperCAmelCase__ : VQModel , UpperCAmelCase__ : CLIPTextModel , UpperCAmelCase__ : CLIPTokenizer , UpperCAmelCase__ : TransformeraDModel , UpperCAmelCase__ : VQDiffusionScheduler , UpperCAmelCase__ : LearnedClassifierFreeSamplingEmbeddings , ) -> int: super().__init__() self.register_modules( vqvae=UpperCAmelCase__ , transformer=UpperCAmelCase__ , text_encoder=UpperCAmelCase__ , tokenizer=UpperCAmelCase__ , scheduler=UpperCAmelCase__ , learned_classifier_free_sampling_embeddings=UpperCAmelCase__ , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : Any ) -> int: __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else 1 # get prompt text embeddings __SCREAMING_SNAKE_CASE = self.tokenizer( UpperCAmelCase__ , padding="max_length" , max_length=self.tokenizer.model_max_length , return_tensors="pt" , ) __SCREAMING_SNAKE_CASE = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: __SCREAMING_SNAKE_CASE = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( "The following part of your input was truncated because CLIP can only handle sequences up to" F""" {self.tokenizer.model_max_length} tokens: {removed_text}""" ) __SCREAMING_SNAKE_CASE = text_input_ids[:, : self.tokenizer.model_max_length] __SCREAMING_SNAKE_CASE = self.text_encoder(text_input_ids.to(self.device ) )[0] # NOTE: This additional step of normalizing the text embeddings is from VQ-Diffusion. # While CLIP does normalize the pooled output of the text transformer when combining # the image and text embeddings, CLIP does not directly normalize the last hidden state. # # CLIP normalizing the pooled output. # https://github.com/huggingface/transformers/blob/d92e22d1f28324f513f3080e5c47c071a3916721/src/transformers/models/clip/modeling_clip.py#L1052-L1053 __SCREAMING_SNAKE_CASE = prompt_embeds / prompt_embeds.norm(dim=-1 , keepdim=UpperCAmelCase__ ) # duplicate text embeddings for each generation per prompt __SCREAMING_SNAKE_CASE = prompt_embeds.repeat_interleave(UpperCAmelCase__ , dim=0 ) if do_classifier_free_guidance: if self.learned_classifier_free_sampling_embeddings.learnable: __SCREAMING_SNAKE_CASE = self.learned_classifier_free_sampling_embeddings.embeddings __SCREAMING_SNAKE_CASE = negative_prompt_embeds.unsqueeze(0 ).repeat(UpperCAmelCase__ , 1 , 1 ) else: __SCREAMING_SNAKE_CASE = [""] * batch_size __SCREAMING_SNAKE_CASE = text_input_ids.shape[-1] __SCREAMING_SNAKE_CASE = self.tokenizer( UpperCAmelCase__ , padding="max_length" , max_length=UpperCAmelCase__ , truncation=UpperCAmelCase__ , return_tensors="pt" , ) __SCREAMING_SNAKE_CASE = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # See comment for normalizing text embeddings __SCREAMING_SNAKE_CASE = negative_prompt_embeds / negative_prompt_embeds.norm(dim=-1 , keepdim=UpperCAmelCase__ ) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method __SCREAMING_SNAKE_CASE = negative_prompt_embeds.shape[1] __SCREAMING_SNAKE_CASE = negative_prompt_embeds.repeat(1 , UpperCAmelCase__ , 1 ) __SCREAMING_SNAKE_CASE = negative_prompt_embeds.view(batch_size * num_images_per_prompt , UpperCAmelCase__ , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes __SCREAMING_SNAKE_CASE = torch.cat([negative_prompt_embeds, prompt_embeds] ) return prompt_embeds @torch.no_grad() def __call__( self : Tuple , UpperCAmelCase__ : Union[str, List[str]] , UpperCAmelCase__ : int = 1_0_0 , UpperCAmelCase__ : float = 5.0 , UpperCAmelCase__ : float = 1.0 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase__ : Optional[torch.FloatTensor] = None , UpperCAmelCase__ : Optional[str] = "pil" , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , UpperCAmelCase__ : int = 1 , ) -> Union[ImagePipelineOutput, Tuple]: if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = 1 elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) else: raise ValueError(F"""`prompt` has to be of type `str` or `list` but is {type(UpperCAmelCase__ )}""" ) __SCREAMING_SNAKE_CASE = batch_size * num_images_per_prompt __SCREAMING_SNAKE_CASE = guidance_scale > 1.0 __SCREAMING_SNAKE_CASE = self._encode_prompt(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) or callback_steps <= 0) ): raise ValueError( F"""`callback_steps` has to be a positive integer but is {callback_steps} of type""" F""" {type(UpperCAmelCase__ )}.""" ) # get the initial completely masked latents unless the user supplied it __SCREAMING_SNAKE_CASE = (batch_size, self.transformer.num_latent_pixels) if latents is None: __SCREAMING_SNAKE_CASE = self.transformer.num_vector_embeds - 1 __SCREAMING_SNAKE_CASE = torch.full(UpperCAmelCase__ , UpperCAmelCase__ ).to(self.device ) else: if latents.shape != latents_shape: raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}""" ) if (latents < 0).any() or (latents >= self.transformer.num_vector_embeds).any(): raise ValueError( "Unexpected latents value(s). All latents be valid embedding indices i.e. in the range 0," F""" {self.transformer.num_vector_embeds - 1} (inclusive).""" ) __SCREAMING_SNAKE_CASE = latents.to(self.device ) # set timesteps self.scheduler.set_timesteps(UpperCAmelCase__ , device=self.device ) __SCREAMING_SNAKE_CASE = self.scheduler.timesteps.to(self.device ) __SCREAMING_SNAKE_CASE = latents for i, t in enumerate(self.progress_bar(UpperCAmelCase__ ) ): # expand the sample if we are doing classifier free guidance __SCREAMING_SNAKE_CASE = torch.cat([sample] * 2 ) if do_classifier_free_guidance else sample # predict the un-noised image # model_output == `log_p_x_0` __SCREAMING_SNAKE_CASE = self.transformer(UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , timestep=UpperCAmelCase__ ).sample if do_classifier_free_guidance: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = model_output.chunk(2 ) __SCREAMING_SNAKE_CASE = model_output_uncond + guidance_scale * (model_output_text - model_output_uncond) model_output -= torch.logsumexp(UpperCAmelCase__ , dim=1 , keepdim=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.truncate(UpperCAmelCase__ , UpperCAmelCase__ ) # remove `log(0)`'s (`-inf`s) __SCREAMING_SNAKE_CASE = model_output.clamp(-7_0 ) # compute the previous noisy sample x_t -> x_t-1 __SCREAMING_SNAKE_CASE = self.scheduler.step(UpperCAmelCase__ , timestep=UpperCAmelCase__ , sample=UpperCAmelCase__ , generator=UpperCAmelCase__ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.vqvae.config.vq_embed_dim __SCREAMING_SNAKE_CASE = (batch_size, self.transformer.height, self.transformer.width, embedding_channels) __SCREAMING_SNAKE_CASE = self.vqvae.quantize.get_codebook_entry(UpperCAmelCase__ , shape=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.vqvae.decode(UpperCAmelCase__ , force_not_quantize=UpperCAmelCase__ ).sample __SCREAMING_SNAKE_CASE = (image / 2 + 0.5).clamp(0 , 1 ) __SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __SCREAMING_SNAKE_CASE = self.numpy_to_pil(UpperCAmelCase__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : torch.FloatTensor , UpperCAmelCase__ : float ) -> torch.FloatTensor: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = torch.sort(UpperCAmelCase__ , 1 , descending=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.exp(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = sorted_p_x_0.cumsum(dim=1 ) < truncation_rate # Ensure that at least the largest probability is not zeroed out __SCREAMING_SNAKE_CASE = torch.full_like(keep_mask[:, 0:1, :] , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.cat((all_true, keep_mask) , dim=1 ) __SCREAMING_SNAKE_CASE = keep_mask[:, :-1, :] __SCREAMING_SNAKE_CASE = keep_mask.gather(1 , indices.argsort(1 ) ) __SCREAMING_SNAKE_CASE = log_p_x_0.clone() __SCREAMING_SNAKE_CASE = -torch.inf # -inf = log(0) return rv
54
"""simple docstring""" import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device a__ : Tuple = False class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" pass @slow @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = VersatileDiffusionImageVariationPipeline.from_pretrained("shi-labs/versatile-diffusion" ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( image=UpperCAmelCase__ , generator=UpperCAmelCase__ , guidance_scale=7.5 , num_inference_steps=5_0 , output_type="numpy" , ).images __SCREAMING_SNAKE_CASE = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __SCREAMING_SNAKE_CASE = np.array([0.0_441, 0.0_469, 0.0_507, 0.0_575, 0.0_632, 0.0_650, 0.0_865, 0.0_909, 0.0_945] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
54
1
"""simple docstring""" import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class UpperCamelCase_ : """simple docstring""" def __init__( self : List[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Tuple=1_3 , UpperCAmelCase__ : Dict=7 , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : Tuple=False , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : List[str]=9_9 , UpperCAmelCase__ : List[Any]=3_2 , UpperCAmelCase__ : str=5 , UpperCAmelCase__ : List[str]=4 , UpperCAmelCase__ : str=3_7 , UpperCAmelCase__ : int="gelu" , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : List[str]=5_1_2 , UpperCAmelCase__ : Union[str, Any]=1_6 , UpperCAmelCase__ : str=2 , UpperCAmelCase__ : Union[str, Any]=0.02 , UpperCAmelCase__ : List[str]=3 , UpperCAmelCase__ : str=4 , UpperCAmelCase__ : List[str]=None , ) -> Tuple: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = scope def UpperCAmelCase_ ( self : Optional[int] ) -> int: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self : str ) -> Tuple: return LlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = LlamaModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict , ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = LlamaModel(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , ) -> str: __SCREAMING_SNAKE_CASE = LlamaForCausalLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , ) -> Any: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = LlamaForCausalLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() # first forward pass __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , use_cache=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , config.vocab_size ) __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and __SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1 ) __SCREAMING_SNAKE_CASE = torch.cat([input_mask, next_mask] , dim=-1 ) __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , )["hidden_states"][0] __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , )["hidden_states"][0] # select random slice __SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1] ).item() __SCREAMING_SNAKE_CASE = output_from_no_past[:, -3:, random_slice_idx].detach() __SCREAMING_SNAKE_CASE = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) def UpperCAmelCase_ ( self : str ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Dict = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () snake_case__ : str = (LlamaForCausalLM,) if is_torch_available() else () snake_case__ : List[Any] = ( { "feature-extraction": LlamaModel, "text-classification": LlamaForSequenceClassification, "text-generation": LlamaForCausalLM, "zero-shot": LlamaForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : Dict = False snake_case__ : Optional[Any] = False def UpperCAmelCase_ ( self : int ) -> Tuple: __SCREAMING_SNAKE_CASE = LlamaModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : List[str] ) -> Optional[Any]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : str ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __SCREAMING_SNAKE_CASE = type self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> List[str]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = input_dict["input_ids"] __SCREAMING_SNAKE_CASE = input_ids.ne(1 ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = LlamaForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = "single_label_classification" __SCREAMING_SNAKE_CASE = input_dict["input_ids"] __SCREAMING_SNAKE_CASE = input_ids.ne(1 ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = LlamaForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self : List[Any] ) -> Dict: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = "multi_label_classification" __SCREAMING_SNAKE_CASE = input_dict["input_ids"] __SCREAMING_SNAKE_CASE = input_ids.ne(1 ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __SCREAMING_SNAKE_CASE = LlamaForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip("LLaMA buffers include complex numbers, which breaks this test" ) def UpperCAmelCase_ ( self : List[Any] ) -> List[str]: pass @parameterized.expand([("linear",), ("dynamic",)] ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Optional[Any] ) -> Dict: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = ids_tensor([1, 1_0] , config.vocab_size ) __SCREAMING_SNAKE_CASE = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(4_2 ) # Fixed seed at init time so the two models get the same random weights __SCREAMING_SNAKE_CASE = LlamaModel(UpperCAmelCase__ ) original_model.to(UpperCAmelCase__ ) original_model.eval() __SCREAMING_SNAKE_CASE = original_model(UpperCAmelCase__ ).last_hidden_state __SCREAMING_SNAKE_CASE = original_model(UpperCAmelCase__ ).last_hidden_state set_seed(4_2 ) # Fixed seed at init time so the two models get the same random weights __SCREAMING_SNAKE_CASE = {"type": scaling_type, "factor": 10.0} __SCREAMING_SNAKE_CASE = LlamaModel(UpperCAmelCase__ ) scaled_model.to(UpperCAmelCase__ ) scaled_model.eval() __SCREAMING_SNAKE_CASE = scaled_model(UpperCAmelCase__ ).last_hidden_state __SCREAMING_SNAKE_CASE = scaled_model(UpperCAmelCase__ ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-5 ) ) else: self.assertFalse(torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-5 ) ) @require_torch class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @unittest.skip("Logits are not exactly the same, once we fix the instabalities somehow, will update!" ) @slow def UpperCAmelCase_ ( self : Tuple ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = [1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8] __SCREAMING_SNAKE_CASE = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf" , device_map="auto" ) __SCREAMING_SNAKE_CASE = model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 __SCREAMING_SNAKE_CASE = torch.tensor([[-6.6_550, -4.1_227, -4.9_859, -3.2_406, 0.8_262, -3.0_033, 1.2_964, -3.3_699]] ) torch.testing.assert_close(out.mean(-1 ) , UpperCAmelCase__ , atol=1E-2 , rtol=1E-2 ) # slicing logits[0, 0, 0:30] # fmt: off __SCREAMING_SNAKE_CASE = torch.tensor([-12.8_281, -7.4_453, -0.4_639, -8.0_625, -7.2_500, -8.0_000, -6.4_883, -7.7_695, -7.8_438, -7.0_312, -6.2_188, -7.1_328, -1.8_496, 1.9_961, -8.6_250, -6.7_227, -12.8_281, -6.9_492, -7.0_742, -7.7_852, -7.5_820, -7.9_062, -6.9_375, -7.9_805, -8.3_438, -8.1_562, -8.0_469, -7.6_250, -7.7_422, -7.3_398,] ) # fmt: on torch.testing.assert_close(out[0, 0, :3_0] , UpperCAmelCase__ , atol=1E-5 , rtol=1E-5 ) @unittest.skip("Logits are not exactly the same, once we fix the instabalities somehow, will update!" ) @slow def UpperCAmelCase_ ( self : List[Any] ) -> Any: __SCREAMING_SNAKE_CASE = [1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8] __SCREAMING_SNAKE_CASE = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-13b-hf" , device_map="auto" ) __SCREAMING_SNAKE_CASE = model(torch.tensor(UpperCAmelCase__ ) ) # Expected mean on dim = -1 __SCREAMING_SNAKE_CASE = torch.tensor([[-2.0_622, -1.2_794, -1.1_638, -0.9_788, -1.4_603, -1.0_238, -1.7_893, -1.4_411]] ) torch.testing.assert_close(out.mean(-1 ) , UpperCAmelCase__ , atol=1E-2 , rtol=1E-2 ) # slicing logits[0, 0, 0:30] # fmt: off __SCREAMING_SNAKE_CASE = torch.tensor([-8.1_406, -8.0_547, 2.7_461, -1.2_344, -0.1_448, -1.8_262, -1.0_020, -1.8_154, -1.6_895, -1.8_516, -2.3_574, -0.9_277, 3.7_598, 6.5_742, -1.2_998, -0.1_177, -8.1_406, -2.9_688, -2.9_199, -3.1_699, -3.5_254, -2.3_555, -2.7_988, -3.4_141, -2.8_262, -4.5_195, -3.3_379, -3.3_164, -2.7_832, -3.0_273] ) # fmt: on torch.testing.assert_close(out[0, 0, :3_0] , UpperCAmelCase__ , atol=1E-5 , rtol=1E-5 ) @unittest.skip("Logits are not exactly the same, once we fix the instabalities somehow, will update!" ) @slow def UpperCAmelCase_ ( self : Dict ) -> int: __SCREAMING_SNAKE_CASE = [1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8] __SCREAMING_SNAKE_CASE = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-13b-chat-hf" , device_map="auto" ) __SCREAMING_SNAKE_CASE = model(torch.tensor(UpperCAmelCase__ ) ) # Expected mean on dim = -1 __SCREAMING_SNAKE_CASE = torch.tensor([[-0.8_562, -1.8_520, -0.7_551, -0.4_162, -1.5_161, -1.2_038, -2.4_823, -2.3_254]] ) torch.testing.assert_close(out.mean(-1 ) , UpperCAmelCase__ , atol=1E-2 , rtol=1E-2 ) # slicing logits[0, 0, 0:30] # fmt: off __SCREAMING_SNAKE_CASE = torch.tensor([-2.2_227, 4.8_828, 0.9_023, -0.4_578, -0.7_871, -0.1_033, -0.6_221, -0.5_786, -0.7_803, -1.0_674, -1.2_920, -0.1_570, 0.8_008, 2.0_723, -0.9_497, 0.2_771, -2.2_227, -0.7_612, -1.4_346, -1.2_061, -1.6_426, -0.3_000, -0.7_139, -1.1_934, -1.8_691, -1.6_973, -1.5_947, -1.2_705, -0.3_523, -0.5_513] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) , UpperCAmelCase__ , atol=1E-2 , rtol=1E-2 ) @unittest.skip( "Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test" ) @slow def UpperCAmelCase_ ( self : Dict ) -> int: __SCREAMING_SNAKE_CASE = [1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8] __SCREAMING_SNAKE_CASE = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-70b-hf" , device_map="auto" ) __SCREAMING_SNAKE_CASE = model(torch.tensor(UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = torch.tensor( [[-4.2_327, -3.3_360, -4.6_665, -4.7_631, -1.8_180, -3.4_170, -1.4_211, -3.1_810]] , dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) , UpperCAmelCase__ , atol=1E-2 , rtol=1E-2 ) # fmt: off __SCREAMING_SNAKE_CASE = torch.tensor([-9.4_922, -3.9_551, 1.7_998, -5.6_758, -5.1_055, -5.8_984, -4.8_320, -6.8_086, -6.5_391, -5.6_172, -5.5_820, -5.5_352, 1.7_881, 3.6_289, -6.5_117, -3.4_785, -9.5_000, -6.0_352, -6.8_125, -6.0_195, -6.6_836, -5.4_727, -6.2_812, -6.0_391, -7.3_398, -7.4_297, -7.4_844, -6.5_820, -5.8_789, -5.5_312] ) # fmt: on torch.testing.assert_close(out[0, 0, :3_0] , UpperCAmelCase__ , atol=1E-5 , rtol=1E-5 ) @unittest.skip("Model is curently gated" ) @slow def UpperCAmelCase_ ( self : Any ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = "Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the \"princi" __SCREAMING_SNAKE_CASE = "Simply put, the theory of relativity states that " __SCREAMING_SNAKE_CASE = LlamaTokenizer.from_pretrained("meta-llama/Llama-2-13b-chat-hf" ) __SCREAMING_SNAKE_CASE = tokenizer.encode(UpperCAmelCase__ , return_tensors="pt" ) __SCREAMING_SNAKE_CASE = LlamaForCausalLM.from_pretrained( "meta-llama/Llama-2-13b-chat-hf" , device_map="sequential" , use_safetensors=UpperCAmelCase__ ) # greedy generation outputs __SCREAMING_SNAKE_CASE = model.generate(UpperCAmelCase__ , max_new_tokens=6_4 , top_p=UpperCAmelCase__ , temperature=1 , do_sample=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.decode(generated_ids[0] , skip_special_tokens=UpperCAmelCase__ ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ )
54
"""simple docstring""" import importlib.util import json import os import warnings from dataclasses import dataclass, field import torch from ..training_args import TrainingArguments from ..utils import cached_property, is_sagemaker_dp_enabled, logging a__ : Union[str, Any] = logging.get_logger(__name__) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = os.getenv("SM_HP_MP_PARAMETERS" , "{}" ) try: # Parse it and check the field "partitions" is included, it is required for model parallel. __SCREAMING_SNAKE_CASE = json.loads(lowerCAmelCase_ ) if "partitions" not in smp_options: return False except json.JSONDecodeError: return False # Get the sagemaker specific framework parameters from mpi_options variable. __SCREAMING_SNAKE_CASE = os.getenv("SM_FRAMEWORK_PARAMS" , "{}" ) try: # Parse it and check the field "sagemaker_distributed_dataparallel_enabled". __SCREAMING_SNAKE_CASE = json.loads(lowerCAmelCase_ ) if not mpi_options.get("sagemaker_mpi_enabled" , lowerCAmelCase_ ): return False except json.JSONDecodeError: return False # Lastly, check if the `smdistributed` module is present. return importlib.util.find_spec("smdistributed" ) is not None if is_sagemaker_model_parallel_available(): import smdistributed.modelparallel.torch as smp smp.init() @dataclass class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = field( default="" , metadata={"help": "Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer"} , ) def UpperCAmelCase_ ( self : List[str] ) -> Any: super().__post_init__() warnings.warn( "`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use " "`TrainingArguments` instead." , UpperCAmelCase__ , ) @cached_property def UpperCAmelCase_ ( self : List[str] ) -> "torch.device": logger.info("PyTorch: setting up devices" ) if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1: logger.warning( "torch.distributed process group is initialized, but local_rank == -1. " "In order to use Torch DDP, launch your script with `python -m torch.distributed.launch" ) if self.no_cuda: __SCREAMING_SNAKE_CASE = torch.device("cpu" ) __SCREAMING_SNAKE_CASE = 0 elif is_sagemaker_model_parallel_available(): __SCREAMING_SNAKE_CASE = smp.local_rank() __SCREAMING_SNAKE_CASE = torch.device("cuda" , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = 1 elif is_sagemaker_dp_enabled(): import smdistributed.dataparallel.torch.torch_smddp # noqa: F401 torch.distributed.init_process_group(backend="smddp" , timeout=self.ddp_timeout_delta ) __SCREAMING_SNAKE_CASE = int(os.getenv("SMDATAPARALLEL_LOCAL_RANK" ) ) __SCREAMING_SNAKE_CASE = torch.device("cuda" , self.local_rank ) __SCREAMING_SNAKE_CASE = 1 elif self.local_rank == -1: # if n_gpu is > 1 we'll use nn.DataParallel. # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0` # Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will # trigger an error that a device index is missing. Index 0 takes into account the # GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0` # will use the first GPU in that env, i.e. GPU#1 __SCREAMING_SNAKE_CASE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" ) # Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at # the default value. __SCREAMING_SNAKE_CASE = torch.cuda.device_count() else: # Here, we'll use torch.distributed. # Initializes the distributed backend which will take care of synchronizing nodes/GPUs if not torch.distributed.is_initialized(): torch.distributed.init_process_group(backend="nccl" , timeout=self.ddp_timeout_delta ) __SCREAMING_SNAKE_CASE = torch.device("cuda" , self.local_rank ) __SCREAMING_SNAKE_CASE = 1 if device.type == "cuda": torch.cuda.set_device(UpperCAmelCase__ ) return device @property def UpperCAmelCase_ ( self : Dict ) -> Any: if is_sagemaker_model_parallel_available(): return smp.dp_size() return super().world_size @property def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[Any]: return not is_sagemaker_model_parallel_available() @property def UpperCAmelCase_ ( self : Tuple ) -> int: return False
54
1
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if number > 0: raise ValueError("input must be a negative integer" ) __SCREAMING_SNAKE_CASE = len(bin(lowerCAmelCase_ )[3:] ) __SCREAMING_SNAKE_CASE = bin(abs(lowerCAmelCase_ ) - (1 << binary_number_length) )[3:] __SCREAMING_SNAKE_CASE = ( ( "1" + "0" * (binary_number_length - len(lowerCAmelCase_ )) + twos_complement_number ) if number < 0 else "0" ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
54
"""simple docstring""" import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Optional[int] ) -> List[str]: # For consistency across different places the DisjunctiveConstraint is called, # dc.token_ids is a list of integers. It is also initialized only by integers. __SCREAMING_SNAKE_CASE = [[1, 2, 4], [1, 2, 3, 4]] __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(UpperCAmelCase__ ) self.assertTrue(isinstance(dc.token_ids , UpperCAmelCase__ ) ) with self.assertRaises(UpperCAmelCase__ ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(UpperCAmelCase__ ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def UpperCAmelCase_ ( self : Any ) -> int: # We can't have constraints that are complete subsets of another. This leads to a preverse # interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint? # It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially # fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm # will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it). __SCREAMING_SNAKE_CASE = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(UpperCAmelCase__ ): DisjunctiveConstraint(UpperCAmelCase__ ) # fails here def UpperCAmelCase_ ( self : List[Any] ) -> Any: __SCREAMING_SNAKE_CASE = [[1, 2, 3], [1, 2, 4]] __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) __SCREAMING_SNAKE_CASE = stepped is True and completed is False and reset is False self.assertTrue(UpperCAmelCase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) __SCREAMING_SNAKE_CASE = stepped is True and completed is False and reset is False self.assertTrue(UpperCAmelCase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(3 ) __SCREAMING_SNAKE_CASE = stepped is True and completed is True and reset is False self.assertTrue(UpperCAmelCase__ ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def UpperCAmelCase_ ( self : str ) -> List[str]: __SCREAMING_SNAKE_CASE = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
54
1
"""simple docstring""" from __future__ import annotations import pandas as pd def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [0] * no_of_processes __SCREAMING_SNAKE_CASE = [0] * no_of_processes # Copy the burst time into remaining_time[] for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = burst_time[i] __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 9_9999_9999 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = False # Process until all processes are completed while complete != no_of_processes: for j in range(lowerCAmelCase_ ): if arrival_time[j] <= increment_time and remaining_time[j] > 0: if remaining_time[j] < minm: __SCREAMING_SNAKE_CASE = remaining_time[j] __SCREAMING_SNAKE_CASE = j __SCREAMING_SNAKE_CASE = True if not check: increment_time += 1 continue remaining_time[short] -= 1 __SCREAMING_SNAKE_CASE = remaining_time[short] if minm == 0: __SCREAMING_SNAKE_CASE = 9_9999_9999 if remaining_time[short] == 0: complete += 1 __SCREAMING_SNAKE_CASE = False # Find finish time of current process __SCREAMING_SNAKE_CASE = increment_time + 1 # Calculate waiting time __SCREAMING_SNAKE_CASE = finish_time - arrival_time[short] __SCREAMING_SNAKE_CASE = finar - burst_time[short] if waiting_time[short] < 0: __SCREAMING_SNAKE_CASE = 0 # Increment time increment_time += 1 return waiting_time def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [0] * no_of_processes for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = burst_time[i] + waiting_time[i] return turn_around_time def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = total_waiting_time + waiting_time[i] __SCREAMING_SNAKE_CASE = total_turn_around_time + turn_around_time[i] print(f"""Average waiting time = {total_waiting_time / no_of_processes:.5f}""" ) print("Average turn around time =" , total_turn_around_time / no_of_processes ) if __name__ == "__main__": print('''Enter how many process you want to analyze''') a__ : Optional[Any] = int(input()) a__ : Optional[int] = [0] * no_of_processes a__ : int = [0] * no_of_processes a__ : List[Any] = list(range(1, no_of_processes + 1)) for i in range(no_of_processes): print('''Enter the arrival time and burst time for process:--''' + str(i + 1)) a__ , a__ : Tuple = map(int, input().split()) a__ : int = calculate_waitingtime(arrival_time, burst_time, no_of_processes) a__ : Dict = burst_time a__ : Any = no_of_processes a__ : Optional[int] = waiting_time a__ : Union[str, Any] = calculate_turnaroundtime(bt, n, wt) calculate_average_times(waiting_time, turn_around_time, no_of_processes) a__ : str = pd.DataFrame( list(zip(processes, burst_time, arrival_time, waiting_time, turn_around_time)), columns=[ '''Process''', '''BurstTime''', '''ArrivalTime''', '''WaitingTime''', '''TurnAroundTime''', ], ) # Printing the dataFrame pd.set_option('''display.max_rows''', fcfs.shape[0] + 1) print(fcfs)
54
"""simple docstring""" from __future__ import annotations def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = None ): '''simple docstring''' if start is None: __SCREAMING_SNAKE_CASE = 0 if end is None: __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) - 1 if start >= end: return __SCREAMING_SNAKE_CASE = (start + end) // 2 slowsort(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) slowsort(lowerCAmelCase_ , mid + 1 , lowerCAmelCase_ ) if sequence[end] < sequence[mid]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = sequence[mid], sequence[end] slowsort(lowerCAmelCase_ , lowerCAmelCase_ , end - 1 ) if __name__ == "__main__": from doctest import testmod testmod()
54
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableUnCLIPImgaImgPipeline, UNetaDConditionModel from diffusers.pipelines.pipeline_utils import DiffusionPipeline from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import ( enable_full_determinism, floats_tensor, load_image, load_numpy, require_torch_gpu, skip_mps, slow, torch_device, ) from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Dict = StableUnCLIPImgaImgPipeline snake_case__ : Dict = TEXT_GUIDED_IMAGE_VARIATION_PARAMS snake_case__ : str = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS snake_case__ : Union[str, Any] = frozenset( []) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess snake_case__ : Union[str, Any] = frozenset([]) def UpperCAmelCase_ ( self : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = 3_2 __SCREAMING_SNAKE_CASE = embedder_hidden_size # image encoding components __SCREAMING_SNAKE_CASE = CLIPImageProcessor(crop_size=3_2 , size=3_2 ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = CLIPVisionModelWithProjection( CLIPVisionConfig( hidden_size=UpperCAmelCase__ , projection_dim=UpperCAmelCase__ , num_hidden_layers=5 , num_attention_heads=4 , image_size=3_2 , intermediate_size=3_7 , patch_size=1 , ) ) # regular denoising components torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = StableUnCLIPImageNormalizer(embedding_dim=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = DDPMScheduler(beta_schedule="squaredcos_cap_v2" ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=UpperCAmelCase__ , projection_dim=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 , ) ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = UNetaDConditionModel( sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "CrossAttnUpBlock2D") , block_out_channels=(3_2, 6_4) , attention_head_dim=(2, 4) , class_embed_type="projection" , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=UpperCAmelCase__ , layers_per_block=1 , upcast_attention=UpperCAmelCase__ , use_linear_projection=UpperCAmelCase__ , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = DDIMScheduler( beta_schedule="scaled_linear" , beta_start=0.00_085 , beta_end=0.012 , prediction_type="v_prediction" , set_alpha_to_one=UpperCAmelCase__ , steps_offset=1 , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = AutoencoderKL() __SCREAMING_SNAKE_CASE = { # image encoding components "feature_extractor": feature_extractor, "image_encoder": image_encoder.eval(), # image noising components "image_normalizer": image_normalizer.eval(), "image_noising_scheduler": image_noising_scheduler, # regular denoising components "tokenizer": tokenizer, "text_encoder": text_encoder.eval(), "unet": unet.eval(), "scheduler": scheduler, "vae": vae.eval(), } return components def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : int=0 , UpperCAmelCase__ : Union[str, Any]=True ) -> Optional[int]: if str(UpperCAmelCase__ ).startswith("mps" ): __SCREAMING_SNAKE_CASE = torch.manual_seed(UpperCAmelCase__ ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(UpperCAmelCase__ ) ).to(UpperCAmelCase__ ) if pil_image: __SCREAMING_SNAKE_CASE = input_image * 0.5 + 0.5 __SCREAMING_SNAKE_CASE = input_image.clamp(0 , 1 ) __SCREAMING_SNAKE_CASE = input_image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() __SCREAMING_SNAKE_CASE = DiffusionPipeline.numpy_to_pil(UpperCAmelCase__ )[0] return { "prompt": "An anime racoon running a marathon", "image": input_image, "generator": generator, "num_inference_steps": 2, "output_type": "np", } @skip_mps def UpperCAmelCase_ ( self : Optional[int] ) -> List[str]: __SCREAMING_SNAKE_CASE = "cpu" # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE = self.get_dummy_components() __SCREAMING_SNAKE_CASE = StableUnCLIPImgaImgPipeline(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = sd_pipe.to(UpperCAmelCase__ ) sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(UpperCAmelCase__ ) inputs.update({"image_embeds": None} ) __SCREAMING_SNAKE_CASE = sd_pipe(**UpperCAmelCase__ ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) __SCREAMING_SNAKE_CASE = np.array([0.3_872, 0.7_224, 0.5_601, 0.4_741, 0.6_872, 0.5_814, 0.4_636, 0.3_867, 0.5_078] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def UpperCAmelCase_ ( self : Optional[int] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = torch_device in ["cpu", "mps"] self._test_attention_slicing_forward_pass(test_max_difference=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = torch_device in ["cpu", "mps"] self._test_inference_batch_single_identical(test_max_difference=UpperCAmelCase__ ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def UpperCAmelCase_ ( self : Any ) -> Any: self._test_xformers_attention_forwardGenerator_pass(test_max_difference=UpperCAmelCase__ ) @slow @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Optional[Any] ) -> int: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase_ ( self : Any ) -> List[str]: __SCREAMING_SNAKE_CASE = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png" ) __SCREAMING_SNAKE_CASE = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_img2img_anime_turtle_fp16.npy" ) __SCREAMING_SNAKE_CASE = StableUnCLIPImgaImgPipeline.from_pretrained( "fusing/stable-unclip-2-1-l-img2img" , torch_dtype=torch.floataa ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __SCREAMING_SNAKE_CASE = torch.Generator(device="cpu" ).manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe(UpperCAmelCase__ , "anime turle" , generator=UpperCAmelCase__ , output_type="np" ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (7_6_8, 7_6_8, 3) assert_mean_pixel_difference(UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png" ) __SCREAMING_SNAKE_CASE = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_h_img2img_anime_turtle_fp16.npy" ) __SCREAMING_SNAKE_CASE = StableUnCLIPImgaImgPipeline.from_pretrained( "fusing/stable-unclip-2-1-h-img2img" , torch_dtype=torch.floataa ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __SCREAMING_SNAKE_CASE = torch.Generator(device="cpu" ).manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe(UpperCAmelCase__ , "anime turle" , generator=UpperCAmelCase__ , output_type="np" ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (7_6_8, 7_6_8, 3) assert_mean_pixel_difference(UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> Any: __SCREAMING_SNAKE_CASE = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png" ) torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __SCREAMING_SNAKE_CASE = StableUnCLIPImgaImgPipeline.from_pretrained( "fusing/stable-unclip-2-1-h-img2img" , torch_dtype=torch.floataa ) __SCREAMING_SNAKE_CASE = pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __SCREAMING_SNAKE_CASE = pipe( UpperCAmelCase__ , "anime turtle" , num_inference_steps=2 , output_type="np" , ) __SCREAMING_SNAKE_CASE = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 1_0**9
54
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if number > 0: raise ValueError("input must be a negative integer" ) __SCREAMING_SNAKE_CASE = len(bin(lowerCAmelCase_ )[3:] ) __SCREAMING_SNAKE_CASE = bin(abs(lowerCAmelCase_ ) - (1 << binary_number_length) )[3:] __SCREAMING_SNAKE_CASE = ( ( "1" + "0" * (binary_number_length - len(lowerCAmelCase_ )) + twos_complement_number ) if number < 0 else "0" ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
54
1
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) for _ in range(lowerCAmelCase_ ): for i in range(_ % 2 , arr_size - 1 , 2 ): if arr[i + 1] < arr[i]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = arr[i + 1], arr[i] return arr if __name__ == "__main__": a__ : str = list(range(1_0, 0, -1)) print(F"Original: {arr}. Sorted: {odd_even_transposition(arr)}")
54
"""simple docstring""" import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Any = CLIPTokenizer snake_case__ : Dict = CLIPTokenizerFast snake_case__ : List[Any] = True snake_case__ : Optional[Any] = {} snake_case__ : Dict = False def UpperCAmelCase_ ( self : Any ) -> Any: super().setUp() # fmt: off __SCREAMING_SNAKE_CASE = ["l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"] # fmt: on __SCREAMING_SNAKE_CASE = dict(zip(UpperCAmelCase__ , range(len(UpperCAmelCase__ ) ) ) ) __SCREAMING_SNAKE_CASE = ["#version: 0.2", "l o", "lo w</w>", "e r</w>"] __SCREAMING_SNAKE_CASE = {"unk_token": "<unk>"} __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(UpperCAmelCase__ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(UpperCAmelCase__ ) ) def UpperCAmelCase_ ( self : List[Any] , **UpperCAmelCase__ : Tuple ) -> List[Any]: kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any , **UpperCAmelCase__ : Optional[Any] ) -> List[str]: kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = "lower newer" __SCREAMING_SNAKE_CASE = "lower newer" return input_text, output_text def UpperCAmelCase_ ( self : int ) -> List[str]: __SCREAMING_SNAKE_CASE = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __SCREAMING_SNAKE_CASE = "lower newer" __SCREAMING_SNAKE_CASE = ["lo", "w", "er</w>", "n", "e", "w", "er</w>"] __SCREAMING_SNAKE_CASE = tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokens + [tokenizer.unk_token] __SCREAMING_SNAKE_CASE = [1_0, 2, 1_6, 9, 3, 2, 1_6, 2_0] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , UpperCAmelCase__ ) @require_ftfy def UpperCAmelCase_ ( self : Optional[Any] ) -> int: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = "A\n'll 11p223RF☆ho!!to?'d'd''d of a cat to-$''d." __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways __SCREAMING_SNAKE_CASE = "xa\u0303y" + " " + "x\xe3y" __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Test that the tokenization is identical on unicode of space type __SCREAMING_SNAKE_CASE = [ "\u0009", # (horizontal tab, '\t') "\u000B", # (vertical tab) "\u000C", # (form feed) "\u0020", # (space, ' ') "\u200E", # (left-to-right mark):w "\u200F", # (right-to-left mark) ] for unicode_seq in spaces_unicodes: __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Test that the tokenization is identical on unicode of line break type __SCREAMING_SNAKE_CASE = [ "\u000A", # (line feed, '\n') "\r\n", # (carriage return and line feed, '\r\n') "\u000D", # (carriage return, '\r') "\r", # (carriage return, '\r') "\u000D", # (carriage return, '\r') "\u2028", # (line separator) "\u2029", # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Optional[Any]: # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = "hello" # `hello` is a token in the vocabulary of `pretrained_name` __SCREAMING_SNAKE_CASE = F"""{text_of_1_token} {text_of_1_token}""" __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(UpperCAmelCase__ ) + 1, len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , ) __SCREAMING_SNAKE_CASE = F""" {text}""" __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(UpperCAmelCase__ ) + 1, 1 + len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , ) def UpperCAmelCase_ ( self : str ) -> Optional[int]: # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(UpperCAmelCase__ ) as context: self.rust_tokenizer_class.from_pretrained("robot-test/old-clip-tokenizer" ) self.assertTrue( context.exception.args[0].startswith( "The `backend_tokenizer` provided does not match the expected format." ) ) @require_ftfy def UpperCAmelCase_ ( self : Optional[int] ) -> int: super().test_tokenization_python_rust_equals() def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[Any]: # CLIP always lower cases letters pass
54
1
"""simple docstring""" import numpy as np class UpperCamelCase_ : """simple docstring""" def __init__( self : Optional[Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = (0, 0) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 def __eq__( self : Union[str, Any] , UpperCAmelCase__ : List[Any] ) -> Dict: return self.position == cell.position def UpperCAmelCase_ ( self : Optional[Any] ) -> Tuple: print(self.position ) class UpperCamelCase_ : """simple docstring""" def __init__( self : Union[str, Any] , UpperCAmelCase__ : int=(5, 5) ) -> Dict: __SCREAMING_SNAKE_CASE = np.zeros(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = world_size[0] __SCREAMING_SNAKE_CASE = world_size[1] def UpperCAmelCase_ ( self : Tuple ) -> Optional[int]: print(self.w ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : List[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] __SCREAMING_SNAKE_CASE = cell.position[0] __SCREAMING_SNAKE_CASE = cell.position[1] __SCREAMING_SNAKE_CASE = [] for n in neughbour_cord: __SCREAMING_SNAKE_CASE = current_x + n[0] __SCREAMING_SNAKE_CASE = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: __SCREAMING_SNAKE_CASE = Cell() __SCREAMING_SNAKE_CASE = (x, y) __SCREAMING_SNAKE_CASE = cell neighbours.append(UpperCAmelCase__ ) return neighbours def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] _open.append(lowerCAmelCase_ ) while _open: __SCREAMING_SNAKE_CASE = np.argmin([n.f for n in _open] ) __SCREAMING_SNAKE_CASE = _open[min_f] _closed.append(_open.pop(lowerCAmelCase_ ) ) if current == goal: break for n in world.get_neigbours(lowerCAmelCase_ ): for c in _closed: if c == n: continue __SCREAMING_SNAKE_CASE = current.g + 1 __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = n.position __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = goal.position __SCREAMING_SNAKE_CASE = (ya - ya) ** 2 + (xa - xa) ** 2 __SCREAMING_SNAKE_CASE = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [] while current.parent is not None: path.append(current.position ) __SCREAMING_SNAKE_CASE = current.parent path.append(current.position ) return path[::-1] if __name__ == "__main__": a__ : Tuple = Gridworld() # Start position and goal a__ : int = Cell() a__ : Optional[int] = (0, 0) a__ : Optional[Any] = Cell() a__ : List[str] = (4, 4) print(F"path from {start.position} to {goal.position}") a__ : Union[str, Any] = astar(world, start, goal) # Just for visual reasons. for i in s: a__ : Union[str, Any] = 1 print(world.w)
54
"""simple docstring""" import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( "kwargs, expected" , [ ({"num_shards": 0, "max_num_jobs": 1}, []), ({"num_shards": 10, "max_num_jobs": 1}, [range(10 )]), ({"num_shards": 10, "max_num_jobs": 10}, [range(lowerCAmelCase_ , i + 1 ) for i in range(10 )]), ({"num_shards": 1, "max_num_jobs": 10}, [range(1 )]), ({"num_shards": 10, "max_num_jobs": 3}, [range(0 , 4 ), range(4 , 7 ), range(7 , 10 )]), ({"num_shards": 3, "max_num_jobs": 10}, [range(0 , 1 ), range(1 , 2 ), range(2 , 3 )]), ] , ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = _distribute_shards(**lowerCAmelCase_ ) assert out == expected @pytest.mark.parametrize( "gen_kwargs, max_num_jobs, expected" , [ ({"foo": 0}, 10, [{"foo": 0}]), ({"shards": [0, 1, 2, 3]}, 1, [{"shards": [0, 1, 2, 3]}]), ({"shards": [0, 1, 2, 3]}, 4, [{"shards": [0]}, {"shards": [1]}, {"shards": [2]}, {"shards": [3]}]), ({"shards": [0, 1]}, 4, [{"shards": [0]}, {"shards": [1]}]), ({"shards": [0, 1, 2, 3]}, 2, [{"shards": [0, 1]}, {"shards": [2, 3]}]), ] , ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = _split_gen_kwargs(lowerCAmelCase_ , lowerCAmelCase_ ) assert out == expected @pytest.mark.parametrize( "gen_kwargs, expected" , [ ({"foo": 0}, 1), ({"shards": [0]}, 1), ({"shards": [0, 1, 2, 3]}, 4), ({"shards": [0, 1, 2, 3], "foo": 0}, 4), ({"shards": [0, 1, 2, 3], "other": (0, 1)}, 4), ({"shards": [0, 1, 2, 3], "shards2": [0, 1]}, RuntimeError), ] , ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if expected is RuntimeError: with pytest.raises(lowerCAmelCase_ ): _number_of_shards_in_gen_kwargs(lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = _number_of_shards_in_gen_kwargs(lowerCAmelCase_ ) assert out == expected
54
1
"""simple docstring""" from __future__ import annotations import math def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if num <= 0: __SCREAMING_SNAKE_CASE = f"""{num}: Invalid input, please enter a positive integer.""" raise ValueError(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [True] * (num + 1) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = 2 __SCREAMING_SNAKE_CASE = int(math.sqrt(lowerCAmelCase_ ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(lowerCAmelCase_ ) # Set multiples of start be False for i in range(start * start , num + 1 , lowerCAmelCase_ ): if sieve[i] is True: __SCREAMING_SNAKE_CASE = False start += 1 for j in range(end + 1 , num + 1 ): if sieve[j] is True: prime.append(lowerCAmelCase_ ) return prime if __name__ == "__main__": print(prime_sieve(int(input('''Enter a positive integer: ''').strip())))
54
"""simple docstring""" import unittest from transformers.testing_utils import CaptureStdout from transformers.tools.python_interpreter import evaluate def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return x + 2 class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Any ) -> Any: __SCREAMING_SNAKE_CASE = "x = 3" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result == 3 self.assertDictEqual(UpperCAmelCase__ , {"x": 3} ) __SCREAMING_SNAKE_CASE = "x = y" __SCREAMING_SNAKE_CASE = {"y": 5} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 5, "y": 5} ) def UpperCAmelCase_ ( self : Dict ) -> List[str]: __SCREAMING_SNAKE_CASE = "y = add_two(x)" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 5} ) # Won't work without the tool with CaptureStdout() as out: __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result is None assert "tried to execute add_two" in out.out def UpperCAmelCase_ ( self : List[Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = "x = 3" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result == 3 self.assertDictEqual(UpperCAmelCase__ , {"x": 3} ) def UpperCAmelCase_ ( self : str ) -> Any: __SCREAMING_SNAKE_CASE = "test_dict = {'x': x, 'y': add_two(x)}" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 5} ) self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_dict": {"x": 3, "y": 5}} ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = "x = 3\ny = 5" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 5} ) def UpperCAmelCase_ ( self : Any ) -> Any: __SCREAMING_SNAKE_CASE = "text = f'This is x: {x}.'" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == "This is x: 3." self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "text": "This is x: 3."} ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = "if x <= 3:\n y = 2\nelse:\n y = 5" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 2 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 2} ) __SCREAMING_SNAKE_CASE = {"x": 8} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 8, "y": 5} ) def UpperCAmelCase_ ( self : Tuple ) -> str: __SCREAMING_SNAKE_CASE = "test_list = [x, add_two(x)]" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , [3, 5] ) self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_list": [3, 5]} ) def UpperCAmelCase_ ( self : Any ) -> int: __SCREAMING_SNAKE_CASE = "y = x" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result == 3 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 3} ) def UpperCAmelCase_ ( self : Tuple ) -> int: __SCREAMING_SNAKE_CASE = "test_list = [x, add_two(x)]\ntest_list[1]" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_list": [3, 5]} ) __SCREAMING_SNAKE_CASE = "test_dict = {'x': x, 'y': add_two(x)}\ntest_dict['y']" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_dict": {"x": 3, "y": 5}} ) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = "x = 0\nfor i in range(3):\n x = i" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"range": range} , state=UpperCAmelCase__ ) assert result == 2 self.assertDictEqual(UpperCAmelCase__ , {"x": 2, "i": 2} )
54
1
"""simple docstring""" import json import os import pickle import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers import is_faiss_available from transformers.models.bart.configuration_bart import BartConfig from transformers.models.bart.tokenization_bart import BartTokenizer from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES from transformers.models.dpr.configuration_dpr import DPRConfig from transformers.models.dpr.tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer from transformers.models.rag.configuration_rag import RagConfig from transformers.models.rag.retrieval_rag import CustomHFIndex, RagRetriever from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES from transformers.testing_utils import require_faiss, require_sentencepiece, require_tokenizers, require_torch if is_faiss_available(): import faiss @require_faiss class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def UpperCAmelCase_ ( self : List[str] ) -> str: __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = 8 # DPR tok __SCREAMING_SNAKE_CASE = [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , "dpr_tokenizer" ) os.makedirs(UpperCAmelCase__ , exist_ok=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = os.path.join(UpperCAmelCase__ , DPR_VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) # BART tok __SCREAMING_SNAKE_CASE = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "\u0120", "\u0120l", "\u0120n", "\u0120lo", "\u0120low", "er", "\u0120lowest", "\u0120newer", "\u0120wider", "<unk>", ] __SCREAMING_SNAKE_CASE = dict(zip(UpperCAmelCase__ , range(len(UpperCAmelCase__ ) ) ) ) __SCREAMING_SNAKE_CASE = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""] __SCREAMING_SNAKE_CASE = {"unk_token": "<unk>"} __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , "bart_tokenizer" ) os.makedirs(UpperCAmelCase__ , exist_ok=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = os.path.join(UpperCAmelCase__ , BART_VOCAB_FILES_NAMES["vocab_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(UpperCAmelCase__ , BART_VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(UpperCAmelCase__ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(UpperCAmelCase__ ) ) def UpperCAmelCase_ ( self : List[str] ) -> DPRQuestionEncoderTokenizer: return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , "dpr_tokenizer" ) ) def UpperCAmelCase_ ( self : Tuple ) -> DPRContextEncoderTokenizer: return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , "dpr_tokenizer" ) ) def UpperCAmelCase_ ( self : Tuple ) -> BartTokenizer: return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname , "bart_tokenizer" ) ) def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: shutil.rmtree(self.tmpdirname ) def UpperCAmelCase_ ( self : List[str] ) -> str: __SCREAMING_SNAKE_CASE = Dataset.from_dict( { "id": ["0", "1"], "text": ["foo", "bar"], "title": ["Foo", "Bar"], "embeddings": [np.ones(self.retrieval_vector_size ), 2 * np.ones(self.retrieval_vector_size )], } ) dataset.add_faiss_index("embeddings" , string_factory="Flat" , metric_type=faiss.METRIC_INNER_PRODUCT ) return dataset def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.get_dummy_dataset() __SCREAMING_SNAKE_CASE = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , ) with patch("transformers.models.rag.retrieval_rag.load_dataset" ) as mock_load_dataset: __SCREAMING_SNAKE_CASE = dataset __SCREAMING_SNAKE_CASE = RagRetriever( UpperCAmelCase__ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) return retriever def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : bool ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.get_dummy_dataset() __SCREAMING_SNAKE_CASE = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name="custom" , ) if from_disk: __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , "dataset" ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , "index.faiss" ) dataset.get_index("embeddings" ).save(os.path.join(self.tmpdirname , "index.faiss" ) ) dataset.drop_index("embeddings" ) dataset.save_to_disk(os.path.join(self.tmpdirname , "dataset" ) ) del dataset __SCREAMING_SNAKE_CASE = RagRetriever( UpperCAmelCase__ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) else: __SCREAMING_SNAKE_CASE = RagRetriever( UpperCAmelCase__ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , index=CustomHFIndex(config.retrieval_vector_size , UpperCAmelCase__ ) , ) return retriever def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = Dataset.from_dict( { "id": ["0", "1"], "text": ["foo", "bar"], "title": ["Foo", "Bar"], "embeddings": [np.ones(self.retrieval_vector_size + 1 ), 2 * np.ones(self.retrieval_vector_size + 1 )], } ) dataset.add_faiss_index("embeddings" , string_factory="Flat" , metric_type=faiss.METRIC_INNER_PRODUCT ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , "hf_bert_base.hnswSQ8_correct_phi_128.c_index" ) dataset.save_faiss_index("embeddings" , index_file_name + ".index.dpr" ) pickle.dump(dataset["id"] , open(index_file_name + ".index_meta.dpr" , "wb" ) ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , "psgs_w100.tsv.pkl" ) __SCREAMING_SNAKE_CASE = {sample["id"]: [sample["text"], sample["title"]] for sample in dataset} pickle.dump(UpperCAmelCase__ , open(UpperCAmelCase__ , "wb" ) ) __SCREAMING_SNAKE_CASE = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name="legacy" , index_path=self.tmpdirname , ) __SCREAMING_SNAKE_CASE = RagRetriever( UpperCAmelCase__ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() ) return retriever def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = self.get_dummy_canonical_hf_index_retriever() __SCREAMING_SNAKE_CASE = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = retriever.retrieve(UpperCAmelCase__ , n_docs=UpperCAmelCase__ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(UpperCAmelCase__ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ["embeddings", "id", "text", "title"] ) self.assertEqual(len(doc_dicts[0]["id"] ) , UpperCAmelCase__ ) self.assertEqual(doc_dicts[0]["id"][0] , "1" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["id"][0] , "0" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def UpperCAmelCase_ ( self : Dict ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.get_dummy_canonical_hf_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: with patch("transformers.models.rag.retrieval_rag.load_dataset" ) as mock_load_dataset: __SCREAMING_SNAKE_CASE = self.get_dummy_dataset() retriever.save_pretrained(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = RagRetriever.from_pretrained(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) __SCREAMING_SNAKE_CASE = retriever.retrieve(UpperCAmelCase__ , n_docs=1 ) self.assertTrue(out is not None ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = self.get_dummy_custom_hf_index_retriever(from_disk=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = retriever.retrieve(UpperCAmelCase__ , n_docs=UpperCAmelCase__ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(UpperCAmelCase__ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ["embeddings", "id", "text", "title"] ) self.assertEqual(len(doc_dicts[0]["id"] ) , UpperCAmelCase__ ) self.assertEqual(doc_dicts[0]["id"][0] , "1" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["id"][0] , "0" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def UpperCAmelCase_ ( self : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = self.get_dummy_custom_hf_index_retriever(from_disk=UpperCAmelCase__ ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = RagRetriever.from_pretrained(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) __SCREAMING_SNAKE_CASE = retriever.retrieve(UpperCAmelCase__ , n_docs=1 ) self.assertTrue(out is not None ) def UpperCAmelCase_ ( self : List[str] ) -> Any: __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = self.get_dummy_custom_hf_index_retriever(from_disk=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = retriever.retrieve(UpperCAmelCase__ , n_docs=UpperCAmelCase__ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(UpperCAmelCase__ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ["embeddings", "id", "text", "title"] ) self.assertEqual(len(doc_dicts[0]["id"] ) , UpperCAmelCase__ ) self.assertEqual(doc_dicts[0]["id"][0] , "1" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["id"][0] , "0" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def UpperCAmelCase_ ( self : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.get_dummy_custom_hf_index_retriever(from_disk=UpperCAmelCase__ ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = RagRetriever.from_pretrained(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) __SCREAMING_SNAKE_CASE = retriever.retrieve(UpperCAmelCase__ , n_docs=1 ) self.assertTrue(out is not None ) def UpperCAmelCase_ ( self : List[str] ) -> int: __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = self.get_dummy_legacy_index_retriever() __SCREAMING_SNAKE_CASE = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = retriever.retrieve(UpperCAmelCase__ , n_docs=UpperCAmelCase__ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(UpperCAmelCase__ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ["text", "title"] ) self.assertEqual(len(doc_dicts[0]["text"] ) , UpperCAmelCase__ ) self.assertEqual(doc_dicts[0]["text"][0] , "bar" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["text"][0] , "foo" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def UpperCAmelCase_ ( self : str ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.get_dummy_legacy_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = RagRetriever.from_pretrained(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) __SCREAMING_SNAKE_CASE = retriever.retrieve(UpperCAmelCase__ , n_docs=1 ) self.assertTrue(out is not None ) @require_torch @require_tokenizers @require_sentencepiece def UpperCAmelCase_ ( self : Dict ) -> int: import torch __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = self.get_dummy_canonical_hf_index_retriever() __SCREAMING_SNAKE_CASE = [[5, 7], [1_0, 1_1]] __SCREAMING_SNAKE_CASE = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) __SCREAMING_SNAKE_CASE = retriever(UpperCAmelCase__ , UpperCAmelCase__ , prefix=retriever.config.generator.prefix , n_docs=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = ( out["context_input_ids"], out["context_attention_mask"], out["retrieved_doc_embeds"], ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , np.ndarray ) __SCREAMING_SNAKE_CASE = retriever( UpperCAmelCase__ , UpperCAmelCase__ , prefix=retriever.config.generator.prefix , n_docs=UpperCAmelCase__ , return_tensors="pt" , ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = ( # noqa: F841 out["context_input_ids"], out["context_attention_mask"], out["retrieved_doc_embeds"], out["doc_ids"], ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertIsInstance(UpperCAmelCase__ , torch.Tensor ) self.assertIsInstance(UpperCAmelCase__ , torch.Tensor ) self.assertIsInstance(UpperCAmelCase__ , torch.Tensor ) @require_torch @require_tokenizers @require_sentencepiece def UpperCAmelCase_ ( self : str ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.get_dpr_ctx_encoder_tokenizer() __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = self.get_dummy_custom_hf_index_retriever(from_disk=UpperCAmelCase__ ) retriever.set_ctx_encoder_tokenizer(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [[5, 7], [1_0, 1_1]] __SCREAMING_SNAKE_CASE = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) __SCREAMING_SNAKE_CASE = retriever(UpperCAmelCase__ , UpperCAmelCase__ , prefix=retriever.config.generator.prefix , n_docs=UpperCAmelCase__ ) self.assertEqual( len(UpperCAmelCase__ ) , 6 ) # check whether the retriever output consist of 6 attributes including tokenized docs self.assertEqual( all(k in out for k in ("tokenized_doc_ids", "tokenized_doc_attention_mask") ) , UpperCAmelCase__ ) # check for doc token related keys in dictionary.
54
"""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__ : str = { '''configuration_roformer''': ['''ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''RoFormerConfig''', '''RoFormerOnnxConfig'''], '''tokenization_roformer''': ['''RoFormerTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = ['''RoFormerTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''RoFormerForCausalLM''', '''RoFormerForMaskedLM''', '''RoFormerForMultipleChoice''', '''RoFormerForQuestionAnswering''', '''RoFormerForSequenceClassification''', '''RoFormerForTokenClassification''', '''RoFormerLayer''', '''RoFormerModel''', '''RoFormerPreTrainedModel''', '''load_tf_weights_in_roformer''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = [ '''TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFRoFormerForCausalLM''', '''TFRoFormerForMaskedLM''', '''TFRoFormerForMultipleChoice''', '''TFRoFormerForQuestionAnswering''', '''TFRoFormerForSequenceClassification''', '''TFRoFormerForTokenClassification''', '''TFRoFormerLayer''', '''TFRoFormerModel''', '''TFRoFormerPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FlaxRoFormerForMaskedLM''', '''FlaxRoFormerForMultipleChoice''', '''FlaxRoFormerForQuestionAnswering''', '''FlaxRoFormerForSequenceClassification''', '''FlaxRoFormerForTokenClassification''', '''FlaxRoFormerModel''', '''FlaxRoFormerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys a__ : int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
54
1
"""simple docstring""" import gc import unittest from diffusers import FlaxDPMSolverMultistepScheduler, FlaxStableDiffusionPipeline from diffusers.utils import is_flax_available, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[int]: # clean up the VRAM after each test super().tearDown() gc.collect() def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( "stabilityai/stable-diffusion-2" , revision="bf16" , dtype=jnp.bfloataa , ) __SCREAMING_SNAKE_CASE = "A painting of a squirrel eating a burger" __SCREAMING_SNAKE_CASE = jax.device_count() __SCREAMING_SNAKE_CASE = num_samples * [prompt] __SCREAMING_SNAKE_CASE = sd_pipe.prepare_inputs(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = replicate(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = shard(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0 ) __SCREAMING_SNAKE_CASE = jax.random.split(UpperCAmelCase__ , jax.device_count() ) __SCREAMING_SNAKE_CASE = sd_pipe(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , num_inference_steps=2_5 , jit=UpperCAmelCase__ )[0] assert images.shape == (jax.device_count(), 1, 7_6_8, 7_6_8, 3) __SCREAMING_SNAKE_CASE = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) __SCREAMING_SNAKE_CASE = images[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] __SCREAMING_SNAKE_CASE = jnp.asarray(jax.device_get(image_slice.flatten() ) ) __SCREAMING_SNAKE_CASE = jnp.array([0.4_238, 0.4_414, 0.4_395, 0.4_453, 0.4_629, 0.4_590, 0.4_531, 0.45_508, 0.4_512] ) print(F"""output_slice: {output_slice}""" ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2 def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = "stabilityai/stable-diffusion-2" __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = FlaxDPMSolverMultistepScheduler.from_pretrained(UpperCAmelCase__ , subfolder="scheduler" ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( UpperCAmelCase__ , scheduler=UpperCAmelCase__ , revision="bf16" , dtype=jnp.bfloataa , ) __SCREAMING_SNAKE_CASE = scheduler_params __SCREAMING_SNAKE_CASE = "A painting of a squirrel eating a burger" __SCREAMING_SNAKE_CASE = jax.device_count() __SCREAMING_SNAKE_CASE = num_samples * [prompt] __SCREAMING_SNAKE_CASE = sd_pipe.prepare_inputs(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = replicate(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = shard(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0 ) __SCREAMING_SNAKE_CASE = jax.random.split(UpperCAmelCase__ , jax.device_count() ) __SCREAMING_SNAKE_CASE = sd_pipe(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , num_inference_steps=2_5 , jit=UpperCAmelCase__ )[0] assert images.shape == (jax.device_count(), 1, 7_6_8, 7_6_8, 3) __SCREAMING_SNAKE_CASE = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) __SCREAMING_SNAKE_CASE = images[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] __SCREAMING_SNAKE_CASE = jnp.asarray(jax.device_get(image_slice.flatten() ) ) __SCREAMING_SNAKE_CASE = jnp.array([0.4_336, 0.42_969, 0.4_453, 0.4_199, 0.4_297, 0.4_531, 0.4_434, 0.4_434, 0.4_297] ) print(F"""output_slice: {output_slice}""" ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2
54
"""simple docstring""" # Copyright 2022 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. import argparse import os import subprocess from packaging.version import Version, parse from accelerate.commands.config.config_args import default_config_file, load_config_from_file a__ : Tuple = '''Run commands across TPU VMs for initial setup before running `accelerate launch`.''' def UpperCAmelCase__ (lowerCAmelCase_=None ): '''simple docstring''' if subparsers is not None: __SCREAMING_SNAKE_CASE = subparsers.add_parser("tpu-config" , description=_description ) else: __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("Accelerate tpu-config command" , description=_description ) # Core arguments __SCREAMING_SNAKE_CASE = parser.add_argument_group( "Config Arguments" , "Arguments that can be configured through `accelerate config`." ) config_args.add_argument( "--config_file" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , help="Path to the config file to use for accelerate." , ) config_args.add_argument( "--tpu_name" , default=lowerCAmelCase_ , help="The name of the TPU to use. If not specified, will use the TPU specified in the config file." , ) config_args.add_argument( "--tpu_zone" , default=lowerCAmelCase_ , help="The zone of the TPU to use. If not specified, will use the zone specified in the config file." , ) __SCREAMING_SNAKE_CASE = parser.add_argument_group("TPU Arguments" , "Arguments for options ran inside the TPU." ) pod_args.add_argument( "--use_alpha" , action="store_true" , help="Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`." , ) pod_args.add_argument( "--command_file" , default=lowerCAmelCase_ , help="The path to the file containing the commands to run on the pod on startup." , ) pod_args.add_argument( "--command" , action="append" , nargs="+" , help="A command to run on the pod. Can be passed multiple times." , ) pod_args.add_argument( "--install_accelerate" , action="store_true" , help="Whether to install accelerate on the pod. Defaults to False." , ) pod_args.add_argument( "--accelerate_version" , default="latest" , help="The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify 'dev' to install from GitHub." , ) pod_args.add_argument( "--debug" , action="store_true" , help="If set, will print the command that would be run instead of running it." ) if subparsers is not None: parser.set_defaults(func=lowerCAmelCase_ ) return parser def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = None # Get the default from the config file if it exists. if args.config_file is not None or os.path.isfile(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = load_config_from_file(args.config_file ) if not args.command_file and defaults.command_file is not None and not args.command: __SCREAMING_SNAKE_CASE = defaults.command_file if not args.command and defaults.commands is not None: __SCREAMING_SNAKE_CASE = defaults.commands if not args.tpu_name: __SCREAMING_SNAKE_CASE = defaults.tpu_name if not args.tpu_zone: __SCREAMING_SNAKE_CASE = defaults.tpu_zone if args.accelerate_version == "dev": __SCREAMING_SNAKE_CASE = "git+https://github.com/huggingface/accelerate.git" elif args.accelerate_version == "latest": __SCREAMING_SNAKE_CASE = "accelerate -U" elif isinstance(parse(args.accelerate_version ) , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = f"""accelerate=={args.accelerate_version}""" if not args.command_file and not args.command: raise ValueError("You must specify either a command file or a command to run on the pod." ) if args.command_file: with open(args.command_file , "r" ) as f: __SCREAMING_SNAKE_CASE = [f.read().splitlines()] # To turn list of lists into list of strings if isinstance(args.command[0] , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = [line for cmd in args.command for line in cmd] # Default to the shared folder and install accelerate __SCREAMING_SNAKE_CASE = ["cd /usr/share"] if args.install_accelerate: new_cmd += [f"""pip install {args.accelerate_version}"""] new_cmd += args.command __SCREAMING_SNAKE_CASE = "; ".join(lowerCAmelCase_ ) # Then send it to gcloud # Eventually try to use google-api-core to do this instead of subprocess __SCREAMING_SNAKE_CASE = ["gcloud"] if args.use_alpha: cmd += ["alpha"] cmd += [ "compute", "tpus", "tpu-vm", "ssh", args.tpu_name, "--zone", args.tpu_zone, "--command", args.command, "--worker", "all", ] if args.debug: print(f"""Running {' '.join(lowerCAmelCase_ )}""" ) return subprocess.run(lowerCAmelCase_ ) print("Successfully setup pod." ) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = tpu_command_parser() __SCREAMING_SNAKE_CASE = parser.parse_args() tpu_command_launcher(lowerCAmelCase_ )
54
1
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import copy import importlib.metadata import json import os from dataclasses import dataclass from typing import Any, Dict, Union from packaging import version from ..utils import is_torch_available, logging if is_torch_available(): import torch a__ : Union[str, Any] = logging.get_logger(__name__) @dataclass class UpperCamelCase_ : """simple docstring""" def __init__( self : Union[str, Any] , UpperCAmelCase__ : Dict=False , UpperCAmelCase__ : List[Any]=False , UpperCAmelCase__ : List[Any]=6.0 , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : List[str]=False , UpperCAmelCase__ : Union[str, Any]=False , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : Union[str, Any]="fp4" , UpperCAmelCase__ : Optional[int]=False , **UpperCAmelCase__ : List[str] , ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = load_in_abit __SCREAMING_SNAKE_CASE = load_in_abit __SCREAMING_SNAKE_CASE = llm_inta_threshold __SCREAMING_SNAKE_CASE = llm_inta_skip_modules __SCREAMING_SNAKE_CASE = llm_inta_enable_fpaa_cpu_offload __SCREAMING_SNAKE_CASE = llm_inta_has_fpaa_weight __SCREAMING_SNAKE_CASE = bnb_abit_quant_type __SCREAMING_SNAKE_CASE = bnb_abit_use_double_quant if bnb_abit_compute_dtype is None: __SCREAMING_SNAKE_CASE = torch.floataa elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = getattr(UpperCAmelCase__ , UpperCAmelCase__ ) elif isinstance(UpperCAmelCase__ , torch.dtype ): __SCREAMING_SNAKE_CASE = bnb_abit_compute_dtype else: raise ValueError("bnb_4bit_compute_dtype must be a string or a torch.dtype" ) self.post_init() def UpperCAmelCase_ ( self : Optional[Any] ) -> List[Any]: if not isinstance(self.llm_inta_threshold , UpperCAmelCase__ ): raise ValueError("llm_int8_threshold must be a float" ) if self.llm_inta_skip_modules is not None and not isinstance(self.llm_inta_skip_modules , UpperCAmelCase__ ): raise ValueError("llm_int8_skip_modules must be a list of strings" ) if not isinstance(self.llm_inta_enable_fpaa_cpu_offload , UpperCAmelCase__ ): raise ValueError("llm_int8_enable_fp32_cpu_offload must be a boolean" ) if not isinstance(self.llm_inta_has_fpaa_weight , UpperCAmelCase__ ): raise ValueError("llm_int8_has_fp16_weight must be a boolean" ) if self.bnb_abit_compute_dtype is not None and not isinstance(self.bnb_abit_compute_dtype , torch.dtype ): raise ValueError("bnb_4bit_compute_dtype must be torch.dtype" ) if not isinstance(self.bnb_abit_quant_type , UpperCAmelCase__ ): raise ValueError("bnb_4bit_quant_type must be a string" ) if not isinstance(self.bnb_abit_use_double_quant , UpperCAmelCase__ ): raise ValueError("bnb_4bit_use_double_quant must be a boolean" ) if self.load_in_abit and not version.parse(importlib.metadata.version("bitsandbytes" ) ) >= version.parse( "0.39.0" ): raise ValueError( "4 bit quantization requires bitsandbytes>=0.39.0 - please upgrade your bitsandbytes version" ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Union[str, Any]: return self.load_in_abit or self.load_in_abit def UpperCAmelCase_ ( self : List[str] ) -> int: if self.load_in_abit: return "llm_int8" elif self.load_in_abit and self.bnb_abit_quant_type == "fp4": return "fp4" elif self.load_in_abit and self.bnb_abit_quant_type == "nf4": return "nf4" else: return None @classmethod def UpperCAmelCase_ ( cls : Dict , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[Any] , **UpperCAmelCase__ : List[Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = cls(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [] for key, value in kwargs.items(): if hasattr(UpperCAmelCase__ , UpperCAmelCase__ ): setattr(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) to_remove.append(UpperCAmelCase__ ) for key in to_remove: kwargs.pop(UpperCAmelCase__ , UpperCAmelCase__ ) if return_unused_kwargs: return config, kwargs else: return config def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Union[str, os.PathLike] ) -> List[Any]: with open(UpperCAmelCase__ , "w" , encoding="utf-8" ) as writer: __SCREAMING_SNAKE_CASE = self.to_dict() __SCREAMING_SNAKE_CASE = json.dumps(UpperCAmelCase__ , indent=2 , sort_keys=UpperCAmelCase__ ) + "\n" writer.write(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Dict[str, Any]: __SCREAMING_SNAKE_CASE = copy.deepcopy(self.__dict__ ) __SCREAMING_SNAKE_CASE = str(output["bnb_4bit_compute_dtype"] ).split("." )[1] return output def __repr__( self : Optional[int] ) -> List[Any]: return F"""{self.__class__.__name__} {self.to_json_string()}""" def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : bool = True ) -> str: if use_diff is True: __SCREAMING_SNAKE_CASE = self.to_diff_dict() else: __SCREAMING_SNAKE_CASE = self.to_dict() return json.dumps(UpperCAmelCase__ , indent=2 , sort_keys=UpperCAmelCase__ ) + "\n" def UpperCAmelCase_ ( self : Optional[Any] ) -> Dict[str, Any]: __SCREAMING_SNAKE_CASE = self.to_dict() # get the default config dict __SCREAMING_SNAKE_CASE = BitsAndBytesConfig().to_dict() __SCREAMING_SNAKE_CASE = {} # only serialize values that differ from the default config for key, value in config_dict.items(): if value != default_config_dict[key]: __SCREAMING_SNAKE_CASE = value return serializable_config_dict
54
"""simple docstring""" from abc import ABC, abstractmethod from argparse import ArgumentParser class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @staticmethod @abstractmethod def UpperCAmelCase_ ( UpperCAmelCase__ : ArgumentParser ) -> int: raise NotImplementedError() @abstractmethod def UpperCAmelCase_ ( self : int ) -> Optional[int]: raise NotImplementedError()
54
1
"""simple docstring""" from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = field(default="language-modeling" , metadata={"include_in_asdict_even_if_is_default": True}) snake_case__ : ClassVar[Features] = Features({"text": Value("string")}) snake_case__ : ClassVar[Features] = Features({}) snake_case__ : str = "text" @property def UpperCAmelCase_ ( self : str ) -> Dict[str, str]: return {self.text_column: "text"}
54
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def UpperCAmelCase__ (lowerCAmelCase_ = 100_0000 , lowerCAmelCase_ = 10 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = defaultdict(lowerCAmelCase_ ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: __SCREAMING_SNAKE_CASE = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: __SCREAMING_SNAKE_CASE = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(lowerCAmelCase_ , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 10 ) if __name__ == "__main__": print(F"{solution() = }")
54
1
"""simple docstring""" import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Optional[int] = ["image_processor", "tokenizer"] snake_case__ : Union[str, Any] = "OwlViTImageProcessor" snake_case__ : str = ("CLIPTokenizer", "CLIPTokenizerFast") def __init__( self : List[Any] , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : List[str]=None , **UpperCAmelCase__ : Tuple ) -> List[Any]: __SCREAMING_SNAKE_CASE = None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = kwargs.pop("feature_extractor" ) __SCREAMING_SNAKE_CASE = 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__(UpperCAmelCase__ , UpperCAmelCase__ ) def __call__( self : Dict , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : str=None , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : Optional[Any]="max_length" , UpperCAmelCase__ : Optional[Any]="np" , **UpperCAmelCase__ : Union[str, Any] ) -> Optional[int]: if text is None and query_images is None and images is None: raise ValueError( "You have to specify at least one text or query image or image. All three cannot be none." ) if text is not None: if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) or (isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) and not isinstance(text[0] , UpperCAmelCase__ )): __SCREAMING_SNAKE_CASE = [self.tokenizer(UpperCAmelCase__ , padding=UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__ )] elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) and isinstance(text[0] , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = [] # Maximum number of queries across batch __SCREAMING_SNAKE_CASE = max([len(UpperCAmelCase__ ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(UpperCAmelCase__ ) != max_num_queries: __SCREAMING_SNAKE_CASE = t + [" "] * (max_num_queries - len(UpperCAmelCase__ )) __SCREAMING_SNAKE_CASE = self.tokenizer(UpperCAmelCase__ , padding=UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__ ) encodings.append(UpperCAmelCase__ ) else: raise TypeError("Input text should be a string, a list of strings or a nested list of strings" ) if return_tensors == "np": __SCREAMING_SNAKE_CASE = np.concatenate([encoding["input_ids"] for encoding in encodings] , axis=0 ) __SCREAMING_SNAKE_CASE = np.concatenate([encoding["attention_mask"] for encoding in encodings] , axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp __SCREAMING_SNAKE_CASE = jnp.concatenate([encoding["input_ids"] for encoding in encodings] , axis=0 ) __SCREAMING_SNAKE_CASE = jnp.concatenate([encoding["attention_mask"] for encoding in encodings] , axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch __SCREAMING_SNAKE_CASE = torch.cat([encoding["input_ids"] for encoding in encodings] , dim=0 ) __SCREAMING_SNAKE_CASE = torch.cat([encoding["attention_mask"] for encoding in encodings] , dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf __SCREAMING_SNAKE_CASE = tf.stack([encoding["input_ids"] for encoding in encodings] , axis=0 ) __SCREAMING_SNAKE_CASE = tf.stack([encoding["attention_mask"] for encoding in encodings] , axis=0 ) else: raise ValueError("Target return tensor type could not be returned" ) __SCREAMING_SNAKE_CASE = BatchEncoding() __SCREAMING_SNAKE_CASE = input_ids __SCREAMING_SNAKE_CASE = attention_mask if query_images is not None: __SCREAMING_SNAKE_CASE = BatchEncoding() __SCREAMING_SNAKE_CASE = self.image_processor( UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__ ).pixel_values __SCREAMING_SNAKE_CASE = query_pixel_values if images is not None: __SCREAMING_SNAKE_CASE = self.image_processor(UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__ ) if text is not None and images is not None: __SCREAMING_SNAKE_CASE = image_features.pixel_values return encoding elif query_images is not None and images is not None: __SCREAMING_SNAKE_CASE = image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**UpperCAmelCase__ ) , tensor_type=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] , *UpperCAmelCase__ : Optional[Any] , **UpperCAmelCase__ : str ) -> List[str]: return self.image_processor.post_process(*UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , *UpperCAmelCase__ : Dict , **UpperCAmelCase__ : Optional[int] ) -> Tuple: return self.image_processor.post_process_object_detection(*UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str , *UpperCAmelCase__ : int , **UpperCAmelCase__ : Optional[int] ) -> List[Any]: return self.image_processor.post_process_image_guided_detection(*UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , *UpperCAmelCase__ : Any , **UpperCAmelCase__ : Optional[int] ) -> Optional[int]: return self.tokenizer.batch_decode(*UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Optional[int] ) -> Tuple: return self.tokenizer.decode(*UpperCAmelCase__ , **UpperCAmelCase__ ) @property def UpperCAmelCase_ ( self : Any ) -> str: warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , UpperCAmelCase__ , ) return self.image_processor_class @property def UpperCAmelCase_ ( self : List[str] ) -> str: warnings.warn( "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead." , UpperCAmelCase__ , ) return self.image_processor
54
"""simple docstring""" import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html a__ : List[str] = '''platform''' import jax import jax.numpy as jnp import numpy as np from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel @require_flax class UpperCamelCase_ : """simple docstring""" snake_case__ : Dict = PegasusConfig snake_case__ : Union[str, Any] = {} snake_case__ : Any = "gelu" def __init__( self : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int=1_3 , UpperCAmelCase__ : Optional[int]=7 , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : Any=False , UpperCAmelCase__ : List[Any]=9_9 , UpperCAmelCase__ : int=3_2 , UpperCAmelCase__ : Dict=5 , UpperCAmelCase__ : Optional[int]=4 , UpperCAmelCase__ : List[Any]=3_7 , UpperCAmelCase__ : int=0.1 , UpperCAmelCase__ : int=0.1 , UpperCAmelCase__ : List[Any]=2_0 , UpperCAmelCase__ : int=2 , UpperCAmelCase__ : List[Any]=1 , UpperCAmelCase__ : Optional[Any]=0 , ) -> Any: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = eos_token_id __SCREAMING_SNAKE_CASE = pad_token_id __SCREAMING_SNAKE_CASE = bos_token_id def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ).clip(3 , self.vocab_size ) __SCREAMING_SNAKE_CASE = np.expand_dims(np.array([self.eos_token_id] * self.batch_size ) , 1 ) __SCREAMING_SNAKE_CASE = np.concatenate([input_ids, eos_tensor] , axis=1 ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) __SCREAMING_SNAKE_CASE = prepare_pegasus_inputs_dict(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) return config, inputs_dict def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] ) -> str: __SCREAMING_SNAKE_CASE = 2_0 __SCREAMING_SNAKE_CASE = model_class_name(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.encode(inputs_dict["input_ids"] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) __SCREAMING_SNAKE_CASE = model.init_cache(decoder_input_ids.shape[0] , UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="i4" ) __SCREAMING_SNAKE_CASE = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, :-1] , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, -1:] , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , past_key_values=outputs_cache.past_key_values , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = 2_0 __SCREAMING_SNAKE_CASE = model_class_name(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.encode(inputs_dict["input_ids"] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) __SCREAMING_SNAKE_CASE = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) __SCREAMING_SNAKE_CASE = model.init_cache(decoder_input_ids.shape[0] , UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, :-1] , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, -1:] , UpperCAmelCase__ , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=UpperCAmelCase__ , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=None , lowerCAmelCase_=None , ): '''simple docstring''' if attention_mask is None: __SCREAMING_SNAKE_CASE = np.not_equal(lowerCAmelCase_ , config.pad_token_id ).astype(np.inta ) if decoder_attention_mask is None: __SCREAMING_SNAKE_CASE = np.concatenate( [ np.ones(decoder_input_ids[:, :1].shape , dtype=np.inta ), np.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ).astype(np.inta ), ] , axis=-1 , ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, } @require_flax class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Tuple = ( ( FlaxPegasusForConditionalGeneration, FlaxPegasusModel, ) if is_flax_available() else () ) snake_case__ : Union[str, Any] = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else () snake_case__ : Tuple = True snake_case__ : Union[str, Any] = False snake_case__ : int = False snake_case__ : List[Any] = False def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = FlaxPegasusModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : Tuple ) -> Optional[int]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Tuple: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __SCREAMING_SNAKE_CASE = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) @jax.jit def encode_jitted(UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : int=None , **UpperCAmelCase__ : int ): return model.encode(input_ids=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) with self.subTest("JIT Enabled" ): __SCREAMING_SNAKE_CASE = encode_jitted(**UpperCAmelCase__ ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): __SCREAMING_SNAKE_CASE = encode_jitted(**UpperCAmelCase__ ).to_tuple() self.assertEqual(len(UpperCAmelCase__ ) , len(UpperCAmelCase__ ) ) for jitted_output, output in zip(UpperCAmelCase__ , UpperCAmelCase__ ): self.assertEqual(jitted_output.shape , output.shape ) def UpperCAmelCase_ ( self : Tuple ) -> Any: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.encode(inputs_dict["input_ids"] , inputs_dict["attention_mask"] ) __SCREAMING_SNAKE_CASE = { "decoder_input_ids": inputs_dict["decoder_input_ids"], "decoder_attention_mask": inputs_dict["decoder_attention_mask"], "encoder_outputs": encoder_outputs, } @jax.jit def decode_jitted(UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] ): return model.decode( decoder_input_ids=UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , encoder_outputs=UpperCAmelCase__ , ) with self.subTest("JIT Enabled" ): __SCREAMING_SNAKE_CASE = decode_jitted(**UpperCAmelCase__ ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): __SCREAMING_SNAKE_CASE = decode_jitted(**UpperCAmelCase__ ).to_tuple() self.assertEqual(len(UpperCAmelCase__ ) , len(UpperCAmelCase__ ) ) for jitted_output, output in zip(UpperCAmelCase__ , UpperCAmelCase__ ): self.assertEqual(jitted_output.shape , output.shape ) @slow def UpperCAmelCase_ ( self : Dict ) -> Tuple: for model_class_name in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class_name.from_pretrained("google/pegasus-large" , from_pt=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.ones((1, 1) ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : Optional[int] ) -> List[Any]: __SCREAMING_SNAKE_CASE = FlaxPegasusForConditionalGeneration.from_pretrained("google/pegasus-xsum" ) __SCREAMING_SNAKE_CASE = PegasusTokenizer.from_pretrained("google/pegasus-xsum" ) __SCREAMING_SNAKE_CASE = [ " PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.", " The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" ", ] __SCREAMING_SNAKE_CASE = [ "California's largest electricity provider has turned off power to hundreds of thousands of customers.", "Pop group N-Dubz have revealed they were surprised to get four nominations for this year's Mobo Awards.", ] __SCREAMING_SNAKE_CASE = tokenizer(UpperCAmelCase__ , return_tensors="np" , truncation=UpperCAmelCase__ , max_length=5_1_2 , padding=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate(**UpperCAmelCase__ , num_beams=2 ).sequences __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ ) assert tgt_text == decoded
54
1
"""simple docstring""" from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, flip_channel_order, get_resize_output_image_size, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_torch_tensor, is_vision_available, logging if is_vision_available(): import PIL if is_torch_available(): import torch a__ : List[str] = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Union[str, Any] = ["pixel_values"] def __init__( self : Tuple , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Dict[str, int] = None , UpperCAmelCase__ : PILImageResampling = PILImageResampling.BILINEAR , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Union[int, float] = 1 / 2_5_5 , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Dict[str, int] = None , UpperCAmelCase__ : bool = True , **UpperCAmelCase__ : int , ) -> None: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = size if size is not None else {"shortest_edge": 2_2_4} __SCREAMING_SNAKE_CASE = get_size_dict(UpperCAmelCase__ , default_to_square=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = crop_size if crop_size is not None else {"height": 2_5_6, "width": 2_5_6} __SCREAMING_SNAKE_CASE = get_size_dict(UpperCAmelCase__ , param_name="crop_size" ) __SCREAMING_SNAKE_CASE = do_resize __SCREAMING_SNAKE_CASE = size __SCREAMING_SNAKE_CASE = resample __SCREAMING_SNAKE_CASE = do_rescale __SCREAMING_SNAKE_CASE = rescale_factor __SCREAMING_SNAKE_CASE = do_center_crop __SCREAMING_SNAKE_CASE = crop_size __SCREAMING_SNAKE_CASE = do_flip_channel_order def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : Dict[str, int] , UpperCAmelCase__ : PILImageResampling = PIL.Image.BILINEAR , UpperCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase__ : str , ) -> np.ndarray: __SCREAMING_SNAKE_CASE = get_size_dict(UpperCAmelCase__ , default_to_square=UpperCAmelCase__ ) if "shortest_edge" not in size: raise ValueError(F"""The `size` dictionary must contain the key `shortest_edge`. Got {size.keys()}""" ) __SCREAMING_SNAKE_CASE = get_resize_output_image_size(UpperCAmelCase__ , size=size["shortest_edge"] , default_to_square=UpperCAmelCase__ ) return resize(UpperCAmelCase__ , size=UpperCAmelCase__ , resample=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : Dict[str, int] , UpperCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase__ : Tuple , ) -> np.ndarray: __SCREAMING_SNAKE_CASE = get_size_dict(UpperCAmelCase__ ) if "height" not in size or "width" not in size: raise ValueError(F"""The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}""" ) return center_crop(UpperCAmelCase__ , size=(size["height"], size["width"]) , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : Union[int, float] , UpperCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase__ : Optional[int] , ) -> Dict: return rescale(UpperCAmelCase__ , scale=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : Optional[Union[str, ChannelDimension]] = None ) -> np.ndarray: return flip_channel_order(UpperCAmelCase__ , data_format=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : ImageInput , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : Dict[str, int] = None , UpperCAmelCase__ : PILImageResampling = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : float = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : Dict[str, int] = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : Optional[Union[str, TensorType]] = None , UpperCAmelCase__ : ChannelDimension = ChannelDimension.FIRST , **UpperCAmelCase__ : Union[str, Any] , ) -> PIL.Image.Image: __SCREAMING_SNAKE_CASE = do_resize if do_resize is not None else self.do_resize __SCREAMING_SNAKE_CASE = resample if resample is not None else self.resample __SCREAMING_SNAKE_CASE = do_rescale if do_rescale is not None else self.do_rescale __SCREAMING_SNAKE_CASE = rescale_factor if rescale_factor is not None else self.rescale_factor __SCREAMING_SNAKE_CASE = do_center_crop if do_center_crop is not None else self.do_center_crop __SCREAMING_SNAKE_CASE = ( do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order ) __SCREAMING_SNAKE_CASE = size if size is not None else self.size __SCREAMING_SNAKE_CASE = get_size_dict(UpperCAmelCase__ , default_to_square=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = crop_size if crop_size is not None else self.crop_size __SCREAMING_SNAKE_CASE = get_size_dict(UpperCAmelCase__ , param_name="crop_size" ) __SCREAMING_SNAKE_CASE = make_list_of_images(UpperCAmelCase__ ) if not valid_images(UpperCAmelCase__ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) # All transformations expect numpy arrays. __SCREAMING_SNAKE_CASE = [to_numpy_array(UpperCAmelCase__ ) for image in images] if do_resize: __SCREAMING_SNAKE_CASE = [self.resize(image=UpperCAmelCase__ , size=UpperCAmelCase__ , resample=UpperCAmelCase__ ) for image in images] if do_center_crop: __SCREAMING_SNAKE_CASE = [self.center_crop(image=UpperCAmelCase__ , size=UpperCAmelCase__ ) for image in images] if do_rescale: __SCREAMING_SNAKE_CASE = [self.rescale(image=UpperCAmelCase__ , scale=UpperCAmelCase__ ) for image in images] # the pretrained checkpoints assume images are BGR, not RGB if do_flip_channel_order: __SCREAMING_SNAKE_CASE = [self.flip_channel_order(image=UpperCAmelCase__ ) for image in images] __SCREAMING_SNAKE_CASE = [to_channel_dimension_format(UpperCAmelCase__ , UpperCAmelCase__ ) for image in images] __SCREAMING_SNAKE_CASE = {"pixel_values": images} return BatchFeature(data=UpperCAmelCase__ , tensor_type=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Tuple] = None ) -> List[str]: __SCREAMING_SNAKE_CASE = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(UpperCAmelCase__ ) != len(UpperCAmelCase__ ): raise ValueError( "Make sure that you pass in as many target sizes as the batch dimension of the logits" ) if is_torch_tensor(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = target_sizes.numpy() __SCREAMING_SNAKE_CASE = [] for idx in range(len(UpperCAmelCase__ ) ): __SCREAMING_SNAKE_CASE = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="bilinear" , align_corners=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(UpperCAmelCase__ ) else: __SCREAMING_SNAKE_CASE = logits.argmax(dim=1 ) __SCREAMING_SNAKE_CASE = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
54
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ = 100_0000 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = set(range(3 , lowerCAmelCase_ , 2 ) ) primes.add(2 ) for p in range(3 , lowerCAmelCase_ , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , lowerCAmelCase_ , lowerCAmelCase_ ) ) ) __SCREAMING_SNAKE_CASE = [float(lowerCAmelCase_ ) for n in range(limit + 1 )] for p in primes: for n in range(lowerCAmelCase_ , limit + 1 , lowerCAmelCase_ ): phi[n] *= 1 - 1 / p return int(sum(phi[2:] ) ) if __name__ == "__main__": print(F"{solution() = }")
54
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__ : int = logging.get_logger(__name__) a__ : str = { '''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 UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = "deit" def __init__( self : List[Any] , UpperCAmelCase__ : str=7_6_8 , UpperCAmelCase__ : Union[str, Any]=1_2 , UpperCAmelCase__ : Any=1_2 , UpperCAmelCase__ : Dict=3_0_7_2 , UpperCAmelCase__ : Union[str, Any]="gelu" , UpperCAmelCase__ : Optional[int]=0.0 , UpperCAmelCase__ : Optional[Any]=0.0 , UpperCAmelCase__ : List[str]=0.02 , UpperCAmelCase__ : str=1E-12 , UpperCAmelCase__ : Any=2_2_4 , UpperCAmelCase__ : Tuple=1_6 , UpperCAmelCase__ : int=3 , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Any=1_6 , **UpperCAmelCase__ : str , ) -> Union[str, Any]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = qkv_bias __SCREAMING_SNAKE_CASE = encoder_stride class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = version.parse("1.11") @property def UpperCAmelCase_ ( self : Dict ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def UpperCAmelCase_ ( self : str ) -> float: return 1E-4
54
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if upper_limit < 0: raise ValueError("Limit for the Catalan sequence must be ≥ 0" ) __SCREAMING_SNAKE_CASE = [0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 __SCREAMING_SNAKE_CASE = 1 if upper_limit > 0: __SCREAMING_SNAKE_CASE = 1 # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i for i in range(2 , upper_limit + 1 ): for j in range(lowerCAmelCase_ ): catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1] return catalan_list if __name__ == "__main__": print('''\n********* Catalan Numbers Using Dynamic Programming ************\n''') print('''\n*** Enter -1 at any time to quit ***''') print('''\nEnter the upper limit (≥ 0) for the Catalan number sequence: ''', end='''''') try: while True: a__ : List[str] = int(input().strip()) if N < 0: print('''\n********* Goodbye!! ************''') break else: print(F"The Catalan numbers from 0 through {N} are:") print(catalan_numbers(N)) print('''Try another upper limit for the sequence: ''', end='''''') except (NameError, ValueError): print('''\n********* Invalid input, goodbye! ************\n''') import doctest doctest.testmod()
54
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 UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = filter(lambda lowerCAmelCase_ : p.requires_grad , model.parameters() ) __SCREAMING_SNAKE_CASE = sum([np.prod(p.size() ) for p in model_parameters] ) return params a__ : List[Any] = logging.getLogger(__name__) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if metric == "rouge2": __SCREAMING_SNAKE_CASE = "{val_avg_rouge2:.4f}-{step_count}" elif metric == "bleu": __SCREAMING_SNAKE_CASE = "{val_avg_bleu:.4f}-{step_count}" elif metric == "em": __SCREAMING_SNAKE_CASE = "{val_avg_em:.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." ) __SCREAMING_SNAKE_CASE = ModelCheckpoint( dirpath=lowerCAmelCase_ , filename=lowerCAmelCase_ , monitor=f"""val_{metric}""" , mode="max" , save_top_k=3 , every_n_epochs=1 , ) return checkpoint_callback def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' return EarlyStopping( monitor=f"""val_{metric}""" , mode="min" if "loss" in metric else "max" , patience=lowerCAmelCase_ , verbose=lowerCAmelCase_ , ) class UpperCamelCase_ ( pl.Callback): """simple docstring""" def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : str ) -> Any: __SCREAMING_SNAKE_CASE = {F"""lr_group_{i}""": param["lr"] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(UpperCAmelCase__ ) @rank_zero_only def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : pl.Trainer , UpperCAmelCase__ : pl.LightningModule , UpperCAmelCase__ : str , UpperCAmelCase__ : List[str]=True ) -> None: logger.info(F"""***** {type_path} results at step {trainer.global_step:05d} *****""" ) __SCREAMING_SNAKE_CASE = 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 __SCREAMING_SNAKE_CASE = Path(pl_module.hparams.output_dir ) if type_path == "test": __SCREAMING_SNAKE_CASE = od / "test_results.txt" __SCREAMING_SNAKE_CASE = 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. __SCREAMING_SNAKE_CASE = od / F"""{type_path}_results/{trainer.global_step:05d}.txt""" __SCREAMING_SNAKE_CASE = od / F"""{type_path}_generations/{trainer.global_step:05d}.txt""" results_file.parent.mkdir(exist_ok=UpperCAmelCase__ ) generations_file.parent.mkdir(exist_ok=UpperCAmelCase__ ) with open(UpperCAmelCase__ , "a+" ) as writer: for key in sorted(UpperCAmelCase__ ): if key in ["log", "progress_bar", "preds"]: continue __SCREAMING_SNAKE_CASE = metrics[key] if isinstance(UpperCAmelCase__ , torch.Tensor ): __SCREAMING_SNAKE_CASE = val.item() __SCREAMING_SNAKE_CASE = F"""{key}: {val:.6f}\n""" writer.write(UpperCAmelCase__ ) if not save_generations: return if "preds" in metrics: __SCREAMING_SNAKE_CASE = "\n".join(metrics["preds"] ) generations_file.open("w+" ).write(UpperCAmelCase__ ) @rank_zero_only def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : str ) -> List[Any]: try: __SCREAMING_SNAKE_CASE = pl_module.model.model.num_parameters() except AttributeError: __SCREAMING_SNAKE_CASE = pl_module.model.num_parameters() __SCREAMING_SNAKE_CASE = count_trainable_parameters(UpperCAmelCase__ ) # 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 UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : pl.Trainer , UpperCAmelCase__ : pl.LightningModule ) -> str: save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(UpperCAmelCase__ , UpperCAmelCase__ , "test" ) @rank_zero_only def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : pl.Trainer , UpperCAmelCase__ : Optional[int] ) -> Dict: save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
54
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from itertools import chain from typing import Optional, Union import datasets import numpy as np import torch from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.tokenization_utils_base import PreTrainedTokenizerBase from transformers.trainer_utils import get_last_checkpoint from transformers.utils import PaddingStrategy, check_min_version, send_example_telemetry # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('''4.31.0''') a__ : Tuple = logging.getLogger(__name__) @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Pretrained config name or path if not the same as model_name"}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} , ) snake_case__ : str = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : Optional[str] = field(default=UpperCamelCase , metadata={"help": "The input training data file (a text file)."}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."} , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={"help": "Overwrite the cached training and evaluation sets"}) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={"help": "The number of processes to use for the preprocessing."} , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "The maximum total input sequence length after tokenization. If passed, sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={ "help": ( "Whether to pad all samples to the maximum sentence length. " "If False, will pad the samples dynamically when batching to the maximum length in the batch. More " "efficient on GPU but very bad for TPU." ) } , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: if self.train_file is not None: __SCREAMING_SNAKE_CASE = self.train_file.split("." )[-1] assert extension in ["csv", "json"], "`train_file` should be a csv or a json file." if self.validation_file is not None: __SCREAMING_SNAKE_CASE = self.validation_file.split("." )[-1] assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file." @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : PreTrainedTokenizerBase snake_case__ : Union[bool, str, PaddingStrategy] = True snake_case__ : Optional[int] = None snake_case__ : Optional[int] = None def __call__( self : int , UpperCAmelCase__ : Any ) -> str: __SCREAMING_SNAKE_CASE = "label" if "label" in features[0].keys() else "labels" __SCREAMING_SNAKE_CASE = [feature.pop(UpperCAmelCase__ ) for feature in features] __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = len(features[0]["input_ids"] ) __SCREAMING_SNAKE_CASE = [ [{k: v[i] for k, v in feature.items()} for i in range(UpperCAmelCase__ )] for feature in features ] __SCREAMING_SNAKE_CASE = list(chain(*UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = self.tokenizer.pad( UpperCAmelCase__ , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="pt" , ) # Un-flatten __SCREAMING_SNAKE_CASE = {k: v.view(UpperCAmelCase__ , UpperCAmelCase__ , -1 ) for k, v in batch.items()} # Add back labels __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ , dtype=torch.intaa ) return batch def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("run_swag" , lowerCAmelCase_ , lowerCAmelCase_ ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() __SCREAMING_SNAKE_CASE = training_args.get_process_log_level() logger.setLevel(lowerCAmelCase_ ) datasets.utils.logging.set_verbosity(lowerCAmelCase_ ) transformers.utils.logging.set_verbosity(lowerCAmelCase_ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + f"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(f"""Training/evaluation parameters {training_args}""" ) # Detecting last checkpoint. __SCREAMING_SNAKE_CASE = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: __SCREAMING_SNAKE_CASE = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. """ "Use --overwrite_output_dir to overcome." ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.train_file is not None or data_args.validation_file is not None: __SCREAMING_SNAKE_CASE = {} if data_args.train_file is not None: __SCREAMING_SNAKE_CASE = data_args.train_file if data_args.validation_file is not None: __SCREAMING_SNAKE_CASE = data_args.validation_file __SCREAMING_SNAKE_CASE = data_args.train_file.split("." )[-1] __SCREAMING_SNAKE_CASE = load_dataset( lowerCAmelCase_ , data_files=lowerCAmelCase_ , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) else: # Downloading and loading the swag dataset from the hub. __SCREAMING_SNAKE_CASE = load_dataset( "swag" , "regular" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) __SCREAMING_SNAKE_CASE = 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_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) __SCREAMING_SNAKE_CASE = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # When using your own dataset or a different dataset from swag, you will probably need to change this. __SCREAMING_SNAKE_CASE = [f"""ending{i}""" for i in range(4 )] __SCREAMING_SNAKE_CASE = "sent1" __SCREAMING_SNAKE_CASE = "sent2" if data_args.max_seq_length is None: __SCREAMING_SNAKE_CASE = tokenizer.model_max_length if max_seq_length > 1024: logger.warning( "The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value" " of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can" " override this default with `--block_size xxx`." ) __SCREAMING_SNAKE_CASE = 1024 else: if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( f"""The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the""" f"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.""" ) __SCREAMING_SNAKE_CASE = min(data_args.max_seq_length , tokenizer.model_max_length ) # Preprocessing the datasets. def preprocess_function(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = [[context] * 4 for context in examples[context_name]] __SCREAMING_SNAKE_CASE = examples[question_header_name] __SCREAMING_SNAKE_CASE = [ [f"""{header} {examples[end][i]}""" for end in ending_names] for i, header in enumerate(lowerCAmelCase_ ) ] # Flatten out __SCREAMING_SNAKE_CASE = list(chain(*lowerCAmelCase_ ) ) __SCREAMING_SNAKE_CASE = list(chain(*lowerCAmelCase_ ) ) # Tokenize __SCREAMING_SNAKE_CASE = tokenizer( lowerCAmelCase_ , lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=lowerCAmelCase_ , padding="max_length" if data_args.pad_to_max_length else False , ) # Un-flatten return {k: [v[i : i + 4] for i in range(0 , len(lowerCAmelCase_ ) , 4 )] for k, v in tokenized_examples.items()} if training_args.do_train: if "train" not in raw_datasets: raise ValueError("--do_train requires a train dataset" ) __SCREAMING_SNAKE_CASE = raw_datasets["train"] if data_args.max_train_samples is not None: __SCREAMING_SNAKE_CASE = min(len(lowerCAmelCase_ ) , data_args.max_train_samples ) __SCREAMING_SNAKE_CASE = train_dataset.select(range(lowerCAmelCase_ ) ) with training_args.main_process_first(desc="train dataset map pre-processing" ): __SCREAMING_SNAKE_CASE = train_dataset.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , ) if training_args.do_eval: if "validation" not in raw_datasets: raise ValueError("--do_eval requires a validation dataset" ) __SCREAMING_SNAKE_CASE = raw_datasets["validation"] if data_args.max_eval_samples is not None: __SCREAMING_SNAKE_CASE = min(len(lowerCAmelCase_ ) , data_args.max_eval_samples ) __SCREAMING_SNAKE_CASE = eval_dataset.select(range(lowerCAmelCase_ ) ) with training_args.main_process_first(desc="validation dataset map pre-processing" ): __SCREAMING_SNAKE_CASE = eval_dataset.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , ) # Data collator __SCREAMING_SNAKE_CASE = ( default_data_collator if data_args.pad_to_max_length else DataCollatorForMultipleChoice(tokenizer=lowerCAmelCase_ , pad_to_multiple_of=8 if training_args.fpaa else None ) ) # Metric def compute_metrics(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = eval_predictions __SCREAMING_SNAKE_CASE = np.argmax(lowerCAmelCase_ , axis=1 ) return {"accuracy": (preds == label_ids).astype(np.floataa ).mean().item()} # Initialize our Trainer __SCREAMING_SNAKE_CASE = Trainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , tokenizer=lowerCAmelCase_ , data_collator=lowerCAmelCase_ , compute_metrics=lowerCAmelCase_ , ) # Training if training_args.do_train: __SCREAMING_SNAKE_CASE = None if training_args.resume_from_checkpoint is not None: __SCREAMING_SNAKE_CASE = training_args.resume_from_checkpoint elif last_checkpoint is not None: __SCREAMING_SNAKE_CASE = last_checkpoint __SCREAMING_SNAKE_CASE = trainer.train(resume_from_checkpoint=lowerCAmelCase_ ) trainer.save_model() # Saves the tokenizer too for easy upload __SCREAMING_SNAKE_CASE = train_result.metrics __SCREAMING_SNAKE_CASE = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(lowerCAmelCase_ ) ) __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ , len(lowerCAmelCase_ ) ) trainer.log_metrics("train" , lowerCAmelCase_ ) trainer.save_metrics("train" , lowerCAmelCase_ ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("*** Evaluate ***" ) __SCREAMING_SNAKE_CASE = trainer.evaluate() __SCREAMING_SNAKE_CASE = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ , len(lowerCAmelCase_ ) ) trainer.log_metrics("eval" , lowerCAmelCase_ ) trainer.save_metrics("eval" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { "finetuned_from": model_args.model_name_or_path, "tasks": "multiple-choice", "dataset_tags": "swag", "dataset_args": "regular", "dataset": "SWAG", "language": "en", } if training_args.push_to_hub: trainer.push_to_hub(**lowerCAmelCase_ ) else: trainer.create_model_card(**lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' main() if __name__ == "__main__": main()
54
1
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ = 10 ): '''simple docstring''' if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) or n < 0: raise ValueError("Invalid input" ) __SCREAMING_SNAKE_CASE = 10**n __SCREAMING_SNAKE_CASE = 2_8433 * (pow(2 , 783_0457 , lowerCAmelCase_ )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(F"{solution(1_0) = }")
54
"""simple docstring""" from PIL import Image def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = image.size __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = image.load() for i in range(lowerCAmelCase_ ): for j in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = pixels[j, i] mean += pixel mean //= width * height for j in range(lowerCAmelCase_ ): for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = 255 if pixels[i, j] > mean else 0 return image if __name__ == "__main__": a__ : List[str] = mean_threshold(Image.open('''path_to_image''').convert('''L''')) image.save('''output_image_path''')
54
1
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if graph[path[curr_ind - 1]][next_ver] == 0: return False # 2. Validate that next vertex is not already in path return not any(vertex == next_ver for vertex in path ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if curr_ind == len(lowerCAmelCase_ ): # return whether path exists between current and starting vertices return graph[path[curr_ind - 1]][path[0]] == 1 # Recursive Step for next_ver in range(0 , len(lowerCAmelCase_ ) ): if valid_connection(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): # Insert current vertex into path as next transition __SCREAMING_SNAKE_CASE = next_ver # Validate created path if util_hamilton_cycle(lowerCAmelCase_ , lowerCAmelCase_ , curr_ind + 1 ): return True # Backtrack __SCREAMING_SNAKE_CASE = -1 return False def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = 0 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [-1] * (len(lowerCAmelCase_ ) + 1) # initialize start and end of path with starting index __SCREAMING_SNAKE_CASE = __SCREAMING_SNAKE_CASE = start_index # evaluate and if we find answer return path either return empty array return path if util_hamilton_cycle(lowerCAmelCase_ , lowerCAmelCase_ , 1 ) else []
54
"""simple docstring""" from jiwer import compute_measures import datasets a__ : Optional[int] = '''\ @inproceedings{inproceedings, author = {Morris, Andrew and Maier, Viktoria and Green, Phil}, year = {2004}, month = {01}, pages = {}, title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.} } ''' a__ : List[str] = '''\ Word error rate (WER) is a common metric of the performance of an automatic speech recognition system. The general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort. This problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate. Word error rate can then be computed as: WER = (S + D + I) / N = (S + D + I) / (S + D + C) where S is the number of substitutions, D is the number of deletions, I is the number of insertions, C is the number of correct words, N is the number of words in the reference (N=S+D+C). This value indicates the average number of errors per reference word. The lower the value, the better the performance of the ASR system with a WER of 0 being a perfect score. ''' a__ : Dict = ''' Compute WER score of transcribed segments against references. Args: references: List of references for each speech input. predictions: List of transcriptions to score. concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively. Returns: (float): the word error rate Examples: >>> predictions = ["this is the prediction", "there is an other sample"] >>> references = ["this is the reference", "there is another one"] >>> wer = datasets.load_metric("wer") >>> wer_score = wer.compute(predictions=predictions, references=references) >>> print(wer_score) 0.5 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class UpperCamelCase_ ( datasets.Metric): """simple docstring""" def UpperCAmelCase_ ( self : List[Any] ) -> str: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , codebase_urls=["https://github.com/jitsi/jiwer/"] , reference_urls=[ "https://en.wikipedia.org/wiki/Word_error_rate", ] , ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : Any=False ) -> Optional[int]: if concatenate_texts: return compute_measures(UpperCAmelCase__ , UpperCAmelCase__ )["wer"] else: __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for prediction, reference in zip(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = compute_measures(UpperCAmelCase__ , UpperCAmelCase__ ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
54
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_mobilebert import MobileBertTokenizer a__ : int = logging.get_logger(__name__) a__ : Optional[int] = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} a__ : List[Any] = { '''vocab_file''': {'''mobilebert-uncased''': '''https://huggingface.co/google/mobilebert-uncased/resolve/main/vocab.txt'''}, '''tokenizer_file''': { '''mobilebert-uncased''': '''https://huggingface.co/google/mobilebert-uncased/resolve/main/tokenizer.json''' }, } a__ : Optional[Any] = {'''mobilebert-uncased''': 5_1_2} a__ : Any = {} class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Tuple = VOCAB_FILES_NAMES snake_case__ : str = PRETRAINED_VOCAB_FILES_MAP snake_case__ : Optional[Any] = PRETRAINED_INIT_CONFIGURATION snake_case__ : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ : Dict = MobileBertTokenizer def __init__( self : Tuple , UpperCAmelCase__ : int=None , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : List[Any]="[UNK]" , UpperCAmelCase__ : List[Any]="[SEP]" , UpperCAmelCase__ : Optional[Any]="[PAD]" , UpperCAmelCase__ : Tuple="[CLS]" , UpperCAmelCase__ : Tuple="[MASK]" , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Dict=None , **UpperCAmelCase__ : List[str] , ) -> Tuple: super().__init__( UpperCAmelCase__ , tokenizer_file=UpperCAmelCase__ , do_lower_case=UpperCAmelCase__ , unk_token=UpperCAmelCase__ , sep_token=UpperCAmelCase__ , pad_token=UpperCAmelCase__ , cls_token=UpperCAmelCase__ , mask_token=UpperCAmelCase__ , tokenize_chinese_chars=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ , **UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("lowercase" , UpperCAmelCase__ ) != do_lower_case or normalizer_state.get("strip_accents" , UpperCAmelCase__ ) != strip_accents or normalizer_state.get("handle_chinese_chars" , UpperCAmelCase__ ) != tokenize_chinese_chars ): __SCREAMING_SNAKE_CASE = getattr(UpperCAmelCase__ , normalizer_state.pop("type" ) ) __SCREAMING_SNAKE_CASE = do_lower_case __SCREAMING_SNAKE_CASE = strip_accents __SCREAMING_SNAKE_CASE = tokenize_chinese_chars __SCREAMING_SNAKE_CASE = normalizer_class(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = do_lower_case def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Tuple=None ) -> List[Any]: __SCREAMING_SNAKE_CASE = [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 UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ) -> List[int]: __SCREAMING_SNAKE_CASE = [self.sep_token_id] __SCREAMING_SNAKE_CASE = [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 UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[str] = None ) -> Tuple[str]: __SCREAMING_SNAKE_CASE = self._tokenizer.model.save(UpperCAmelCase__ , name=UpperCAmelCase__ ) return tuple(UpperCAmelCase__ )
54
"""simple docstring""" from __future__ import annotations import pandas as pd def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [0] * no_of_processes __SCREAMING_SNAKE_CASE = [0] * no_of_processes # Copy the burst time into remaining_time[] for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = burst_time[i] __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 9_9999_9999 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = False # Process until all processes are completed while complete != no_of_processes: for j in range(lowerCAmelCase_ ): if arrival_time[j] <= increment_time and remaining_time[j] > 0: if remaining_time[j] < minm: __SCREAMING_SNAKE_CASE = remaining_time[j] __SCREAMING_SNAKE_CASE = j __SCREAMING_SNAKE_CASE = True if not check: increment_time += 1 continue remaining_time[short] -= 1 __SCREAMING_SNAKE_CASE = remaining_time[short] if minm == 0: __SCREAMING_SNAKE_CASE = 9_9999_9999 if remaining_time[short] == 0: complete += 1 __SCREAMING_SNAKE_CASE = False # Find finish time of current process __SCREAMING_SNAKE_CASE = increment_time + 1 # Calculate waiting time __SCREAMING_SNAKE_CASE = finish_time - arrival_time[short] __SCREAMING_SNAKE_CASE = finar - burst_time[short] if waiting_time[short] < 0: __SCREAMING_SNAKE_CASE = 0 # Increment time increment_time += 1 return waiting_time def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [0] * no_of_processes for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = burst_time[i] + waiting_time[i] return turn_around_time def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = total_waiting_time + waiting_time[i] __SCREAMING_SNAKE_CASE = total_turn_around_time + turn_around_time[i] print(f"""Average waiting time = {total_waiting_time / no_of_processes:.5f}""" ) print("Average turn around time =" , total_turn_around_time / no_of_processes ) if __name__ == "__main__": print('''Enter how many process you want to analyze''') a__ : Optional[Any] = int(input()) a__ : Optional[int] = [0] * no_of_processes a__ : int = [0] * no_of_processes a__ : List[Any] = list(range(1, no_of_processes + 1)) for i in range(no_of_processes): print('''Enter the arrival time and burst time for process:--''' + str(i + 1)) a__ , a__ : Tuple = map(int, input().split()) a__ : int = calculate_waitingtime(arrival_time, burst_time, no_of_processes) a__ : Dict = burst_time a__ : Any = no_of_processes a__ : Optional[int] = waiting_time a__ : Union[str, Any] = calculate_turnaroundtime(bt, n, wt) calculate_average_times(waiting_time, turn_around_time, no_of_processes) a__ : str = pd.DataFrame( list(zip(processes, burst_time, arrival_time, waiting_time, turn_around_time)), columns=[ '''Process''', '''BurstTime''', '''ArrivalTime''', '''WaitingTime''', '''TurnAroundTime''', ], ) # Printing the dataFrame pd.set_option('''display.max_rows''', fcfs.shape[0] + 1) print(fcfs)
54
1
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from argparse import ArgumentParser from accelerate.commands.config import get_config_parser from accelerate.commands.env import env_command_parser from accelerate.commands.launch import launch_command_parser from accelerate.commands.test import test_command_parser from accelerate.commands.tpu import tpu_command_parser def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = ArgumentParser("Accelerate CLI tool" , usage="accelerate <command> [<args>]" , allow_abbrev=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = parser.add_subparsers(help="accelerate command helpers" ) # Register commands get_config_parser(subparsers=lowerCAmelCase_ ) env_command_parser(subparsers=lowerCAmelCase_ ) launch_command_parser(subparsers=lowerCAmelCase_ ) tpu_command_parser(subparsers=lowerCAmelCase_ ) test_command_parser(subparsers=lowerCAmelCase_ ) # Let's go __SCREAMING_SNAKE_CASE = parser.parse_args() if not hasattr(lowerCAmelCase_ , "func" ): parser.print_help() exit(1 ) # Run args.func(lowerCAmelCase_ ) if __name__ == "__main__": main()
54
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy a__ : Union[str, Any] = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : float , **UpperCAmelCase__ : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = feature_size __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = padding_value __SCREAMING_SNAKE_CASE = kwargs.pop("padding_side" , "right" ) __SCREAMING_SNAKE_CASE = kwargs.pop("return_attention_mask" , UpperCAmelCase__ ) super().__init__(**UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[ BatchFeature, List[BatchFeature], Dict[str, BatchFeature], Dict[str, List[BatchFeature]], List[Dict[str, BatchFeature]], ] , UpperCAmelCase__ : Union[bool, str, PaddingStrategy] = True , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[Union[str, TensorType]] = None , ) -> BatchFeature: # If we have a list of dicts, let's convert it in a dict of lists # We do this to allow using this method as a collate_fn function in PyTorch Dataloader if isinstance(UpperCAmelCase__ , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): __SCREAMING_SNAKE_CASE = { key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( "You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`" F""" to this method that includes {self.model_input_names[0]}, but you provided""" F""" {list(processed_features.keys() )}""" ) __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] __SCREAMING_SNAKE_CASE = ( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(UpperCAmelCase__ ) == 0: if return_attention_mask: __SCREAMING_SNAKE_CASE = [] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch __SCREAMING_SNAKE_CASE = required_input[0] if isinstance(UpperCAmelCase__ , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. __SCREAMING_SNAKE_CASE = 0 while len(required_input[index] ) == 0: index += 1 if index < len(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = required_input[index][0] if return_tensors is None: if is_tf_tensor(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = "tf" elif is_torch_tensor(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = "pt" elif isinstance(UpperCAmelCase__ , (int, float, list, tuple, np.ndarray) ): __SCREAMING_SNAKE_CASE = "np" else: raise ValueError( F"""type of {first_element} unknown: {type(UpperCAmelCase__ )}. """ "Should be one of a python, numpy, pytorch or tensorflow object." ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): __SCREAMING_SNAKE_CASE = to_numpy(UpperCAmelCase__ ) else: __SCREAMING_SNAKE_CASE = [to_numpy(UpperCAmelCase__ ) for v in value] # Convert padding_strategy in PaddingStrategy __SCREAMING_SNAKE_CASE = self._get_padding_strategies(padding=UpperCAmelCase__ , max_length=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) if not all(len(UpperCAmelCase__ ) == batch_size for v in processed_features.values() ): raise ValueError("Some items in the output dictionary have a different batch size than others." ) __SCREAMING_SNAKE_CASE = [] for i in range(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = {k: v[i] for k, v in processed_features.items()} # truncation __SCREAMING_SNAKE_CASE = self._truncate( UpperCAmelCase__ , max_length=UpperCAmelCase__ , pad_to_multiple_of=UpperCAmelCase__ , truncation=UpperCAmelCase__ , ) truncated_inputs.append(UpperCAmelCase__ ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length __SCREAMING_SNAKE_CASE = max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) __SCREAMING_SNAKE_CASE = PaddingStrategy.MAX_LENGTH __SCREAMING_SNAKE_CASE = {} for i in range(UpperCAmelCase__ ): # padding __SCREAMING_SNAKE_CASE = self._pad( truncated_inputs[i] , max_length=UpperCAmelCase__ , padding_strategy=UpperCAmelCase__ , pad_to_multiple_of=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , ) for key, value in outputs.items(): if key not in batch_outputs: __SCREAMING_SNAKE_CASE = [] if value.dtype is np.dtype(np.floataa ): __SCREAMING_SNAKE_CASE = value.astype(np.floataa ) batch_outputs[key].append(UpperCAmelCase__ ) return BatchFeature(UpperCAmelCase__ , tensor_type=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[Dict[str, np.ndarray], BatchFeature] , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , ) -> dict: __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __SCREAMING_SNAKE_CASE = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __SCREAMING_SNAKE_CASE = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(UpperCAmelCase__ ) < max_length if return_attention_mask and "attention_mask" not in processed_features: __SCREAMING_SNAKE_CASE = np.ones(len(UpperCAmelCase__ ) , dtype=np.intaa ) if needs_to_be_padded: __SCREAMING_SNAKE_CASE = max_length - len(UpperCAmelCase__ ) if self.padding_side == "right": if return_attention_mask: __SCREAMING_SNAKE_CASE = np.pad( processed_features["attention_mask"] , (0, difference) ) __SCREAMING_SNAKE_CASE = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) __SCREAMING_SNAKE_CASE = np.pad( UpperCAmelCase__ , UpperCAmelCase__ , "constant" , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: __SCREAMING_SNAKE_CASE = np.pad( processed_features["attention_mask"] , (difference, 0) ) __SCREAMING_SNAKE_CASE = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) __SCREAMING_SNAKE_CASE = np.pad( UpperCAmelCase__ , UpperCAmelCase__ , "constant" , constant_values=self.padding_value ) else: raise ValueError("Invalid padding strategy:" + str(self.padding_side ) ) return processed_features def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Union[Dict[str, np.ndarray], BatchFeature] , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , ) -> str: if not truncation: return processed_features elif truncation and max_length is None: raise ValueError("When setting ``truncation=True``, make sure that ``max_length`` is defined." ) __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __SCREAMING_SNAKE_CASE = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) > max_length if needs_to_be_truncated: __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: __SCREAMING_SNAKE_CASE = processed_features["attention_mask"][:max_length] return processed_features def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Optional[Any]=False , UpperCAmelCase__ : Optional[int]=None ) -> str: # Get padding strategy if padding is not False: if padding is True: __SCREAMING_SNAKE_CASE = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = PaddingStrategy(UpperCAmelCase__ ) elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = padding else: __SCREAMING_SNAKE_CASE = PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( F"""When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined""" ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( "Asking to pad but the feature_extractor does not have a padding value. Please select a value to use" " as `padding_value`. For example: `feature_extractor.padding_value = 0.0`." ) return padding_strategy
54
1
"""simple docstring""" # limitations under the License. # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils import deprecate deprecate( '''pipelines_utils''', '''0.22.0''', '''Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.''', standard_warn=False, stacklevel=3, )
54
"""simple docstring""" import warnings from ...utils import is_sklearn_available, requires_backends if is_sklearn_available(): from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef a__ : Any = ( '''This metric will be removed from the library soon, metrics should be handled with the 🤗 Evaluate ''' '''library. You can have a look at this example script for pointers: ''' '''https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py''' ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) return (preds == labels).mean() def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) __SCREAMING_SNAKE_CASE = simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = fa_score(y_true=lowerCAmelCase_ , y_pred=lowerCAmelCase_ ) return { "acc": acc, "f1": fa, "acc_and_f1": (acc + fa) / 2, } def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) __SCREAMING_SNAKE_CASE = pearsonr(lowerCAmelCase_ , lowerCAmelCase_ )[0] __SCREAMING_SNAKE_CASE = spearmanr(lowerCAmelCase_ , lowerCAmelCase_ )[0] return { "pearson": pearson_corr, "spearmanr": spearman_corr, "corr": (pearson_corr + spearman_corr) / 2, } def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) assert len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ), f"""Predictions and labels have mismatched lengths {len(lowerCAmelCase_ )} and {len(lowerCAmelCase_ )}""" if task_name == "cola": return {"mcc": matthews_corrcoef(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "sst-2": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "mrpc": return acc_and_fa(lowerCAmelCase_ , lowerCAmelCase_ ) elif task_name == "sts-b": return pearson_and_spearman(lowerCAmelCase_ , lowerCAmelCase_ ) elif task_name == "qqp": return acc_and_fa(lowerCAmelCase_ , lowerCAmelCase_ ) elif task_name == "mnli": return {"mnli/acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "mnli-mm": return {"mnli-mm/acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "qnli": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "rte": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "wnli": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "hans": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} else: raise KeyError(lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) if len(lowerCAmelCase_ ) != len(lowerCAmelCase_ ): raise ValueError(f"""Predictions and labels have mismatched lengths {len(lowerCAmelCase_ )} and {len(lowerCAmelCase_ )}""" ) if task_name == "xnli": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} else: raise KeyError(lowerCAmelCase_ )
54
1
"""simple docstring""" from typing import TYPE_CHECKING from ..utils import _LazyModule a__ : List[str] = { '''config''': [ '''EXTERNAL_DATA_FORMAT_SIZE_LIMIT''', '''OnnxConfig''', '''OnnxConfigWithPast''', '''OnnxSeq2SeqConfigWithPast''', '''PatchingSpec''', ], '''convert''': ['''export''', '''validate_model_outputs'''], '''features''': ['''FeaturesManager'''], '''utils''': ['''ParameterFormat''', '''compute_serialized_parameters_size'''], } if TYPE_CHECKING: from .config import ( EXTERNAL_DATA_FORMAT_SIZE_LIMIT, OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast, PatchingSpec, ) from .convert import export, validate_model_outputs from .features import FeaturesManager from .utils import ParameterFormat, compute_serialized_parameters_size else: import sys a__ : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
54
"""simple docstring""" import math import random def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = False ): '''simple docstring''' if deriv: return value * (1 - value) return 1 / (1 + math.exp(-value )) # Initial Value a__ : Tuple = 0.02 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = float(2 * (random.randint(1 , 100 )) - 1 ) for _ in range(lowerCAmelCase_ ): # Forward propagation __SCREAMING_SNAKE_CASE = sigmoid_function(INITIAL_VALUE * weight ) # How much did we miss? __SCREAMING_SNAKE_CASE = (expected / 100) - layer_a # Error delta __SCREAMING_SNAKE_CASE = layer_1_error * sigmoid_function(lowerCAmelCase_ , lowerCAmelCase_ ) # Update weight weight += INITIAL_VALUE * layer_1_delta return layer_a * 100 if __name__ == "__main__": import doctest doctest.testmod() a__ : List[str] = int(input('''Expected value: ''')) a__ : str = int(input('''Number of propagations: ''')) print(forward_propagation(expected, number_propagations))
54
1
"""simple docstring""" # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline # noqa: F401 deprecate( '''stable diffusion controlnet''', '''0.22.0''', '''Importing `FlaxStableDiffusionControlNetPipeline` from diffusers.pipelines.stable_diffusion.flax_pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import FlaxStableDiffusionControlNetPipeline` instead.''', standard_warn=False, stacklevel=3, )
54
"""simple docstring""" import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device a__ : Tuple = False class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" pass @slow @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = VersatileDiffusionImageVariationPipeline.from_pretrained("shi-labs/versatile-diffusion" ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( image=UpperCAmelCase__ , generator=UpperCAmelCase__ , guidance_scale=7.5 , num_inference_steps=5_0 , output_type="numpy" , ).images __SCREAMING_SNAKE_CASE = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __SCREAMING_SNAKE_CASE = np.array([0.0_441, 0.0_469, 0.0_507, 0.0_575, 0.0_632, 0.0_650, 0.0_865, 0.0_909, 0.0_945] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
54
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a__ : str = logging.get_logger(__name__) a__ : Union[str, Any] = { '''google/bigbird-roberta-base''': '''https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json''', '''google/bigbird-roberta-large''': '''https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json''', '''google/bigbird-base-trivia-itc''': '''https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json''', # See all BigBird models at https://huggingface.co/models?filter=big_bird } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Dict = "big_bird" def __init__( self : Dict , UpperCAmelCase__ : Any=5_0_3_5_8 , UpperCAmelCase__ : Optional[int]=7_6_8 , UpperCAmelCase__ : Any=1_2 , UpperCAmelCase__ : str=1_2 , UpperCAmelCase__ : Dict=3_0_7_2 , UpperCAmelCase__ : Tuple="gelu_new" , UpperCAmelCase__ : Tuple=0.1 , UpperCAmelCase__ : int=0.1 , UpperCAmelCase__ : List[Any]=4_0_9_6 , UpperCAmelCase__ : Union[str, Any]=2 , UpperCAmelCase__ : List[str]=0.02 , UpperCAmelCase__ : str=1E-12 , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Tuple=0 , UpperCAmelCase__ : Optional[Any]=1 , UpperCAmelCase__ : Tuple=2 , UpperCAmelCase__ : int=6_6 , UpperCAmelCase__ : Any="block_sparse" , UpperCAmelCase__ : str=True , UpperCAmelCase__ : List[str]=False , UpperCAmelCase__ : str=6_4 , UpperCAmelCase__ : str=3 , UpperCAmelCase__ : List[str]=None , **UpperCAmelCase__ : int , ) -> List[str]: super().__init__( pad_token_id=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , sep_token_id=UpperCAmelCase__ , **UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = use_cache __SCREAMING_SNAKE_CASE = rescale_embeddings __SCREAMING_SNAKE_CASE = attention_type __SCREAMING_SNAKE_CASE = use_bias __SCREAMING_SNAKE_CASE = block_size __SCREAMING_SNAKE_CASE = num_random_blocks __SCREAMING_SNAKE_CASE = classifier_dropout class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @property def UpperCAmelCase_ ( self : Union[str, Any] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": __SCREAMING_SNAKE_CASE = {0: "batch", 1: "choice", 2: "sequence"} else: __SCREAMING_SNAKE_CASE = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
54
"""simple docstring""" import importlib.util import json import os import warnings from dataclasses import dataclass, field import torch from ..training_args import TrainingArguments from ..utils import cached_property, is_sagemaker_dp_enabled, logging a__ : Union[str, Any] = logging.get_logger(__name__) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = os.getenv("SM_HP_MP_PARAMETERS" , "{}" ) try: # Parse it and check the field "partitions" is included, it is required for model parallel. __SCREAMING_SNAKE_CASE = json.loads(lowerCAmelCase_ ) if "partitions" not in smp_options: return False except json.JSONDecodeError: return False # Get the sagemaker specific framework parameters from mpi_options variable. __SCREAMING_SNAKE_CASE = os.getenv("SM_FRAMEWORK_PARAMS" , "{}" ) try: # Parse it and check the field "sagemaker_distributed_dataparallel_enabled". __SCREAMING_SNAKE_CASE = json.loads(lowerCAmelCase_ ) if not mpi_options.get("sagemaker_mpi_enabled" , lowerCAmelCase_ ): return False except json.JSONDecodeError: return False # Lastly, check if the `smdistributed` module is present. return importlib.util.find_spec("smdistributed" ) is not None if is_sagemaker_model_parallel_available(): import smdistributed.modelparallel.torch as smp smp.init() @dataclass class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = field( default="" , metadata={"help": "Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer"} , ) def UpperCAmelCase_ ( self : List[str] ) -> Any: super().__post_init__() warnings.warn( "`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use " "`TrainingArguments` instead." , UpperCAmelCase__ , ) @cached_property def UpperCAmelCase_ ( self : List[str] ) -> "torch.device": logger.info("PyTorch: setting up devices" ) if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1: logger.warning( "torch.distributed process group is initialized, but local_rank == -1. " "In order to use Torch DDP, launch your script with `python -m torch.distributed.launch" ) if self.no_cuda: __SCREAMING_SNAKE_CASE = torch.device("cpu" ) __SCREAMING_SNAKE_CASE = 0 elif is_sagemaker_model_parallel_available(): __SCREAMING_SNAKE_CASE = smp.local_rank() __SCREAMING_SNAKE_CASE = torch.device("cuda" , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = 1 elif is_sagemaker_dp_enabled(): import smdistributed.dataparallel.torch.torch_smddp # noqa: F401 torch.distributed.init_process_group(backend="smddp" , timeout=self.ddp_timeout_delta ) __SCREAMING_SNAKE_CASE = int(os.getenv("SMDATAPARALLEL_LOCAL_RANK" ) ) __SCREAMING_SNAKE_CASE = torch.device("cuda" , self.local_rank ) __SCREAMING_SNAKE_CASE = 1 elif self.local_rank == -1: # if n_gpu is > 1 we'll use nn.DataParallel. # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0` # Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will # trigger an error that a device index is missing. Index 0 takes into account the # GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0` # will use the first GPU in that env, i.e. GPU#1 __SCREAMING_SNAKE_CASE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" ) # Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at # the default value. __SCREAMING_SNAKE_CASE = torch.cuda.device_count() else: # Here, we'll use torch.distributed. # Initializes the distributed backend which will take care of synchronizing nodes/GPUs if not torch.distributed.is_initialized(): torch.distributed.init_process_group(backend="nccl" , timeout=self.ddp_timeout_delta ) __SCREAMING_SNAKE_CASE = torch.device("cuda" , self.local_rank ) __SCREAMING_SNAKE_CASE = 1 if device.type == "cuda": torch.cuda.set_device(UpperCAmelCase__ ) return device @property def UpperCAmelCase_ ( self : Dict ) -> Any: if is_sagemaker_model_parallel_available(): return smp.dp_size() return super().world_size @property def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[Any]: return not is_sagemaker_model_parallel_available() @property def UpperCAmelCase_ ( self : Tuple ) -> int: return False
54
1
"""simple docstring""" import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = ArgumentParser( description=( "PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes" ) ) # Optional arguments for the launch helper parser.add_argument("--num_cores" , type=lowerCAmelCase_ , default=1 , help="Number of TPU cores to use (1 or 8)." ) # positional parser.add_argument( "training_script" , type=lowerCAmelCase_ , help=( "The full path to the single TPU training " "program/script to be launched in parallel, " "followed by all the arguments for the " "training script" ) , ) # rest from the training program parser.add_argument("training_script_args" , nargs=lowerCAmelCase_ ) return parser.parse_args() def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = parse_args() # Import training_script as a module. __SCREAMING_SNAKE_CASE = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) __SCREAMING_SNAKE_CASE = script_fpath.stem __SCREAMING_SNAKE_CASE = importlib.import_module(lowerCAmelCase_ ) # Patch sys.argv __SCREAMING_SNAKE_CASE = [args.training_script] + args.training_script_args + ["--tpu_num_cores", str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
54
"""simple docstring""" import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Optional[int] ) -> List[str]: # For consistency across different places the DisjunctiveConstraint is called, # dc.token_ids is a list of integers. It is also initialized only by integers. __SCREAMING_SNAKE_CASE = [[1, 2, 4], [1, 2, 3, 4]] __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(UpperCAmelCase__ ) self.assertTrue(isinstance(dc.token_ids , UpperCAmelCase__ ) ) with self.assertRaises(UpperCAmelCase__ ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(UpperCAmelCase__ ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def UpperCAmelCase_ ( self : Any ) -> int: # We can't have constraints that are complete subsets of another. This leads to a preverse # interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint? # It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially # fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm # will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it). __SCREAMING_SNAKE_CASE = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(UpperCAmelCase__ ): DisjunctiveConstraint(UpperCAmelCase__ ) # fails here def UpperCAmelCase_ ( self : List[Any] ) -> Any: __SCREAMING_SNAKE_CASE = [[1, 2, 3], [1, 2, 4]] __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) __SCREAMING_SNAKE_CASE = stepped is True and completed is False and reset is False self.assertTrue(UpperCAmelCase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) __SCREAMING_SNAKE_CASE = stepped is True and completed is False and reset is False self.assertTrue(UpperCAmelCase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(3 ) __SCREAMING_SNAKE_CASE = stepped is True and completed is True and reset is False self.assertTrue(UpperCAmelCase__ ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def UpperCAmelCase_ ( self : str ) -> List[str]: __SCREAMING_SNAKE_CASE = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
54
1
"""simple docstring""" from __future__ import annotations from PIL import Image # Define glider example a__ : Dict = [ [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [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], ] # Define blinker example a__ : List[str] = [[0, 1, 0], [0, 1, 0], [0, 1, 0]] def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] for i in range(len(lowerCAmelCase_ ) ): __SCREAMING_SNAKE_CASE = [] for j in range(len(cells[i] ) ): # Get the number of live neighbours __SCREAMING_SNAKE_CASE = 0 if i > 0 and j > 0: neighbour_count += cells[i - 1][j - 1] if i > 0: neighbour_count += cells[i - 1][j] if i > 0 and j < len(cells[i] ) - 1: neighbour_count += cells[i - 1][j + 1] if j > 0: neighbour_count += cells[i][j - 1] if j < len(cells[i] ) - 1: neighbour_count += cells[i][j + 1] if i < len(lowerCAmelCase_ ) - 1 and j > 0: neighbour_count += cells[i + 1][j - 1] if i < len(lowerCAmelCase_ ) - 1: neighbour_count += cells[i + 1][j] if i < len(lowerCAmelCase_ ) - 1 and j < len(cells[i] ) - 1: neighbour_count += cells[i + 1][j + 1] # Rules of the game of life (excerpt from Wikipedia): # 1. Any live cell with two or three live neighbours survives. # 2. Any dead cell with three live neighbours becomes a live cell. # 3. All other live cells die in the next generation. # Similarly, all other dead cells stay dead. __SCREAMING_SNAKE_CASE = cells[i][j] == 1 if ( (alive and 2 <= neighbour_count <= 3) or not alive and neighbour_count == 3 ): next_generation_row.append(1 ) else: next_generation_row.append(0 ) next_generation.append(lowerCAmelCase_ ) return next_generation def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] for _ in range(lowerCAmelCase_ ): # Create output image __SCREAMING_SNAKE_CASE = Image.new("RGB" , (len(cells[0] ), len(lowerCAmelCase_ )) ) __SCREAMING_SNAKE_CASE = img.load() # Save cells to image for x in range(len(lowerCAmelCase_ ) ): for y in range(len(cells[0] ) ): __SCREAMING_SNAKE_CASE = 255 - cells[y][x] * 255 __SCREAMING_SNAKE_CASE = (colour, colour, colour) # Save image images.append(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = new_generation(lowerCAmelCase_ ) return images if __name__ == "__main__": a__ : Optional[Any] = generate_images(GLIDER, 1_6) images[0].save('''out.gif''', save_all=True, append_images=images[1:])
54
"""simple docstring""" from __future__ import annotations def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = None ): '''simple docstring''' if start is None: __SCREAMING_SNAKE_CASE = 0 if end is None: __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) - 1 if start >= end: return __SCREAMING_SNAKE_CASE = (start + end) // 2 slowsort(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) slowsort(lowerCAmelCase_ , mid + 1 , lowerCAmelCase_ ) if sequence[end] < sequence[mid]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = sequence[mid], sequence[end] slowsort(lowerCAmelCase_ , lowerCAmelCase_ , end - 1 ) if __name__ == "__main__": from doctest import testmod testmod()
54
1
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Union[str, Any] = "facebook/bart-large-mnli" snake_case__ : str = ( "This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which " "should be the text to classify, and `labels`, which should be the list of labels to use for classification. " "It returns the most likely label in the list of provided `labels` for the input text." ) snake_case__ : Tuple = "text_classifier" snake_case__ : Any = AutoTokenizer snake_case__ : Optional[Any] = AutoModelForSequenceClassification snake_case__ : Any = ["text", ["text"]] snake_case__ : Optional[int] = ["text"] def UpperCAmelCase_ ( self : Optional[int] ) -> List[Any]: super().setup() __SCREAMING_SNAKE_CASE = self.model.config __SCREAMING_SNAKE_CASE = -1 for idx, label in config.idalabel.items(): if label.lower().startswith("entail" ): __SCREAMING_SNAKE_CASE = int(UpperCAmelCase__ ) if self.entailment_id == -1: raise ValueError("Could not determine the entailment ID from the model config, please pass it at init." ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = labels return self.pre_processor( [text] * len(UpperCAmelCase__ ) , [F"""This example is {label}""" for label in labels] , return_tensors="pt" , padding="max_length" , ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : List[str] ) -> Dict: __SCREAMING_SNAKE_CASE = outputs.logits __SCREAMING_SNAKE_CASE = torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
54
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if number > 0: raise ValueError("input must be a negative integer" ) __SCREAMING_SNAKE_CASE = len(bin(lowerCAmelCase_ )[3:] ) __SCREAMING_SNAKE_CASE = bin(abs(lowerCAmelCase_ ) - (1 << binary_number_length) )[3:] __SCREAMING_SNAKE_CASE = ( ( "1" + "0" * (binary_number_length - len(lowerCAmelCase_ )) + twos_complement_number ) if number < 0 else "0" ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
54
1
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ = 100_0000 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = set(range(3 , lowerCAmelCase_ , 2 ) ) primes.add(2 ) for p in range(3 , lowerCAmelCase_ , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , lowerCAmelCase_ , lowerCAmelCase_ ) ) ) __SCREAMING_SNAKE_CASE = [float(lowerCAmelCase_ ) for n in range(limit + 1 )] for p in primes: for n in range(lowerCAmelCase_ , limit + 1 , lowerCAmelCase_ ): phi[n] *= 1 - 1 / p return int(sum(phi[2:] ) ) if __name__ == "__main__": print(F"{solution() = }")
54
"""simple docstring""" import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Any = CLIPTokenizer snake_case__ : Dict = CLIPTokenizerFast snake_case__ : List[Any] = True snake_case__ : Optional[Any] = {} snake_case__ : Dict = False def UpperCAmelCase_ ( self : Any ) -> Any: super().setUp() # fmt: off __SCREAMING_SNAKE_CASE = ["l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"] # fmt: on __SCREAMING_SNAKE_CASE = dict(zip(UpperCAmelCase__ , range(len(UpperCAmelCase__ ) ) ) ) __SCREAMING_SNAKE_CASE = ["#version: 0.2", "l o", "lo w</w>", "e r</w>"] __SCREAMING_SNAKE_CASE = {"unk_token": "<unk>"} __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(UpperCAmelCase__ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(UpperCAmelCase__ ) ) def UpperCAmelCase_ ( self : List[Any] , **UpperCAmelCase__ : Tuple ) -> List[Any]: kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any , **UpperCAmelCase__ : Optional[Any] ) -> List[str]: kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = "lower newer" __SCREAMING_SNAKE_CASE = "lower newer" return input_text, output_text def UpperCAmelCase_ ( self : int ) -> List[str]: __SCREAMING_SNAKE_CASE = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __SCREAMING_SNAKE_CASE = "lower newer" __SCREAMING_SNAKE_CASE = ["lo", "w", "er</w>", "n", "e", "w", "er</w>"] __SCREAMING_SNAKE_CASE = tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokens + [tokenizer.unk_token] __SCREAMING_SNAKE_CASE = [1_0, 2, 1_6, 9, 3, 2, 1_6, 2_0] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , UpperCAmelCase__ ) @require_ftfy def UpperCAmelCase_ ( self : Optional[Any] ) -> int: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = "A\n'll 11p223RF☆ho!!to?'d'd''d of a cat to-$''d." __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways __SCREAMING_SNAKE_CASE = "xa\u0303y" + " " + "x\xe3y" __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Test that the tokenization is identical on unicode of space type __SCREAMING_SNAKE_CASE = [ "\u0009", # (horizontal tab, '\t') "\u000B", # (vertical tab) "\u000C", # (form feed) "\u0020", # (space, ' ') "\u200E", # (left-to-right mark):w "\u200F", # (right-to-left mark) ] for unicode_seq in spaces_unicodes: __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Test that the tokenization is identical on unicode of line break type __SCREAMING_SNAKE_CASE = [ "\u000A", # (line feed, '\n') "\r\n", # (carriage return and line feed, '\r\n') "\u000D", # (carriage return, '\r') "\r", # (carriage return, '\r') "\u000D", # (carriage return, '\r') "\u2028", # (line separator) "\u2029", # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Optional[Any]: # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = "hello" # `hello` is a token in the vocabulary of `pretrained_name` __SCREAMING_SNAKE_CASE = F"""{text_of_1_token} {text_of_1_token}""" __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(UpperCAmelCase__ ) + 1, len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , ) __SCREAMING_SNAKE_CASE = F""" {text}""" __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(UpperCAmelCase__ ) + 1, 1 + len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , ) def UpperCAmelCase_ ( self : str ) -> Optional[int]: # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(UpperCAmelCase__ ) as context: self.rust_tokenizer_class.from_pretrained("robot-test/old-clip-tokenizer" ) self.assertTrue( context.exception.args[0].startswith( "The `backend_tokenizer` provided does not match the expected format." ) ) @require_ftfy def UpperCAmelCase_ ( self : Optional[int] ) -> int: super().test_tokenization_python_rust_equals() def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[Any]: # CLIP always lower cases letters pass
54
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available a__ : Tuple = { '''configuration_mvp''': ['''MVP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MvpConfig''', '''MvpOnnxConfig'''], '''tokenization_mvp''': ['''MvpTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Union[str, Any] = ['''MvpTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Optional[Any] = [ '''MVP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MvpForCausalLM''', '''MvpForConditionalGeneration''', '''MvpForQuestionAnswering''', '''MvpForSequenceClassification''', '''MvpModel''', '''MvpPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig from .tokenization_mvp import MvpTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mvp_fast import MvpTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mvp import ( MVP_PRETRAINED_MODEL_ARCHIVE_LIST, MvpForCausalLM, MvpForConditionalGeneration, MvpForQuestionAnswering, MvpForSequenceClassification, MvpModel, MvpPreTrainedModel, ) else: import sys a__ : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
54
"""simple docstring""" import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( "kwargs, expected" , [ ({"num_shards": 0, "max_num_jobs": 1}, []), ({"num_shards": 10, "max_num_jobs": 1}, [range(10 )]), ({"num_shards": 10, "max_num_jobs": 10}, [range(lowerCAmelCase_ , i + 1 ) for i in range(10 )]), ({"num_shards": 1, "max_num_jobs": 10}, [range(1 )]), ({"num_shards": 10, "max_num_jobs": 3}, [range(0 , 4 ), range(4 , 7 ), range(7 , 10 )]), ({"num_shards": 3, "max_num_jobs": 10}, [range(0 , 1 ), range(1 , 2 ), range(2 , 3 )]), ] , ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = _distribute_shards(**lowerCAmelCase_ ) assert out == expected @pytest.mark.parametrize( "gen_kwargs, max_num_jobs, expected" , [ ({"foo": 0}, 10, [{"foo": 0}]), ({"shards": [0, 1, 2, 3]}, 1, [{"shards": [0, 1, 2, 3]}]), ({"shards": [0, 1, 2, 3]}, 4, [{"shards": [0]}, {"shards": [1]}, {"shards": [2]}, {"shards": [3]}]), ({"shards": [0, 1]}, 4, [{"shards": [0]}, {"shards": [1]}]), ({"shards": [0, 1, 2, 3]}, 2, [{"shards": [0, 1]}, {"shards": [2, 3]}]), ] , ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = _split_gen_kwargs(lowerCAmelCase_ , lowerCAmelCase_ ) assert out == expected @pytest.mark.parametrize( "gen_kwargs, expected" , [ ({"foo": 0}, 1), ({"shards": [0]}, 1), ({"shards": [0, 1, 2, 3]}, 4), ({"shards": [0, 1, 2, 3], "foo": 0}, 4), ({"shards": [0, 1, 2, 3], "other": (0, 1)}, 4), ({"shards": [0, 1, 2, 3], "shards2": [0, 1]}, RuntimeError), ] , ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if expected is RuntimeError: with pytest.raises(lowerCAmelCase_ ): _number_of_shards_in_gen_kwargs(lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = _number_of_shards_in_gen_kwargs(lowerCAmelCase_ ) assert out == expected
54
1
"""simple docstring""" class UpperCamelCase_ : """simple docstring""" def __init__( self : Dict , UpperCAmelCase__ : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : List[str] ) -> str: __SCREAMING_SNAKE_CASE = name __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = weight def __repr__( self : Tuple ) -> Union[str, Any]: return F"""{self.__class__.__name__}({self.name}, {self.value}, {self.weight})""" def UpperCAmelCase_ ( self : Dict ) -> Any: return self.value def UpperCAmelCase_ ( self : List[Any] ) -> str: return self.name def UpperCAmelCase_ ( self : Tuple ) -> int: return self.weight def UpperCAmelCase_ ( self : int ) -> int: return self.value / self.weight def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] for i in range(len(lowerCAmelCase_ ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = sorted(lowerCAmelCase_ , key=lowerCAmelCase_ , reverse=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 0.0, 0.0 for i in range(len(lowerCAmelCase_ ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def UpperCAmelCase__ (): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
54
"""simple docstring""" import unittest from transformers.testing_utils import CaptureStdout from transformers.tools.python_interpreter import evaluate def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return x + 2 class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Any ) -> Any: __SCREAMING_SNAKE_CASE = "x = 3" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result == 3 self.assertDictEqual(UpperCAmelCase__ , {"x": 3} ) __SCREAMING_SNAKE_CASE = "x = y" __SCREAMING_SNAKE_CASE = {"y": 5} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 5, "y": 5} ) def UpperCAmelCase_ ( self : Dict ) -> List[str]: __SCREAMING_SNAKE_CASE = "y = add_two(x)" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 5} ) # Won't work without the tool with CaptureStdout() as out: __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result is None assert "tried to execute add_two" in out.out def UpperCAmelCase_ ( self : List[Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = "x = 3" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result == 3 self.assertDictEqual(UpperCAmelCase__ , {"x": 3} ) def UpperCAmelCase_ ( self : str ) -> Any: __SCREAMING_SNAKE_CASE = "test_dict = {'x': x, 'y': add_two(x)}" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 5} ) self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_dict": {"x": 3, "y": 5}} ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = "x = 3\ny = 5" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 5} ) def UpperCAmelCase_ ( self : Any ) -> Any: __SCREAMING_SNAKE_CASE = "text = f'This is x: {x}.'" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == "This is x: 3." self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "text": "This is x: 3."} ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = "if x <= 3:\n y = 2\nelse:\n y = 5" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 2 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 2} ) __SCREAMING_SNAKE_CASE = {"x": 8} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 8, "y": 5} ) def UpperCAmelCase_ ( self : Tuple ) -> str: __SCREAMING_SNAKE_CASE = "test_list = [x, add_two(x)]" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , [3, 5] ) self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_list": [3, 5]} ) def UpperCAmelCase_ ( self : Any ) -> int: __SCREAMING_SNAKE_CASE = "y = x" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result == 3 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 3} ) def UpperCAmelCase_ ( self : Tuple ) -> int: __SCREAMING_SNAKE_CASE = "test_list = [x, add_two(x)]\ntest_list[1]" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_list": [3, 5]} ) __SCREAMING_SNAKE_CASE = "test_dict = {'x': x, 'y': add_two(x)}\ntest_dict['y']" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_dict": {"x": 3, "y": 5}} ) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = "x = 0\nfor i in range(3):\n x = i" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"range": range} , state=UpperCAmelCase__ ) assert result == 2 self.assertDictEqual(UpperCAmelCase__ , {"x": 2, "i": 2} )
54
1
"""simple docstring""" from typing import List, Optional, Tuple, Union import torch from torch import nn from torch.nn import CrossEntropyLoss from ... import AutoBackbone from ...modeling_outputs import SemanticSegmenterOutput from ...modeling_utils import PreTrainedModel from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings from ...utils.backbone_utils import BackboneMixin from .configuration_upernet import UperNetConfig a__ : Tuple = [ '''openmmlab/upernet-convnext-tiny''', # See all UperNet models at https://huggingface.co/models?filter=upernet ] # General docstring a__ : Dict = '''UperNetConfig''' class UpperCamelCase_ ( nn.Module): """simple docstring""" def __init__( self : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[int, Tuple[int, int]] , UpperCAmelCase__ : Union[int, Tuple[int, int], str] = 0 , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : Union[int, Tuple[int, int]] = 1 , ) -> None: super().__init__() __SCREAMING_SNAKE_CASE = nn.Convad( in_channels=UpperCAmelCase__ , out_channels=UpperCAmelCase__ , kernel_size=UpperCAmelCase__ , padding=UpperCAmelCase__ , bias=UpperCAmelCase__ , dilation=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = nn.BatchNormad(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = nn.ReLU() def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : torch.Tensor ) -> torch.Tensor: __SCREAMING_SNAKE_CASE = self.conv(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.batch_norm(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return output class UpperCamelCase_ ( nn.Module): """simple docstring""" def __init__( self : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> None: super().__init__() __SCREAMING_SNAKE_CASE = [ nn.AdaptiveAvgPoolad(UpperCAmelCase__ ), UperNetConvModule(UpperCAmelCase__ , UpperCAmelCase__ , kernel_size=1 ), ] for i, layer in enumerate(self.layers ): self.add_module(str(UpperCAmelCase__ ) , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : torch.Tensor ) -> torch.Tensor: __SCREAMING_SNAKE_CASE = input for layer in self.layers: __SCREAMING_SNAKE_CASE = layer(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( nn.Module): """simple docstring""" def __init__( self : Any , UpperCAmelCase__ : Tuple[int, ...] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : bool ) -> None: super().__init__() __SCREAMING_SNAKE_CASE = pool_scales __SCREAMING_SNAKE_CASE = align_corners __SCREAMING_SNAKE_CASE = in_channels __SCREAMING_SNAKE_CASE = channels __SCREAMING_SNAKE_CASE = [] for i, pool_scale in enumerate(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = UperNetPyramidPoolingBlock(pool_scale=UpperCAmelCase__ , in_channels=UpperCAmelCase__ , channels=UpperCAmelCase__ ) self.blocks.append(UpperCAmelCase__ ) self.add_module(str(UpperCAmelCase__ ) , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : torch.Tensor ) -> List[torch.Tensor]: __SCREAMING_SNAKE_CASE = [] for ppm in self.blocks: __SCREAMING_SNAKE_CASE = ppm(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = nn.functional.interpolate( UpperCAmelCase__ , size=x.size()[2:] , mode="bilinear" , align_corners=self.align_corners ) ppm_outs.append(UpperCAmelCase__ ) return ppm_outs class UpperCamelCase_ ( nn.Module): """simple docstring""" def __init__( self : List[str] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] ) -> Optional[Any]: super().__init__() __SCREAMING_SNAKE_CASE = config __SCREAMING_SNAKE_CASE = config.pool_scales # e.g. (1, 2, 3, 6) __SCREAMING_SNAKE_CASE = in_channels __SCREAMING_SNAKE_CASE = config.hidden_size __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = nn.Convad(self.channels , config.num_labels , kernel_size=1 ) # PSP Module __SCREAMING_SNAKE_CASE = UperNetPyramidPoolingModule( self.pool_scales , self.in_channels[-1] , self.channels , align_corners=self.align_corners , ) __SCREAMING_SNAKE_CASE = UperNetConvModule( self.in_channels[-1] + len(self.pool_scales ) * self.channels , self.channels , kernel_size=3 , padding=1 , ) # FPN Module __SCREAMING_SNAKE_CASE = nn.ModuleList() __SCREAMING_SNAKE_CASE = nn.ModuleList() for in_channels in self.in_channels[:-1]: # skip the top layer __SCREAMING_SNAKE_CASE = UperNetConvModule(UpperCAmelCase__ , self.channels , kernel_size=1 ) __SCREAMING_SNAKE_CASE = UperNetConvModule(self.channels , self.channels , kernel_size=3 , padding=1 ) self.lateral_convs.append(UpperCAmelCase__ ) self.fpn_convs.append(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = UperNetConvModule( len(self.in_channels ) * self.channels , self.channels , kernel_size=3 , padding=1 , ) def UpperCAmelCase_ ( self : str ) -> Union[str, Any]: self.apply(self._init_weights ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : str ) -> int: if isinstance(UpperCAmelCase__ , nn.Convad ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Any ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = inputs[-1] __SCREAMING_SNAKE_CASE = [x] psp_outs.extend(self.psp_modules(UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = torch.cat(UpperCAmelCase__ , dim=1 ) __SCREAMING_SNAKE_CASE = self.bottleneck(UpperCAmelCase__ ) return output def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : torch.Tensor ) -> torch.Tensor: # build laterals __SCREAMING_SNAKE_CASE = [lateral_conv(encoder_hidden_states[i] ) for i, lateral_conv in enumerate(self.lateral_convs )] laterals.append(self.psp_forward(UpperCAmelCase__ ) ) # build top-down path __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) for i in range(used_backbone_levels - 1 , 0 , -1 ): __SCREAMING_SNAKE_CASE = laterals[i - 1].shape[2:] __SCREAMING_SNAKE_CASE = laterals[i - 1] + nn.functional.interpolate( laterals[i] , size=UpperCAmelCase__ , mode="bilinear" , align_corners=self.align_corners ) # build outputs __SCREAMING_SNAKE_CASE = [self.fpn_convs[i](laterals[i] ) for i in range(used_backbone_levels - 1 )] # append psp feature fpn_outs.append(laterals[-1] ) for i in range(used_backbone_levels - 1 , 0 , -1 ): __SCREAMING_SNAKE_CASE = nn.functional.interpolate( fpn_outs[i] , size=fpn_outs[0].shape[2:] , mode="bilinear" , align_corners=self.align_corners ) __SCREAMING_SNAKE_CASE = torch.cat(UpperCAmelCase__ , dim=1 ) __SCREAMING_SNAKE_CASE = self.fpn_bottleneck(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.classifier(UpperCAmelCase__ ) return output class UpperCamelCase_ ( nn.Module): """simple docstring""" def __init__( self : int , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int = 2 , UpperCAmelCase__ : int = 3 , UpperCAmelCase__ : Union[int, Tuple[int, int]] = 1 ) -> None: super().__init__() __SCREAMING_SNAKE_CASE = config __SCREAMING_SNAKE_CASE = config.auxiliary_in_channels __SCREAMING_SNAKE_CASE = config.auxiliary_channels __SCREAMING_SNAKE_CASE = config.auxiliary_num_convs __SCREAMING_SNAKE_CASE = config.auxiliary_concat_input __SCREAMING_SNAKE_CASE = in_index __SCREAMING_SNAKE_CASE = (kernel_size // 2) * dilation __SCREAMING_SNAKE_CASE = [] convs.append( UperNetConvModule( self.in_channels , self.channels , kernel_size=UpperCAmelCase__ , padding=UpperCAmelCase__ , dilation=UpperCAmelCase__ ) ) for i in range(self.num_convs - 1 ): convs.append( UperNetConvModule( self.channels , self.channels , kernel_size=UpperCAmelCase__ , padding=UpperCAmelCase__ , dilation=UpperCAmelCase__ ) ) if self.num_convs == 0: __SCREAMING_SNAKE_CASE = nn.Identity() else: __SCREAMING_SNAKE_CASE = nn.Sequential(*UpperCAmelCase__ ) if self.concat_input: __SCREAMING_SNAKE_CASE = UperNetConvModule( self.in_channels + self.channels , self.channels , kernel_size=UpperCAmelCase__ , padding=kernel_size // 2 ) __SCREAMING_SNAKE_CASE = nn.Convad(self.channels , config.num_labels , kernel_size=1 ) def UpperCAmelCase_ ( self : Optional[Any] ) -> int: self.apply(self._init_weights ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : int ) -> Union[str, Any]: if isinstance(UpperCAmelCase__ , nn.Convad ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : torch.Tensor ) -> torch.Tensor: # just take the relevant feature maps __SCREAMING_SNAKE_CASE = encoder_hidden_states[self.in_index] __SCREAMING_SNAKE_CASE = self.convs(UpperCAmelCase__ ) if self.concat_input: __SCREAMING_SNAKE_CASE = self.conv_cat(torch.cat([hidden_states, output] , dim=1 ) ) __SCREAMING_SNAKE_CASE = self.classifier(UpperCAmelCase__ ) return output class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Optional[Any] = UperNetConfig snake_case__ : Dict = "pixel_values" snake_case__ : Optional[int] = True def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : str ) -> str: if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): module.backbone.init_weights() module.decode_head.init_weights() module.auxiliary_head.init_weights() def UpperCAmelCase_ ( self : int ) -> str: self.backbone.init_weights() self.decode_head.init_weights() self.auxiliary_head.init_weights() def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Dict=False ) -> Optional[Any]: if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = value a__ : Any = r''' Parameters: This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. config ([`UperNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. ''' a__ : Optional[Any] = r''' Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using [`AutoImageProcessor`]. See [`SegformerImageProcessor.__call__`] for details. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers in case the backbone has them. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers of the backbone. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. ''' @add_start_docstrings( "UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes." , UpperCamelCase , ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : List[str] , UpperCAmelCase__ : Tuple ) -> Tuple: super().__init__(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = AutoBackbone.from_config(config.backbone_config ) # Semantic segmentation head(s) __SCREAMING_SNAKE_CASE = UperNetHead(UpperCAmelCase__ , in_channels=self.backbone.channels ) __SCREAMING_SNAKE_CASE = UperNetFCNHead(UpperCAmelCase__ ) if config.use_auxiliary_head else None # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(UPERNET_INPUTS_DOCSTRING.format("batch_size, sequence_length" ) ) @replace_return_docstrings(output_type=UpperCAmelCase__ , config_class=_CONFIG_FOR_DOC ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Optional[torch.Tensor] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[torch.Tensor] = None , UpperCAmelCase__ : Optional[bool] = None , ) -> Union[tuple, SemanticSegmenterOutput]: __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = output_attentions if output_attentions is not None else self.config.output_attentions __SCREAMING_SNAKE_CASE = self.backbone.forward_with_filtered_kwargs( UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , output_attentions=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = outputs.feature_maps __SCREAMING_SNAKE_CASE = self.decode_head(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = nn.functional.interpolate(UpperCAmelCase__ , size=pixel_values.shape[2:] , mode="bilinear" , align_corners=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = None if self.auxiliary_head is not None: __SCREAMING_SNAKE_CASE = self.auxiliary_head(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = nn.functional.interpolate( UpperCAmelCase__ , size=pixel_values.shape[2:] , mode="bilinear" , align_corners=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = None if labels is not None: if self.config.num_labels == 1: raise ValueError("The number of labels should be greater than one" ) else: # compute weighted loss __SCREAMING_SNAKE_CASE = CrossEntropyLoss(ignore_index=self.config.loss_ignore_index ) __SCREAMING_SNAKE_CASE = loss_fct(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = loss_fct(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = main_loss + self.config.auxiliary_loss_weight * auxiliary_loss if not return_dict: if output_hidden_states: __SCREAMING_SNAKE_CASE = (logits,) + outputs[1:] else: __SCREAMING_SNAKE_CASE = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return SemanticSegmenterOutput( loss=UpperCAmelCase__ , logits=UpperCAmelCase__ , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
54
"""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__ : str = { '''configuration_roformer''': ['''ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''RoFormerConfig''', '''RoFormerOnnxConfig'''], '''tokenization_roformer''': ['''RoFormerTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = ['''RoFormerTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''RoFormerForCausalLM''', '''RoFormerForMaskedLM''', '''RoFormerForMultipleChoice''', '''RoFormerForQuestionAnswering''', '''RoFormerForSequenceClassification''', '''RoFormerForTokenClassification''', '''RoFormerLayer''', '''RoFormerModel''', '''RoFormerPreTrainedModel''', '''load_tf_weights_in_roformer''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = [ '''TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFRoFormerForCausalLM''', '''TFRoFormerForMaskedLM''', '''TFRoFormerForMultipleChoice''', '''TFRoFormerForQuestionAnswering''', '''TFRoFormerForSequenceClassification''', '''TFRoFormerForTokenClassification''', '''TFRoFormerLayer''', '''TFRoFormerModel''', '''TFRoFormerPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FlaxRoFormerForMaskedLM''', '''FlaxRoFormerForMultipleChoice''', '''FlaxRoFormerForQuestionAnswering''', '''FlaxRoFormerForSequenceClassification''', '''FlaxRoFormerForTokenClassification''', '''FlaxRoFormerModel''', '''FlaxRoFormerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys a__ : int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
54
1
"""simple docstring""" import argparse import requests import torch from PIL import Image from transformers import SwinConfig, SwinForMaskedImageModeling, ViTImageProcessor def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = SwinConfig(image_size=192 ) if "base" in model_name: __SCREAMING_SNAKE_CASE = 6 __SCREAMING_SNAKE_CASE = 128 __SCREAMING_SNAKE_CASE = (2, 2, 18, 2) __SCREAMING_SNAKE_CASE = (4, 8, 16, 32) elif "large" in model_name: __SCREAMING_SNAKE_CASE = 12 __SCREAMING_SNAKE_CASE = 192 __SCREAMING_SNAKE_CASE = (2, 2, 18, 2) __SCREAMING_SNAKE_CASE = (6, 12, 24, 48) else: raise ValueError("Model not supported, only supports base and large variants" ) __SCREAMING_SNAKE_CASE = window_size __SCREAMING_SNAKE_CASE = embed_dim __SCREAMING_SNAKE_CASE = depths __SCREAMING_SNAKE_CASE = num_heads return config def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if "encoder.mask_token" in name: __SCREAMING_SNAKE_CASE = name.replace("encoder.mask_token" , "embeddings.mask_token" ) if "encoder.patch_embed.proj" in name: __SCREAMING_SNAKE_CASE = name.replace("encoder.patch_embed.proj" , "embeddings.patch_embeddings.projection" ) if "encoder.patch_embed.norm" in name: __SCREAMING_SNAKE_CASE = name.replace("encoder.patch_embed.norm" , "embeddings.norm" ) if "attn.proj" in name: __SCREAMING_SNAKE_CASE = name.replace("attn.proj" , "attention.output.dense" ) if "attn" in name: __SCREAMING_SNAKE_CASE = name.replace("attn" , "attention.self" ) if "norm1" in name: __SCREAMING_SNAKE_CASE = name.replace("norm1" , "layernorm_before" ) if "norm2" in name: __SCREAMING_SNAKE_CASE = name.replace("norm2" , "layernorm_after" ) if "mlp.fc1" in name: __SCREAMING_SNAKE_CASE = name.replace("mlp.fc1" , "intermediate.dense" ) if "mlp.fc2" in name: __SCREAMING_SNAKE_CASE = name.replace("mlp.fc2" , "output.dense" ) if name == "encoder.norm.weight": __SCREAMING_SNAKE_CASE = "layernorm.weight" if name == "encoder.norm.bias": __SCREAMING_SNAKE_CASE = "layernorm.bias" if "decoder" in name: pass else: __SCREAMING_SNAKE_CASE = "swin." + name return name def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' for key in orig_state_dict.copy().keys(): __SCREAMING_SNAKE_CASE = orig_state_dict.pop(lowerCAmelCase_ ) if "attn_mask" in key: pass elif "qkv" in key: __SCREAMING_SNAKE_CASE = key.split("." ) __SCREAMING_SNAKE_CASE = int(key_split[2] ) __SCREAMING_SNAKE_CASE = int(key_split[4] ) __SCREAMING_SNAKE_CASE = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: __SCREAMING_SNAKE_CASE = val[:dim, :] __SCREAMING_SNAKE_CASE = val[ dim : dim * 2, : ] __SCREAMING_SNAKE_CASE = val[-dim:, :] else: __SCREAMING_SNAKE_CASE = val[ :dim ] __SCREAMING_SNAKE_CASE = val[ dim : dim * 2 ] __SCREAMING_SNAKE_CASE = val[ -dim: ] else: __SCREAMING_SNAKE_CASE = val return orig_state_dict def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = torch.load(lowerCAmelCase_ , map_location="cpu" )["model"] __SCREAMING_SNAKE_CASE = get_swin_config(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = SwinForMaskedImageModeling(lowerCAmelCase_ ) model.eval() __SCREAMING_SNAKE_CASE = convert_state_dict(lowerCAmelCase_ , lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = "http://images.cocodataset.org/val2017/000000039769.jpg" __SCREAMING_SNAKE_CASE = ViTImageProcessor(size={"height": 192, "width": 192} ) __SCREAMING_SNAKE_CASE = Image.open(requests.get(lowerCAmelCase_ , stream=lowerCAmelCase_ ).raw ) __SCREAMING_SNAKE_CASE = image_processor(images=lowerCAmelCase_ , return_tensors="pt" ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(**lowerCAmelCase_ ).logits print(outputs.keys() ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: print(f"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(lowerCAmelCase_ ) print(f"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(lowerCAmelCase_ ) if push_to_hub: print(f"""Pushing model and image processor for {model_name} to hub""" ) model.push_to_hub(f"""microsoft/{model_name}""" ) image_processor.push_to_hub(f"""microsoft/{model_name}""" ) if __name__ == "__main__": a__ : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default='''swin-base-simmim-window6-192''', type=str, choices=['''swin-base-simmim-window6-192''', '''swin-large-simmim-window12-192'''], help='''Name of the Swin SimMIM model you\'d like to convert.''', ) parser.add_argument( '''--checkpoint_path''', default='''/Users/nielsrogge/Documents/SwinSimMIM/simmim_pretrain__swin_base__img192_window6__100ep.pth''', type=str, help='''Path to the original PyTorch checkpoint (.pth file).''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.''' ) a__ : List[Any] = parser.parse_args() convert_swin_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
54
"""simple docstring""" # Copyright 2022 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. import argparse import os import subprocess from packaging.version import Version, parse from accelerate.commands.config.config_args import default_config_file, load_config_from_file a__ : Tuple = '''Run commands across TPU VMs for initial setup before running `accelerate launch`.''' def UpperCAmelCase__ (lowerCAmelCase_=None ): '''simple docstring''' if subparsers is not None: __SCREAMING_SNAKE_CASE = subparsers.add_parser("tpu-config" , description=_description ) else: __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("Accelerate tpu-config command" , description=_description ) # Core arguments __SCREAMING_SNAKE_CASE = parser.add_argument_group( "Config Arguments" , "Arguments that can be configured through `accelerate config`." ) config_args.add_argument( "--config_file" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , help="Path to the config file to use for accelerate." , ) config_args.add_argument( "--tpu_name" , default=lowerCAmelCase_ , help="The name of the TPU to use. If not specified, will use the TPU specified in the config file." , ) config_args.add_argument( "--tpu_zone" , default=lowerCAmelCase_ , help="The zone of the TPU to use. If not specified, will use the zone specified in the config file." , ) __SCREAMING_SNAKE_CASE = parser.add_argument_group("TPU Arguments" , "Arguments for options ran inside the TPU." ) pod_args.add_argument( "--use_alpha" , action="store_true" , help="Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`." , ) pod_args.add_argument( "--command_file" , default=lowerCAmelCase_ , help="The path to the file containing the commands to run on the pod on startup." , ) pod_args.add_argument( "--command" , action="append" , nargs="+" , help="A command to run on the pod. Can be passed multiple times." , ) pod_args.add_argument( "--install_accelerate" , action="store_true" , help="Whether to install accelerate on the pod. Defaults to False." , ) pod_args.add_argument( "--accelerate_version" , default="latest" , help="The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify 'dev' to install from GitHub." , ) pod_args.add_argument( "--debug" , action="store_true" , help="If set, will print the command that would be run instead of running it." ) if subparsers is not None: parser.set_defaults(func=lowerCAmelCase_ ) return parser def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = None # Get the default from the config file if it exists. if args.config_file is not None or os.path.isfile(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = load_config_from_file(args.config_file ) if not args.command_file and defaults.command_file is not None and not args.command: __SCREAMING_SNAKE_CASE = defaults.command_file if not args.command and defaults.commands is not None: __SCREAMING_SNAKE_CASE = defaults.commands if not args.tpu_name: __SCREAMING_SNAKE_CASE = defaults.tpu_name if not args.tpu_zone: __SCREAMING_SNAKE_CASE = defaults.tpu_zone if args.accelerate_version == "dev": __SCREAMING_SNAKE_CASE = "git+https://github.com/huggingface/accelerate.git" elif args.accelerate_version == "latest": __SCREAMING_SNAKE_CASE = "accelerate -U" elif isinstance(parse(args.accelerate_version ) , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = f"""accelerate=={args.accelerate_version}""" if not args.command_file and not args.command: raise ValueError("You must specify either a command file or a command to run on the pod." ) if args.command_file: with open(args.command_file , "r" ) as f: __SCREAMING_SNAKE_CASE = [f.read().splitlines()] # To turn list of lists into list of strings if isinstance(args.command[0] , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = [line for cmd in args.command for line in cmd] # Default to the shared folder and install accelerate __SCREAMING_SNAKE_CASE = ["cd /usr/share"] if args.install_accelerate: new_cmd += [f"""pip install {args.accelerate_version}"""] new_cmd += args.command __SCREAMING_SNAKE_CASE = "; ".join(lowerCAmelCase_ ) # Then send it to gcloud # Eventually try to use google-api-core to do this instead of subprocess __SCREAMING_SNAKE_CASE = ["gcloud"] if args.use_alpha: cmd += ["alpha"] cmd += [ "compute", "tpus", "tpu-vm", "ssh", args.tpu_name, "--zone", args.tpu_zone, "--command", args.command, "--worker", "all", ] if args.debug: print(f"""Running {' '.join(lowerCAmelCase_ )}""" ) return subprocess.run(lowerCAmelCase_ ) print("Successfully setup pod." ) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = tpu_command_parser() __SCREAMING_SNAKE_CASE = parser.parse_args() tpu_command_launcher(lowerCAmelCase_ )
54
1
"""simple docstring""" from __future__ import annotations import unittest from transformers import LEDConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFLEDForConditionalGeneration, TFLEDModel @require_tf class UpperCamelCase_ : """simple docstring""" snake_case__ : int = LEDConfig snake_case__ : Tuple = {} snake_case__ : List[Any] = "gelu" def __init__( self : Dict , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str]=1_3 , UpperCAmelCase__ : Any=7 , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : str=False , UpperCAmelCase__ : Optional[int]=9_9 , UpperCAmelCase__ : int=3_2 , UpperCAmelCase__ : Union[str, Any]=2 , UpperCAmelCase__ : Dict=4 , UpperCAmelCase__ : int=3_7 , UpperCAmelCase__ : Optional[int]=0.1 , UpperCAmelCase__ : Optional[int]=0.1 , UpperCAmelCase__ : List[str]=2_0 , UpperCAmelCase__ : int=2 , UpperCAmelCase__ : Dict=1 , UpperCAmelCase__ : Union[str, Any]=0 , UpperCAmelCase__ : List[str]=4 , ) -> Dict: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = eos_token_id __SCREAMING_SNAKE_CASE = pad_token_id __SCREAMING_SNAKE_CASE = bos_token_id __SCREAMING_SNAKE_CASE = attention_window # `ModelTesterMixin.test_attention_outputs` is expecting attention tensors to be of size # [num_attention_heads, encoder_seq_length, encoder_key_length], but TFLongformerSelfAttention # returns attention of shape [num_attention_heads, encoder_seq_length, self.attention_window + 1] # because its local attention only attends to `self.attention_window` and one before and one after __SCREAMING_SNAKE_CASE = self.attention_window + 2 # because of padding `encoder_seq_length`, is different from `seq_length`. Relevant for # the `test_attention_outputs` and `test_hidden_states_output` tests __SCREAMING_SNAKE_CASE = ( self.seq_length + (self.attention_window - self.seq_length % self.attention_window) % self.attention_window ) def UpperCAmelCase_ ( self : Tuple ) -> List[str]: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) __SCREAMING_SNAKE_CASE = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) __SCREAMING_SNAKE_CASE = tf.concat([input_ids, eos_tensor] , axis=1 ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , attention_window=self.attention_window , **self.config_updates , ) __SCREAMING_SNAKE_CASE = prepare_led_inputs_dict(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tf.concat( [tf.zeros_like(UpperCAmelCase__ )[:, :-1], tf.ones_like(UpperCAmelCase__ )[:, -1:]] , axis=-1 , ) __SCREAMING_SNAKE_CASE = global_attention_mask return config, inputs_dict def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Union[str, Any] ) -> int: __SCREAMING_SNAKE_CASE = TFLEDModel(config=UpperCAmelCase__ ).get_decoder() __SCREAMING_SNAKE_CASE = inputs_dict["input_ids"] __SCREAMING_SNAKE_CASE = input_ids[:1, :] __SCREAMING_SNAKE_CASE = inputs_dict["attention_mask"][:1, :] __SCREAMING_SNAKE_CASE = 1 # first forward pass __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , use_cache=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , config.vocab_size ) __SCREAMING_SNAKE_CASE = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and __SCREAMING_SNAKE_CASE = tf.concat([input_ids, next_tokens] , axis=-1 ) __SCREAMING_SNAKE_CASE = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice __SCREAMING_SNAKE_CASE = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) __SCREAMING_SNAKE_CASE = output_from_no_past[:, -3:, random_slice_idx] __SCREAMING_SNAKE_CASE = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(UpperCAmelCase__ , UpperCAmelCase__ , rtol=1E-3 ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=None , lowerCAmelCase_=None , lowerCAmelCase_=None , lowerCAmelCase_=None , ): '''simple docstring''' if attention_mask is None: __SCREAMING_SNAKE_CASE = tf.cast(tf.math.not_equal(lowerCAmelCase_ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: __SCREAMING_SNAKE_CASE = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: __SCREAMING_SNAKE_CASE = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: __SCREAMING_SNAKE_CASE = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, } @require_tf class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : str = (TFLEDForConditionalGeneration, TFLEDModel) if is_tf_available() else () snake_case__ : List[str] = (TFLEDForConditionalGeneration,) if is_tf_available() else () snake_case__ : Union[str, Any] = ( { "conversational": TFLEDForConditionalGeneration, "feature-extraction": TFLEDModel, "summarization": TFLEDForConditionalGeneration, "text2text-generation": TFLEDForConditionalGeneration, "translation": TFLEDForConditionalGeneration, } if is_tf_available() else {} ) snake_case__ : str = True snake_case__ : Tuple = False snake_case__ : List[str] = False snake_case__ : int = False def UpperCAmelCase_ ( self : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = TFLEDModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Tuple: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> Optional[int]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = tf.zeros_like(inputs_dict["attention_mask"] ) __SCREAMING_SNAKE_CASE = 2 __SCREAMING_SNAKE_CASE = tf.where( tf.range(self.model_tester.seq_length )[None, :] < num_global_attn_indices , 1 , inputs_dict["global_attention_mask"] , ) __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.model_tester.seq_length __SCREAMING_SNAKE_CASE = self.model_tester.encoder_seq_length def check_decoder_attentions_output(UpperCAmelCase__ : Optional[int] ): __SCREAMING_SNAKE_CASE = outputs.decoder_attentions self.assertEqual(len(UpperCAmelCase__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) def check_encoder_attentions_output(UpperCAmelCase__ : Optional[Any] ): __SCREAMING_SNAKE_CASE = [t.numpy() for t in outputs.encoder_attentions] __SCREAMING_SNAKE_CASE = [t.numpy() for t in outputs.encoder_global_attentions] self.assertEqual(len(UpperCAmelCase__ ) , self.model_tester.num_hidden_layers ) self.assertEqual(len(UpperCAmelCase__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) self.assertListEqual( list(global_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, num_global_attn_indices] , ) for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) self.assertEqual(config.output_hidden_states , UpperCAmelCase__ ) check_encoder_attentions_output(UpperCAmelCase__ ) if self.is_encoder_decoder: __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) ) self.assertEqual(config.output_hidden_states , UpperCAmelCase__ ) check_decoder_attentions_output(UpperCAmelCase__ ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) ) self.assertEqual(config.output_hidden_states , UpperCAmelCase__ ) check_encoder_attentions_output(UpperCAmelCase__ ) # Check attention is always last and order is fine __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(UpperCAmelCase__ ) ) self.assertEqual(model.config.output_hidden_states , UpperCAmelCase__ ) check_encoder_attentions_output(UpperCAmelCase__ ) @unittest.skip("LED keeps using potentially symbolic tensors in conditionals and breaks tracing." ) def UpperCAmelCase_ ( self : List[Any] ) -> Optional[Any]: pass def UpperCAmelCase_ ( self : List[str] ) -> str: # TODO: Head-masking not yet implement pass def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return tf.constant(lowerCAmelCase_ , dtype=tf.intaa ) a__ : str = 1E-4 @slow @require_tf class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : int ) -> str: __SCREAMING_SNAKE_CASE = TFLEDForConditionalGeneration.from_pretrained("allenai/led-base-16384" ).led # change to intended input here __SCREAMING_SNAKE_CASE = _long_tensor([5_1_2 * [0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9]] ) __SCREAMING_SNAKE_CASE = _long_tensor([1_2_8 * [0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9]] ) __SCREAMING_SNAKE_CASE = prepare_led_inputs_dict(model.config , UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(**UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = (1, 1_0_2_4, 7_6_8) self.assertEqual(output.shape , UpperCAmelCase__ ) # change to expected output here __SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [[2.3_050, 2.8_279, 0.6_531], [-1.8_457, -0.1_455, -3.5_661], [-1.0_186, 0.4_586, -2.2_043]] , ) tf.debugging.assert_near(output[:, :3, :3] , UpperCAmelCase__ , atol=1E-3 ) def UpperCAmelCase_ ( self : Any ) -> Optional[int]: __SCREAMING_SNAKE_CASE = TFLEDForConditionalGeneration.from_pretrained("allenai/led-base-16384" ) # change to intended input here __SCREAMING_SNAKE_CASE = _long_tensor([5_1_2 * [0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9]] ) __SCREAMING_SNAKE_CASE = _long_tensor([1_2_8 * [0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9]] ) __SCREAMING_SNAKE_CASE = prepare_led_inputs_dict(model.config , UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(**UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = (1, 1_0_2_4, model.config.vocab_size) self.assertEqual(output.shape , UpperCAmelCase__ ) # change to expected output here __SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [[33.6_507, 6.4_572, 16.8_089], [5.8_739, -2.4_238, 11.2_902], [-3.2_139, -4.3_149, 4.2_783]] , ) tf.debugging.assert_near(output[:, :3, :3] , UpperCAmelCase__ , atol=1E-3 , rtol=1E-3 )
54
"""simple docstring""" from abc import ABC, abstractmethod from argparse import ArgumentParser class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @staticmethod @abstractmethod def UpperCAmelCase_ ( UpperCAmelCase__ : ArgumentParser ) -> int: raise NotImplementedError() @abstractmethod def UpperCAmelCase_ ( self : int ) -> Optional[int]: raise NotImplementedError()
54
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a__ : List[Any] = { '''configuration_bigbird_pegasus''': [ '''BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BigBirdPegasusConfig''', '''BigBirdPegasusOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Dict = [ '''BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BigBirdPegasusForCausalLM''', '''BigBirdPegasusForConditionalGeneration''', '''BigBirdPegasusForQuestionAnswering''', '''BigBirdPegasusForSequenceClassification''', '''BigBirdPegasusModel''', '''BigBirdPegasusPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP, BigBirdPegasusConfig, BigBirdPegasusOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST, BigBirdPegasusForCausalLM, BigBirdPegasusForConditionalGeneration, BigBirdPegasusForQuestionAnswering, BigBirdPegasusForSequenceClassification, BigBirdPegasusModel, BigBirdPegasusPreTrainedModel, ) else: import sys a__ : Optional[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
54
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def UpperCAmelCase__ (lowerCAmelCase_ = 100_0000 , lowerCAmelCase_ = 10 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = defaultdict(lowerCAmelCase_ ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: __SCREAMING_SNAKE_CASE = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: __SCREAMING_SNAKE_CASE = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(lowerCAmelCase_ , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 10 ) if __name__ == "__main__": print(F"{solution() = }")
54
1
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def UpperCAmelCase__ (lowerCAmelCase_ = 100 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 2 for i in range(2 , max_n + 1 ): __SCREAMING_SNAKE_CASE = pre_numerator __SCREAMING_SNAKE_CASE = 2 * i // 3 if i % 3 == 0 else 1 __SCREAMING_SNAKE_CASE = cur_numerator __SCREAMING_SNAKE_CASE = e_cont * pre_numerator + temp return sum_digits(lowerCAmelCase_ ) if __name__ == "__main__": print(F"{solution() = }")
54
"""simple docstring""" import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html a__ : List[str] = '''platform''' import jax import jax.numpy as jnp import numpy as np from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel @require_flax class UpperCamelCase_ : """simple docstring""" snake_case__ : Dict = PegasusConfig snake_case__ : Union[str, Any] = {} snake_case__ : Any = "gelu" def __init__( self : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int=1_3 , UpperCAmelCase__ : Optional[int]=7 , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : Any=False , UpperCAmelCase__ : List[Any]=9_9 , UpperCAmelCase__ : int=3_2 , UpperCAmelCase__ : Dict=5 , UpperCAmelCase__ : Optional[int]=4 , UpperCAmelCase__ : List[Any]=3_7 , UpperCAmelCase__ : int=0.1 , UpperCAmelCase__ : int=0.1 , UpperCAmelCase__ : List[Any]=2_0 , UpperCAmelCase__ : int=2 , UpperCAmelCase__ : List[Any]=1 , UpperCAmelCase__ : Optional[Any]=0 , ) -> Any: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = eos_token_id __SCREAMING_SNAKE_CASE = pad_token_id __SCREAMING_SNAKE_CASE = bos_token_id def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ).clip(3 , self.vocab_size ) __SCREAMING_SNAKE_CASE = np.expand_dims(np.array([self.eos_token_id] * self.batch_size ) , 1 ) __SCREAMING_SNAKE_CASE = np.concatenate([input_ids, eos_tensor] , axis=1 ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) __SCREAMING_SNAKE_CASE = prepare_pegasus_inputs_dict(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) return config, inputs_dict def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] ) -> str: __SCREAMING_SNAKE_CASE = 2_0 __SCREAMING_SNAKE_CASE = model_class_name(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.encode(inputs_dict["input_ids"] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) __SCREAMING_SNAKE_CASE = model.init_cache(decoder_input_ids.shape[0] , UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="i4" ) __SCREAMING_SNAKE_CASE = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, :-1] , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, -1:] , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , past_key_values=outputs_cache.past_key_values , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = 2_0 __SCREAMING_SNAKE_CASE = model_class_name(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.encode(inputs_dict["input_ids"] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) __SCREAMING_SNAKE_CASE = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) __SCREAMING_SNAKE_CASE = model.init_cache(decoder_input_ids.shape[0] , UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, :-1] , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, -1:] , UpperCAmelCase__ , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=UpperCAmelCase__ , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=None , lowerCAmelCase_=None , ): '''simple docstring''' if attention_mask is None: __SCREAMING_SNAKE_CASE = np.not_equal(lowerCAmelCase_ , config.pad_token_id ).astype(np.inta ) if decoder_attention_mask is None: __SCREAMING_SNAKE_CASE = np.concatenate( [ np.ones(decoder_input_ids[:, :1].shape , dtype=np.inta ), np.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ).astype(np.inta ), ] , axis=-1 , ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, } @require_flax class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Tuple = ( ( FlaxPegasusForConditionalGeneration, FlaxPegasusModel, ) if is_flax_available() else () ) snake_case__ : Union[str, Any] = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else () snake_case__ : Tuple = True snake_case__ : Union[str, Any] = False snake_case__ : int = False snake_case__ : List[Any] = False def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = FlaxPegasusModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : Tuple ) -> Optional[int]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Tuple: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __SCREAMING_SNAKE_CASE = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) @jax.jit def encode_jitted(UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : int=None , **UpperCAmelCase__ : int ): return model.encode(input_ids=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) with self.subTest("JIT Enabled" ): __SCREAMING_SNAKE_CASE = encode_jitted(**UpperCAmelCase__ ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): __SCREAMING_SNAKE_CASE = encode_jitted(**UpperCAmelCase__ ).to_tuple() self.assertEqual(len(UpperCAmelCase__ ) , len(UpperCAmelCase__ ) ) for jitted_output, output in zip(UpperCAmelCase__ , UpperCAmelCase__ ): self.assertEqual(jitted_output.shape , output.shape ) def UpperCAmelCase_ ( self : Tuple ) -> Any: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.encode(inputs_dict["input_ids"] , inputs_dict["attention_mask"] ) __SCREAMING_SNAKE_CASE = { "decoder_input_ids": inputs_dict["decoder_input_ids"], "decoder_attention_mask": inputs_dict["decoder_attention_mask"], "encoder_outputs": encoder_outputs, } @jax.jit def decode_jitted(UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] ): return model.decode( decoder_input_ids=UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , encoder_outputs=UpperCAmelCase__ , ) with self.subTest("JIT Enabled" ): __SCREAMING_SNAKE_CASE = decode_jitted(**UpperCAmelCase__ ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): __SCREAMING_SNAKE_CASE = decode_jitted(**UpperCAmelCase__ ).to_tuple() self.assertEqual(len(UpperCAmelCase__ ) , len(UpperCAmelCase__ ) ) for jitted_output, output in zip(UpperCAmelCase__ , UpperCAmelCase__ ): self.assertEqual(jitted_output.shape , output.shape ) @slow def UpperCAmelCase_ ( self : Dict ) -> Tuple: for model_class_name in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class_name.from_pretrained("google/pegasus-large" , from_pt=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.ones((1, 1) ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : Optional[int] ) -> List[Any]: __SCREAMING_SNAKE_CASE = FlaxPegasusForConditionalGeneration.from_pretrained("google/pegasus-xsum" ) __SCREAMING_SNAKE_CASE = PegasusTokenizer.from_pretrained("google/pegasus-xsum" ) __SCREAMING_SNAKE_CASE = [ " PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.", " The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" ", ] __SCREAMING_SNAKE_CASE = [ "California's largest electricity provider has turned off power to hundreds of thousands of customers.", "Pop group N-Dubz have revealed they were surprised to get four nominations for this year's Mobo Awards.", ] __SCREAMING_SNAKE_CASE = tokenizer(UpperCAmelCase__ , return_tensors="np" , truncation=UpperCAmelCase__ , max_length=5_1_2 , padding=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate(**UpperCAmelCase__ , num_beams=2 ).sequences __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ ) assert tgt_text == decoded
54
1
"""simple docstring""" from __future__ import annotations from random import choice def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return choice(lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = random_pivot(lowerCAmelCase_ ) # partition based on pivot # linear time __SCREAMING_SNAKE_CASE = [e for e in lst if e < pivot] __SCREAMING_SNAKE_CASE = [e for e in lst if e > pivot] # if we get lucky, pivot might be the element we want. # we can easily see this: # small (elements smaller than k) # + pivot (kth element) # + big (elements larger than k) if len(lowerCAmelCase_ ) == k - 1: return pivot # pivot is in elements bigger than k elif len(lowerCAmelCase_ ) < k - 1: return kth_number(lowerCAmelCase_ , k - len(lowerCAmelCase_ ) - 1 ) # pivot is in elements smaller than k else: return kth_number(lowerCAmelCase_ , lowerCAmelCase_ ) if __name__ == "__main__": import doctest doctest.testmod()
54
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ = 100_0000 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = set(range(3 , lowerCAmelCase_ , 2 ) ) primes.add(2 ) for p in range(3 , lowerCAmelCase_ , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , lowerCAmelCase_ , lowerCAmelCase_ ) ) ) __SCREAMING_SNAKE_CASE = [float(lowerCAmelCase_ ) for n in range(limit + 1 )] for p in primes: for n in range(lowerCAmelCase_ , limit + 1 , lowerCAmelCase_ ): phi[n] *= 1 - 1 / p return int(sum(phi[2:] ) ) if __name__ == "__main__": print(F"{solution() = }")
54
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__ : Dict = logging.get_logger(__name__) @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : int , **UpperCAmelCase__ : str ) -> Optional[Any]: super().__init__(**UpperCAmelCase__ ) 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(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any , **UpperCAmelCase__ : str ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = {} # preprocess args if "points_per_batch" in kwargs: __SCREAMING_SNAKE_CASE = kwargs["points_per_batch"] if "points_per_crop" in kwargs: __SCREAMING_SNAKE_CASE = kwargs["points_per_crop"] if "crops_n_layers" in kwargs: __SCREAMING_SNAKE_CASE = kwargs["crops_n_layers"] if "crop_overlap_ratio" in kwargs: __SCREAMING_SNAKE_CASE = kwargs["crop_overlap_ratio"] if "crop_n_points_downscale_factor" in kwargs: __SCREAMING_SNAKE_CASE = kwargs["crop_n_points_downscale_factor"] # postprocess args if "pred_iou_thresh" in kwargs: __SCREAMING_SNAKE_CASE = kwargs["pred_iou_thresh"] if "stability_score_offset" in kwargs: __SCREAMING_SNAKE_CASE = kwargs["stability_score_offset"] if "mask_threshold" in kwargs: __SCREAMING_SNAKE_CASE = kwargs["mask_threshold"] if "stability_score_thresh" in kwargs: __SCREAMING_SNAKE_CASE = kwargs["stability_score_thresh"] if "crops_nms_thresh" in kwargs: __SCREAMING_SNAKE_CASE = kwargs["crops_nms_thresh"] if "output_rle_mask" in kwargs: __SCREAMING_SNAKE_CASE = kwargs["output_rle_mask"] if "output_bboxes_mask" in kwargs: __SCREAMING_SNAKE_CASE = kwargs["output_bboxes_mask"] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__( self : Optional[int] , UpperCAmelCase__ : List[Any] , *UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : List[str]=None , **UpperCAmelCase__ : Tuple ) -> Union[str, Any]: return super().__call__(UpperCAmelCase__ , *UpperCAmelCase__ , num_workers=UpperCAmelCase__ , batch_size=UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : str , UpperCAmelCase__ : List[str]=6_4 , UpperCAmelCase__ : int = 0 , UpperCAmelCase__ : float = 5_1_2 / 1_5_0_0 , UpperCAmelCase__ : Optional[int] = 3_2 , UpperCAmelCase__ : Optional[int] = 1 , ) -> Tuple: __SCREAMING_SNAKE_CASE = load_image(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.image_processor.size["longest_edge"] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.image_processor.generate_crop_boxes( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.image_processor(images=UpperCAmelCase__ , return_tensors="pt" ) with self.device_placement(): if self.framework == "pt": __SCREAMING_SNAKE_CASE = self.get_inference_context() with inference_context(): __SCREAMING_SNAKE_CASE = self._ensure_tensor_on_device(UpperCAmelCase__ , device=self.device ) __SCREAMING_SNAKE_CASE = self.model.get_image_embeddings(model_inputs.pop("pixel_values" ) ) __SCREAMING_SNAKE_CASE = image_embeddings __SCREAMING_SNAKE_CASE = grid_points.shape[1] __SCREAMING_SNAKE_CASE = 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 , UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = grid_points[:, i : i + points_per_batch, :, :] __SCREAMING_SNAKE_CASE = input_labels[:, i : i + points_per_batch] __SCREAMING_SNAKE_CASE = 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 UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any]=0.88 , UpperCAmelCase__ : str=0.95 , UpperCAmelCase__ : str=0 , UpperCAmelCase__ : List[str]=1 , ) -> List[Any]: __SCREAMING_SNAKE_CASE = model_inputs.pop("input_boxes" ) __SCREAMING_SNAKE_CASE = model_inputs.pop("is_last" ) __SCREAMING_SNAKE_CASE = model_inputs.pop("original_sizes" ).tolist() __SCREAMING_SNAKE_CASE = model_inputs.pop("reshaped_input_sizes" ).tolist() __SCREAMING_SNAKE_CASE = self.model(**UpperCAmelCase__ ) # post processing happens here in order to avoid CPU GPU copies of ALL the masks __SCREAMING_SNAKE_CASE = model_outputs["pred_masks"] __SCREAMING_SNAKE_CASE = self.image_processor.post_process_masks( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , binarize=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model_outputs["iou_scores"] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : int=False , UpperCAmelCase__ : Union[str, Any]=False , UpperCAmelCase__ : Any=0.7 , ) -> Optional[int]: __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] 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" ) ) __SCREAMING_SNAKE_CASE = torch.cat(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.cat(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.image_processor.post_process_for_mask_generation( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = defaultdict(UpperCAmelCase__ ) for output in model_outputs: for k, v in output.items(): extra[k].append(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = {} if output_rle_mask: __SCREAMING_SNAKE_CASE = rle_mask if output_bboxes_mask: __SCREAMING_SNAKE_CASE = bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
54
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if upper_limit < 0: raise ValueError("Limit for the Catalan sequence must be ≥ 0" ) __SCREAMING_SNAKE_CASE = [0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 __SCREAMING_SNAKE_CASE = 1 if upper_limit > 0: __SCREAMING_SNAKE_CASE = 1 # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i for i in range(2 , upper_limit + 1 ): for j in range(lowerCAmelCase_ ): catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1] return catalan_list if __name__ == "__main__": print('''\n********* Catalan Numbers Using Dynamic Programming ************\n''') print('''\n*** Enter -1 at any time to quit ***''') print('''\nEnter the upper limit (≥ 0) for the Catalan number sequence: ''', end='''''') try: while True: a__ : List[str] = int(input().strip()) if N < 0: print('''\n********* Goodbye!! ************''') break else: print(F"The Catalan numbers from 0 through {N} are:") print(catalan_numbers(N)) print('''Try another upper limit for the sequence: ''', end='''''') except (NameError, ValueError): print('''\n********* Invalid input, goodbye! ************\n''') import doctest doctest.testmod()
54
1
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("only integers accepted as input" ) else: __SCREAMING_SNAKE_CASE = str(abs(lowerCAmelCase_ ) ) __SCREAMING_SNAKE_CASE = [list(lowerCAmelCase_ ) for char in range(len(lowerCAmelCase_ ) )] for index in range(len(lowerCAmelCase_ ) ): num_transpositions[index].pop(lowerCAmelCase_ ) return max( int("".join(list(lowerCAmelCase_ ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__('''doctest''').testmod()
54
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from itertools import chain from typing import Optional, Union import datasets import numpy as np import torch from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.tokenization_utils_base import PreTrainedTokenizerBase from transformers.trainer_utils import get_last_checkpoint from transformers.utils import PaddingStrategy, check_min_version, send_example_telemetry # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('''4.31.0''') a__ : Tuple = logging.getLogger(__name__) @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Pretrained config name or path if not the same as model_name"}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} , ) snake_case__ : str = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : Optional[str] = field(default=UpperCamelCase , metadata={"help": "The input training data file (a text file)."}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."} , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={"help": "Overwrite the cached training and evaluation sets"}) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={"help": "The number of processes to use for the preprocessing."} , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "The maximum total input sequence length after tokenization. If passed, sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={ "help": ( "Whether to pad all samples to the maximum sentence length. " "If False, will pad the samples dynamically when batching to the maximum length in the batch. More " "efficient on GPU but very bad for TPU." ) } , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: if self.train_file is not None: __SCREAMING_SNAKE_CASE = self.train_file.split("." )[-1] assert extension in ["csv", "json"], "`train_file` should be a csv or a json file." if self.validation_file is not None: __SCREAMING_SNAKE_CASE = self.validation_file.split("." )[-1] assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file." @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : PreTrainedTokenizerBase snake_case__ : Union[bool, str, PaddingStrategy] = True snake_case__ : Optional[int] = None snake_case__ : Optional[int] = None def __call__( self : int , UpperCAmelCase__ : Any ) -> str: __SCREAMING_SNAKE_CASE = "label" if "label" in features[0].keys() else "labels" __SCREAMING_SNAKE_CASE = [feature.pop(UpperCAmelCase__ ) for feature in features] __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = len(features[0]["input_ids"] ) __SCREAMING_SNAKE_CASE = [ [{k: v[i] for k, v in feature.items()} for i in range(UpperCAmelCase__ )] for feature in features ] __SCREAMING_SNAKE_CASE = list(chain(*UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = self.tokenizer.pad( UpperCAmelCase__ , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="pt" , ) # Un-flatten __SCREAMING_SNAKE_CASE = {k: v.view(UpperCAmelCase__ , UpperCAmelCase__ , -1 ) for k, v in batch.items()} # Add back labels __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ , dtype=torch.intaa ) return batch def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("run_swag" , lowerCAmelCase_ , lowerCAmelCase_ ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() __SCREAMING_SNAKE_CASE = training_args.get_process_log_level() logger.setLevel(lowerCAmelCase_ ) datasets.utils.logging.set_verbosity(lowerCAmelCase_ ) transformers.utils.logging.set_verbosity(lowerCAmelCase_ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + f"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(f"""Training/evaluation parameters {training_args}""" ) # Detecting last checkpoint. __SCREAMING_SNAKE_CASE = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: __SCREAMING_SNAKE_CASE = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. """ "Use --overwrite_output_dir to overcome." ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.train_file is not None or data_args.validation_file is not None: __SCREAMING_SNAKE_CASE = {} if data_args.train_file is not None: __SCREAMING_SNAKE_CASE = data_args.train_file if data_args.validation_file is not None: __SCREAMING_SNAKE_CASE = data_args.validation_file __SCREAMING_SNAKE_CASE = data_args.train_file.split("." )[-1] __SCREAMING_SNAKE_CASE = load_dataset( lowerCAmelCase_ , data_files=lowerCAmelCase_ , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) else: # Downloading and loading the swag dataset from the hub. __SCREAMING_SNAKE_CASE = load_dataset( "swag" , "regular" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) __SCREAMING_SNAKE_CASE = 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_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) __SCREAMING_SNAKE_CASE = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # When using your own dataset or a different dataset from swag, you will probably need to change this. __SCREAMING_SNAKE_CASE = [f"""ending{i}""" for i in range(4 )] __SCREAMING_SNAKE_CASE = "sent1" __SCREAMING_SNAKE_CASE = "sent2" if data_args.max_seq_length is None: __SCREAMING_SNAKE_CASE = tokenizer.model_max_length if max_seq_length > 1024: logger.warning( "The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value" " of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can" " override this default with `--block_size xxx`." ) __SCREAMING_SNAKE_CASE = 1024 else: if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( f"""The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the""" f"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.""" ) __SCREAMING_SNAKE_CASE = min(data_args.max_seq_length , tokenizer.model_max_length ) # Preprocessing the datasets. def preprocess_function(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = [[context] * 4 for context in examples[context_name]] __SCREAMING_SNAKE_CASE = examples[question_header_name] __SCREAMING_SNAKE_CASE = [ [f"""{header} {examples[end][i]}""" for end in ending_names] for i, header in enumerate(lowerCAmelCase_ ) ] # Flatten out __SCREAMING_SNAKE_CASE = list(chain(*lowerCAmelCase_ ) ) __SCREAMING_SNAKE_CASE = list(chain(*lowerCAmelCase_ ) ) # Tokenize __SCREAMING_SNAKE_CASE = tokenizer( lowerCAmelCase_ , lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=lowerCAmelCase_ , padding="max_length" if data_args.pad_to_max_length else False , ) # Un-flatten return {k: [v[i : i + 4] for i in range(0 , len(lowerCAmelCase_ ) , 4 )] for k, v in tokenized_examples.items()} if training_args.do_train: if "train" not in raw_datasets: raise ValueError("--do_train requires a train dataset" ) __SCREAMING_SNAKE_CASE = raw_datasets["train"] if data_args.max_train_samples is not None: __SCREAMING_SNAKE_CASE = min(len(lowerCAmelCase_ ) , data_args.max_train_samples ) __SCREAMING_SNAKE_CASE = train_dataset.select(range(lowerCAmelCase_ ) ) with training_args.main_process_first(desc="train dataset map pre-processing" ): __SCREAMING_SNAKE_CASE = train_dataset.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , ) if training_args.do_eval: if "validation" not in raw_datasets: raise ValueError("--do_eval requires a validation dataset" ) __SCREAMING_SNAKE_CASE = raw_datasets["validation"] if data_args.max_eval_samples is not None: __SCREAMING_SNAKE_CASE = min(len(lowerCAmelCase_ ) , data_args.max_eval_samples ) __SCREAMING_SNAKE_CASE = eval_dataset.select(range(lowerCAmelCase_ ) ) with training_args.main_process_first(desc="validation dataset map pre-processing" ): __SCREAMING_SNAKE_CASE = eval_dataset.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , ) # Data collator __SCREAMING_SNAKE_CASE = ( default_data_collator if data_args.pad_to_max_length else DataCollatorForMultipleChoice(tokenizer=lowerCAmelCase_ , pad_to_multiple_of=8 if training_args.fpaa else None ) ) # Metric def compute_metrics(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = eval_predictions __SCREAMING_SNAKE_CASE = np.argmax(lowerCAmelCase_ , axis=1 ) return {"accuracy": (preds == label_ids).astype(np.floataa ).mean().item()} # Initialize our Trainer __SCREAMING_SNAKE_CASE = Trainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , tokenizer=lowerCAmelCase_ , data_collator=lowerCAmelCase_ , compute_metrics=lowerCAmelCase_ , ) # Training if training_args.do_train: __SCREAMING_SNAKE_CASE = None if training_args.resume_from_checkpoint is not None: __SCREAMING_SNAKE_CASE = training_args.resume_from_checkpoint elif last_checkpoint is not None: __SCREAMING_SNAKE_CASE = last_checkpoint __SCREAMING_SNAKE_CASE = trainer.train(resume_from_checkpoint=lowerCAmelCase_ ) trainer.save_model() # Saves the tokenizer too for easy upload __SCREAMING_SNAKE_CASE = train_result.metrics __SCREAMING_SNAKE_CASE = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(lowerCAmelCase_ ) ) __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ , len(lowerCAmelCase_ ) ) trainer.log_metrics("train" , lowerCAmelCase_ ) trainer.save_metrics("train" , lowerCAmelCase_ ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("*** Evaluate ***" ) __SCREAMING_SNAKE_CASE = trainer.evaluate() __SCREAMING_SNAKE_CASE = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ , len(lowerCAmelCase_ ) ) trainer.log_metrics("eval" , lowerCAmelCase_ ) trainer.save_metrics("eval" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { "finetuned_from": model_args.model_name_or_path, "tasks": "multiple-choice", "dataset_tags": "swag", "dataset_args": "regular", "dataset": "SWAG", "language": "en", } if training_args.push_to_hub: trainer.push_to_hub(**lowerCAmelCase_ ) else: trainer.create_model_card(**lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' main() if __name__ == "__main__": main()
54
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__ : Tuple = logging.get_logger(__name__) a__ : Optional[Any] = { '''google/vit-base-patch16-224''': '''https://huggingface.co/vit-base-patch16-224/resolve/main/config.json''', # See all ViT models at https://huggingface.co/models?filter=vit } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Union[str, Any] = "vit" def __init__( self : Union[str, Any] , UpperCAmelCase__ : Dict=7_6_8 , UpperCAmelCase__ : Tuple=1_2 , UpperCAmelCase__ : str=1_2 , UpperCAmelCase__ : Dict=3_0_7_2 , UpperCAmelCase__ : List[Any]="gelu" , UpperCAmelCase__ : Optional[int]=0.0 , UpperCAmelCase__ : int=0.0 , UpperCAmelCase__ : Optional[Any]=0.02 , UpperCAmelCase__ : str=1E-12 , UpperCAmelCase__ : List[str]=2_2_4 , UpperCAmelCase__ : List[str]=1_6 , UpperCAmelCase__ : Union[str, Any]=3 , UpperCAmelCase__ : List[str]=True , UpperCAmelCase__ : Optional[int]=1_6 , **UpperCAmelCase__ : Optional[Any] , ) -> List[Any]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = qkv_bias __SCREAMING_SNAKE_CASE = encoder_stride class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : List[Any] = version.parse("1.11") @property def UpperCAmelCase_ ( self : Optional[Any] ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def UpperCAmelCase_ ( self : Any ) -> float: return 1E-4
54
"""simple docstring""" from PIL import Image def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = image.size __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = image.load() for i in range(lowerCAmelCase_ ): for j in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = pixels[j, i] mean += pixel mean //= width * height for j in range(lowerCAmelCase_ ): for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = 255 if pixels[i, j] > mean else 0 return image if __name__ == "__main__": a__ : List[str] = mean_threshold(Image.open('''path_to_image''').convert('''L''')) image.save('''output_image_path''')
54
1
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from ..utils import cached_file # docstyle-ignore a__ : Union[str, Any] = ''' Human: <<task>> Assistant: ''' a__ : Optional[Any] = '''huggingface-tools/default-prompts''' a__ : int = {'''chat''': '''chat_prompt_template.txt''', '''run''': '''run_prompt_template.txt'''} def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_="run" ): '''simple docstring''' if prompt_or_repo_id is None: __SCREAMING_SNAKE_CASE = DEFAULT_PROMPTS_REPO # prompt is considered a repo ID when it does not contain any kind of space if re.search("\\s" , lowerCAmelCase_ ) is not None: return prompt_or_repo_id __SCREAMING_SNAKE_CASE = cached_file( lowerCAmelCase_ , PROMPT_FILES[mode] , repo_type="dataset" , user_agent={"agent": agent_name} ) with open(lowerCAmelCase_ , "r" , encoding="utf-8" ) as f: return f.read()
54
"""simple docstring""" from jiwer import compute_measures import datasets a__ : Optional[int] = '''\ @inproceedings{inproceedings, author = {Morris, Andrew and Maier, Viktoria and Green, Phil}, year = {2004}, month = {01}, pages = {}, title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.} } ''' a__ : List[str] = '''\ Word error rate (WER) is a common metric of the performance of an automatic speech recognition system. The general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort. This problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate. Word error rate can then be computed as: WER = (S + D + I) / N = (S + D + I) / (S + D + C) where S is the number of substitutions, D is the number of deletions, I is the number of insertions, C is the number of correct words, N is the number of words in the reference (N=S+D+C). This value indicates the average number of errors per reference word. The lower the value, the better the performance of the ASR system with a WER of 0 being a perfect score. ''' a__ : Dict = ''' Compute WER score of transcribed segments against references. Args: references: List of references for each speech input. predictions: List of transcriptions to score. concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively. Returns: (float): the word error rate Examples: >>> predictions = ["this is the prediction", "there is an other sample"] >>> references = ["this is the reference", "there is another one"] >>> wer = datasets.load_metric("wer") >>> wer_score = wer.compute(predictions=predictions, references=references) >>> print(wer_score) 0.5 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class UpperCamelCase_ ( datasets.Metric): """simple docstring""" def UpperCAmelCase_ ( self : List[Any] ) -> str: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , codebase_urls=["https://github.com/jitsi/jiwer/"] , reference_urls=[ "https://en.wikipedia.org/wiki/Word_error_rate", ] , ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : Any=False ) -> Optional[int]: if concatenate_texts: return compute_measures(UpperCAmelCase__ , UpperCAmelCase__ )["wer"] else: __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for prediction, reference in zip(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = compute_measures(UpperCAmelCase__ , UpperCAmelCase__ ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
54
1
"""simple docstring""" from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = cva.getAffineTransform(lowerCAmelCase_ , lowerCAmelCase_ ) return cva.warpAffine(lowerCAmelCase_ , lowerCAmelCase_ , (rows, cols) ) if __name__ == "__main__": # read original image a__ : Any = cva.imread( str(Path(__file__).resolve().parent.parent / '''image_data''' / '''lena.jpg''') ) # turn image in gray scale value a__ : Optional[Any] = cva.cvtColor(image, cva.COLOR_BGR2GRAY) # get image shape a__ , a__ : Union[str, Any] = gray_img.shape # set different points to rotate image a__ : Optional[Any] = np.array([[5_0, 5_0], [2_0_0, 5_0], [5_0, 2_0_0]], np.floataa) a__ : List[str] = np.array([[1_0, 1_0_0], [2_0_0, 5_0], [1_0_0, 2_5_0]], np.floataa) a__ : Optional[Any] = np.array([[5_0, 5_0], [1_5_0, 5_0], [1_2_0, 2_0_0]], np.floataa) a__ : Tuple = np.array([[1_0, 1_0_0], [8_0, 5_0], [1_8_0, 2_5_0]], np.floataa) # add all rotated images in a list a__ : Union[str, Any] = [ gray_img, get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), ] # plot different image rotations a__ : Any = plt.figure(1) a__ : Optional[int] = ['''Original''', '''Rotation 1''', '''Rotation 2''', '''Rotation 3'''] for i, image in enumerate(images): plt.subplot(2, 2, i + 1), plt.imshow(image, '''gray''') plt.title(titles[i]) plt.axis('''off''') plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95) plt.show()
54
"""simple docstring""" from __future__ import annotations import pandas as pd def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [0] * no_of_processes __SCREAMING_SNAKE_CASE = [0] * no_of_processes # Copy the burst time into remaining_time[] for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = burst_time[i] __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 9_9999_9999 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = False # Process until all processes are completed while complete != no_of_processes: for j in range(lowerCAmelCase_ ): if arrival_time[j] <= increment_time and remaining_time[j] > 0: if remaining_time[j] < minm: __SCREAMING_SNAKE_CASE = remaining_time[j] __SCREAMING_SNAKE_CASE = j __SCREAMING_SNAKE_CASE = True if not check: increment_time += 1 continue remaining_time[short] -= 1 __SCREAMING_SNAKE_CASE = remaining_time[short] if minm == 0: __SCREAMING_SNAKE_CASE = 9_9999_9999 if remaining_time[short] == 0: complete += 1 __SCREAMING_SNAKE_CASE = False # Find finish time of current process __SCREAMING_SNAKE_CASE = increment_time + 1 # Calculate waiting time __SCREAMING_SNAKE_CASE = finish_time - arrival_time[short] __SCREAMING_SNAKE_CASE = finar - burst_time[short] if waiting_time[short] < 0: __SCREAMING_SNAKE_CASE = 0 # Increment time increment_time += 1 return waiting_time def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [0] * no_of_processes for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = burst_time[i] + waiting_time[i] return turn_around_time def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = total_waiting_time + waiting_time[i] __SCREAMING_SNAKE_CASE = total_turn_around_time + turn_around_time[i] print(f"""Average waiting time = {total_waiting_time / no_of_processes:.5f}""" ) print("Average turn around time =" , total_turn_around_time / no_of_processes ) if __name__ == "__main__": print('''Enter how many process you want to analyze''') a__ : Optional[Any] = int(input()) a__ : Optional[int] = [0] * no_of_processes a__ : int = [0] * no_of_processes a__ : List[Any] = list(range(1, no_of_processes + 1)) for i in range(no_of_processes): print('''Enter the arrival time and burst time for process:--''' + str(i + 1)) a__ , a__ : Tuple = map(int, input().split()) a__ : int = calculate_waitingtime(arrival_time, burst_time, no_of_processes) a__ : Dict = burst_time a__ : Any = no_of_processes a__ : Optional[int] = waiting_time a__ : Union[str, Any] = calculate_turnaroundtime(bt, n, wt) calculate_average_times(waiting_time, turn_around_time, no_of_processes) a__ : str = pd.DataFrame( list(zip(processes, burst_time, arrival_time, waiting_time, turn_around_time)), columns=[ '''Process''', '''BurstTime''', '''ArrivalTime''', '''WaitingTime''', '''TurnAroundTime''', ], ) # Printing the dataFrame pd.set_option('''display.max_rows''', fcfs.shape[0] + 1) print(fcfs)
54
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import _LazyModule a__ : str = {'''tokenization_bertweet''': ['''BertweetTokenizer''']} if TYPE_CHECKING: from .tokenization_bertweet import BertweetTokenizer else: import sys a__ : Tuple = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
54
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy a__ : Union[str, Any] = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : float , **UpperCAmelCase__ : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = feature_size __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = padding_value __SCREAMING_SNAKE_CASE = kwargs.pop("padding_side" , "right" ) __SCREAMING_SNAKE_CASE = kwargs.pop("return_attention_mask" , UpperCAmelCase__ ) super().__init__(**UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[ BatchFeature, List[BatchFeature], Dict[str, BatchFeature], Dict[str, List[BatchFeature]], List[Dict[str, BatchFeature]], ] , UpperCAmelCase__ : Union[bool, str, PaddingStrategy] = True , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[Union[str, TensorType]] = None , ) -> BatchFeature: # If we have a list of dicts, let's convert it in a dict of lists # We do this to allow using this method as a collate_fn function in PyTorch Dataloader if isinstance(UpperCAmelCase__ , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): __SCREAMING_SNAKE_CASE = { key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( "You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`" F""" to this method that includes {self.model_input_names[0]}, but you provided""" F""" {list(processed_features.keys() )}""" ) __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] __SCREAMING_SNAKE_CASE = ( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(UpperCAmelCase__ ) == 0: if return_attention_mask: __SCREAMING_SNAKE_CASE = [] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch __SCREAMING_SNAKE_CASE = required_input[0] if isinstance(UpperCAmelCase__ , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. __SCREAMING_SNAKE_CASE = 0 while len(required_input[index] ) == 0: index += 1 if index < len(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = required_input[index][0] if return_tensors is None: if is_tf_tensor(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = "tf" elif is_torch_tensor(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = "pt" elif isinstance(UpperCAmelCase__ , (int, float, list, tuple, np.ndarray) ): __SCREAMING_SNAKE_CASE = "np" else: raise ValueError( F"""type of {first_element} unknown: {type(UpperCAmelCase__ )}. """ "Should be one of a python, numpy, pytorch or tensorflow object." ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): __SCREAMING_SNAKE_CASE = to_numpy(UpperCAmelCase__ ) else: __SCREAMING_SNAKE_CASE = [to_numpy(UpperCAmelCase__ ) for v in value] # Convert padding_strategy in PaddingStrategy __SCREAMING_SNAKE_CASE = self._get_padding_strategies(padding=UpperCAmelCase__ , max_length=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) if not all(len(UpperCAmelCase__ ) == batch_size for v in processed_features.values() ): raise ValueError("Some items in the output dictionary have a different batch size than others." ) __SCREAMING_SNAKE_CASE = [] for i in range(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = {k: v[i] for k, v in processed_features.items()} # truncation __SCREAMING_SNAKE_CASE = self._truncate( UpperCAmelCase__ , max_length=UpperCAmelCase__ , pad_to_multiple_of=UpperCAmelCase__ , truncation=UpperCAmelCase__ , ) truncated_inputs.append(UpperCAmelCase__ ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length __SCREAMING_SNAKE_CASE = max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) __SCREAMING_SNAKE_CASE = PaddingStrategy.MAX_LENGTH __SCREAMING_SNAKE_CASE = {} for i in range(UpperCAmelCase__ ): # padding __SCREAMING_SNAKE_CASE = self._pad( truncated_inputs[i] , max_length=UpperCAmelCase__ , padding_strategy=UpperCAmelCase__ , pad_to_multiple_of=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , ) for key, value in outputs.items(): if key not in batch_outputs: __SCREAMING_SNAKE_CASE = [] if value.dtype is np.dtype(np.floataa ): __SCREAMING_SNAKE_CASE = value.astype(np.floataa ) batch_outputs[key].append(UpperCAmelCase__ ) return BatchFeature(UpperCAmelCase__ , tensor_type=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[Dict[str, np.ndarray], BatchFeature] , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , ) -> dict: __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __SCREAMING_SNAKE_CASE = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __SCREAMING_SNAKE_CASE = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(UpperCAmelCase__ ) < max_length if return_attention_mask and "attention_mask" not in processed_features: __SCREAMING_SNAKE_CASE = np.ones(len(UpperCAmelCase__ ) , dtype=np.intaa ) if needs_to_be_padded: __SCREAMING_SNAKE_CASE = max_length - len(UpperCAmelCase__ ) if self.padding_side == "right": if return_attention_mask: __SCREAMING_SNAKE_CASE = np.pad( processed_features["attention_mask"] , (0, difference) ) __SCREAMING_SNAKE_CASE = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) __SCREAMING_SNAKE_CASE = np.pad( UpperCAmelCase__ , UpperCAmelCase__ , "constant" , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: __SCREAMING_SNAKE_CASE = np.pad( processed_features["attention_mask"] , (difference, 0) ) __SCREAMING_SNAKE_CASE = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) __SCREAMING_SNAKE_CASE = np.pad( UpperCAmelCase__ , UpperCAmelCase__ , "constant" , constant_values=self.padding_value ) else: raise ValueError("Invalid padding strategy:" + str(self.padding_side ) ) return processed_features def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Union[Dict[str, np.ndarray], BatchFeature] , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , ) -> str: if not truncation: return processed_features elif truncation and max_length is None: raise ValueError("When setting ``truncation=True``, make sure that ``max_length`` is defined." ) __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __SCREAMING_SNAKE_CASE = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) > max_length if needs_to_be_truncated: __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: __SCREAMING_SNAKE_CASE = processed_features["attention_mask"][:max_length] return processed_features def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Optional[Any]=False , UpperCAmelCase__ : Optional[int]=None ) -> str: # Get padding strategy if padding is not False: if padding is True: __SCREAMING_SNAKE_CASE = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = PaddingStrategy(UpperCAmelCase__ ) elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = padding else: __SCREAMING_SNAKE_CASE = PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( F"""When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined""" ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( "Asking to pad but the feature_extractor does not have a padding value. Please select a value to use" " as `padding_value`. For example: `feature_extractor.padding_value = 0.0`." ) return padding_strategy
54
1
"""simple docstring""" import torch def UpperCAmelCase__ (): '''simple docstring''' if torch.cuda.is_available(): __SCREAMING_SNAKE_CASE = torch.cuda.device_count() else: __SCREAMING_SNAKE_CASE = 0 print(f"""Successfully ran on {num_gpus} GPUs""" ) if __name__ == "__main__": main()
54
"""simple docstring""" import warnings from ...utils import is_sklearn_available, requires_backends if is_sklearn_available(): from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef a__ : Any = ( '''This metric will be removed from the library soon, metrics should be handled with the 🤗 Evaluate ''' '''library. You can have a look at this example script for pointers: ''' '''https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py''' ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) return (preds == labels).mean() def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) __SCREAMING_SNAKE_CASE = simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = fa_score(y_true=lowerCAmelCase_ , y_pred=lowerCAmelCase_ ) return { "acc": acc, "f1": fa, "acc_and_f1": (acc + fa) / 2, } def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) __SCREAMING_SNAKE_CASE = pearsonr(lowerCAmelCase_ , lowerCAmelCase_ )[0] __SCREAMING_SNAKE_CASE = spearmanr(lowerCAmelCase_ , lowerCAmelCase_ )[0] return { "pearson": pearson_corr, "spearmanr": spearman_corr, "corr": (pearson_corr + spearman_corr) / 2, } def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) assert len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ), f"""Predictions and labels have mismatched lengths {len(lowerCAmelCase_ )} and {len(lowerCAmelCase_ )}""" if task_name == "cola": return {"mcc": matthews_corrcoef(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "sst-2": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "mrpc": return acc_and_fa(lowerCAmelCase_ , lowerCAmelCase_ ) elif task_name == "sts-b": return pearson_and_spearman(lowerCAmelCase_ , lowerCAmelCase_ ) elif task_name == "qqp": return acc_and_fa(lowerCAmelCase_ , lowerCAmelCase_ ) elif task_name == "mnli": return {"mnli/acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "mnli-mm": return {"mnli-mm/acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "qnli": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "rte": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "wnli": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "hans": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} else: raise KeyError(lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) if len(lowerCAmelCase_ ) != len(lowerCAmelCase_ ): raise ValueError(f"""Predictions and labels have mismatched lengths {len(lowerCAmelCase_ )} and {len(lowerCAmelCase_ )}""" ) if task_name == "xnli": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} else: raise KeyError(lowerCAmelCase_ )
54
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : str = logging.get_logger(__name__) a__ : Dict = { '''microsoft/markuplm-base''': '''https://huggingface.co/microsoft/markuplm-base/resolve/main/config.json''', '''microsoft/markuplm-large''': '''https://huggingface.co/microsoft/markuplm-large/resolve/main/config.json''', } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : List[str] = "markuplm" def __init__( self : int , UpperCAmelCase__ : Tuple=3_0_5_2_2 , UpperCAmelCase__ : List[Any]=7_6_8 , UpperCAmelCase__ : Optional[Any]=1_2 , UpperCAmelCase__ : int=1_2 , UpperCAmelCase__ : List[str]=3_0_7_2 , UpperCAmelCase__ : Dict="gelu" , UpperCAmelCase__ : Union[str, Any]=0.1 , UpperCAmelCase__ : int=0.1 , UpperCAmelCase__ : List[str]=5_1_2 , UpperCAmelCase__ : Any=2 , UpperCAmelCase__ : List[str]=0.02 , UpperCAmelCase__ : Optional[Any]=1E-12 , UpperCAmelCase__ : str=0 , UpperCAmelCase__ : Optional[int]=0 , UpperCAmelCase__ : int=2 , UpperCAmelCase__ : int=2_5_6 , UpperCAmelCase__ : str=1_0_2_4 , UpperCAmelCase__ : str=2_1_6 , UpperCAmelCase__ : List[Any]=1_0_0_1 , UpperCAmelCase__ : List[Any]=3_2 , UpperCAmelCase__ : Optional[Any]=5_0 , UpperCAmelCase__ : Union[str, Any]="absolute" , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : int=None , **UpperCAmelCase__ : List[str] , ) -> Union[str, Any]: super().__init__( pad_token_id=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , **UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = position_embedding_type __SCREAMING_SNAKE_CASE = use_cache __SCREAMING_SNAKE_CASE = classifier_dropout # additional properties __SCREAMING_SNAKE_CASE = max_depth __SCREAMING_SNAKE_CASE = max_xpath_tag_unit_embeddings __SCREAMING_SNAKE_CASE = max_xpath_subs_unit_embeddings __SCREAMING_SNAKE_CASE = tag_pad_id __SCREAMING_SNAKE_CASE = subs_pad_id __SCREAMING_SNAKE_CASE = xpath_unit_hidden_size
54
"""simple docstring""" import math import random def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = False ): '''simple docstring''' if deriv: return value * (1 - value) return 1 / (1 + math.exp(-value )) # Initial Value a__ : Tuple = 0.02 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = float(2 * (random.randint(1 , 100 )) - 1 ) for _ in range(lowerCAmelCase_ ): # Forward propagation __SCREAMING_SNAKE_CASE = sigmoid_function(INITIAL_VALUE * weight ) # How much did we miss? __SCREAMING_SNAKE_CASE = (expected / 100) - layer_a # Error delta __SCREAMING_SNAKE_CASE = layer_1_error * sigmoid_function(lowerCAmelCase_ , lowerCAmelCase_ ) # Update weight weight += INITIAL_VALUE * layer_1_delta return layer_a * 100 if __name__ == "__main__": import doctest doctest.testmod() a__ : List[str] = int(input('''Expected value: ''')) a__ : str = int(input('''Number of propagations: ''')) print(forward_propagation(expected, number_propagations))
54
1
"""simple docstring""" from typing import Callable, List, Optional, Union import PIL import torch from transformers import ( CLIPImageProcessor, CLIPSegForImageSegmentation, CLIPSegProcessor, CLIPTextModel, CLIPTokenizer, ) from diffusers import DiffusionPipeline from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import deprecate, is_accelerate_available, logging a__ : str = logging.get_logger(__name__) # pylint: disable=invalid-name class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : List[Any] , UpperCAmelCase__ : CLIPSegForImageSegmentation , UpperCAmelCase__ : CLIPSegProcessor , UpperCAmelCase__ : AutoencoderKL , UpperCAmelCase__ : CLIPTextModel , UpperCAmelCase__ : CLIPTokenizer , UpperCAmelCase__ : UNetaDConditionModel , UpperCAmelCase__ : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , UpperCAmelCase__ : StableDiffusionSafetyChecker , UpperCAmelCase__ : CLIPImageProcessor , ) -> List[Any]: super().__init__() if hasattr(scheduler.config , "steps_offset" ) and scheduler.config.steps_offset != 1: __SCREAMING_SNAKE_CASE = ( F"""The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`""" F""" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure """ "to update the config accordingly as leaving `steps_offset` might led to incorrect results" " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" " file" ) deprecate("steps_offset!=1" , "1.0.0" , UpperCAmelCase__ , standard_warn=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = dict(scheduler.config ) __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = FrozenDict(UpperCAmelCase__ ) if hasattr(scheduler.config , "skip_prk_steps" ) and scheduler.config.skip_prk_steps is False: __SCREAMING_SNAKE_CASE = ( F"""The configuration file of this scheduler: {scheduler} has not set the configuration""" " `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make" " sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to" " incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face" " Hub, it would be very nice if you could open a Pull request for the" " `scheduler/scheduler_config.json` file" ) deprecate("skip_prk_steps not set" , "1.0.0" , UpperCAmelCase__ , standard_warn=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = dict(scheduler.config ) __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = FrozenDict(UpperCAmelCase__ ) if safety_checker is None: logger.warning( F"""You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure""" " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" " results in services or applications open to the public. Both the diffusers team and Hugging Face" " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" " it only for use-cases that involve analyzing network behavior or auditing its results. For more" " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." ) self.register_modules( segmentation_model=UpperCAmelCase__ , segmentation_processor=UpperCAmelCase__ , vae=UpperCAmelCase__ , text_encoder=UpperCAmelCase__ , tokenizer=UpperCAmelCase__ , unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ , safety_checker=UpperCAmelCase__ , feature_extractor=UpperCAmelCase__ , ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Optional[Union[str, int]] = "auto" ) -> List[str]: if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory __SCREAMING_SNAKE_CASE = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> List[Any]: self.enable_attention_slicing(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> Dict: if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("Please install accelerate via `pip install accelerate`" ) __SCREAMING_SNAKE_CASE = torch.device("cuda" ) for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]: if cpu_offloaded_model is not None: cpu_offload(UpperCAmelCase__ , UpperCAmelCase__ ) @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def UpperCAmelCase_ ( self : Union[str, Any] ) -> Any: if self.device != torch.device("meta" ) or not hasattr(self.unet , "_hf_hook" ): return self.device for module in self.unet.modules(): if ( hasattr(UpperCAmelCase__ , "_hf_hook" ) and hasattr(module._hf_hook , "execution_device" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() def __call__( self : List[Any] , UpperCAmelCase__ : Union[str, List[str]] , UpperCAmelCase__ : Union[torch.FloatTensor, PIL.Image.Image] , UpperCAmelCase__ : str , UpperCAmelCase__ : int = 5_1_2 , UpperCAmelCase__ : int = 5_1_2 , UpperCAmelCase__ : int = 5_0 , UpperCAmelCase__ : float = 7.5 , UpperCAmelCase__ : Optional[Union[str, List[str]]] = None , UpperCAmelCase__ : Optional[int] = 1 , UpperCAmelCase__ : float = 0.0 , UpperCAmelCase__ : Optional[torch.Generator] = None , UpperCAmelCase__ : Optional[torch.FloatTensor] = None , UpperCAmelCase__ : Optional[str] = "pil" , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , UpperCAmelCase__ : int = 1 , **UpperCAmelCase__ : Optional[Any] , ) -> Any: __SCREAMING_SNAKE_CASE = self.segmentation_processor( text=[text] , images=[image] , padding="max_length" , return_tensors="pt" ).to(self.device ) __SCREAMING_SNAKE_CASE = self.segmentation_model(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy() __SCREAMING_SNAKE_CASE = self.numpy_to_pil(UpperCAmelCase__ )[0].resize(image.size ) # Run inpainting pipeline with the generated mask __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline( vae=self.vae , text_encoder=self.text_encoder , tokenizer=self.tokenizer , unet=self.unet , scheduler=self.scheduler , safety_checker=self.safety_checker , feature_extractor=self.feature_extractor , ) return inpainting_pipeline( prompt=UpperCAmelCase__ , image=UpperCAmelCase__ , mask_image=UpperCAmelCase__ , height=UpperCAmelCase__ , width=UpperCAmelCase__ , num_inference_steps=UpperCAmelCase__ , guidance_scale=UpperCAmelCase__ , negative_prompt=UpperCAmelCase__ , num_images_per_prompt=UpperCAmelCase__ , eta=UpperCAmelCase__ , generator=UpperCAmelCase__ , latents=UpperCAmelCase__ , output_type=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , callback=UpperCAmelCase__ , callback_steps=UpperCAmelCase__ , )
54
"""simple docstring""" import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device a__ : Tuple = False class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" pass @slow @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = VersatileDiffusionImageVariationPipeline.from_pretrained("shi-labs/versatile-diffusion" ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( image=UpperCAmelCase__ , generator=UpperCAmelCase__ , guidance_scale=7.5 , num_inference_steps=5_0 , output_type="numpy" , ).images __SCREAMING_SNAKE_CASE = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __SCREAMING_SNAKE_CASE = np.array([0.0_441, 0.0_469, 0.0_507, 0.0_575, 0.0_632, 0.0_650, 0.0_865, 0.0_909, 0.0_945] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
54
1
"""simple docstring""" from __future__ import annotations def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' create_state_space_tree(lowerCAmelCase_ , [] , 0 , [0 for i in range(len(lowerCAmelCase_ ) )] ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ): '''simple docstring''' if index == len(lowerCAmelCase_ ): print(lowerCAmelCase_ ) return for i in range(len(lowerCAmelCase_ ) ): if not index_used[i]: current_sequence.append(sequence[i] ) __SCREAMING_SNAKE_CASE = True create_state_space_tree(lowerCAmelCase_ , lowerCAmelCase_ , index + 1 , lowerCAmelCase_ ) current_sequence.pop() __SCREAMING_SNAKE_CASE = False a__ : list[int | str] = [3, 1, 2, 4] generate_all_permutations(sequence) a__ : list[int | str] = ["A", "B", "C"] generate_all_permutations(sequence_a)
54
"""simple docstring""" import importlib.util import json import os import warnings from dataclasses import dataclass, field import torch from ..training_args import TrainingArguments from ..utils import cached_property, is_sagemaker_dp_enabled, logging a__ : Union[str, Any] = logging.get_logger(__name__) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = os.getenv("SM_HP_MP_PARAMETERS" , "{}" ) try: # Parse it and check the field "partitions" is included, it is required for model parallel. __SCREAMING_SNAKE_CASE = json.loads(lowerCAmelCase_ ) if "partitions" not in smp_options: return False except json.JSONDecodeError: return False # Get the sagemaker specific framework parameters from mpi_options variable. __SCREAMING_SNAKE_CASE = os.getenv("SM_FRAMEWORK_PARAMS" , "{}" ) try: # Parse it and check the field "sagemaker_distributed_dataparallel_enabled". __SCREAMING_SNAKE_CASE = json.loads(lowerCAmelCase_ ) if not mpi_options.get("sagemaker_mpi_enabled" , lowerCAmelCase_ ): return False except json.JSONDecodeError: return False # Lastly, check if the `smdistributed` module is present. return importlib.util.find_spec("smdistributed" ) is not None if is_sagemaker_model_parallel_available(): import smdistributed.modelparallel.torch as smp smp.init() @dataclass class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = field( default="" , metadata={"help": "Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer"} , ) def UpperCAmelCase_ ( self : List[str] ) -> Any: super().__post_init__() warnings.warn( "`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use " "`TrainingArguments` instead." , UpperCAmelCase__ , ) @cached_property def UpperCAmelCase_ ( self : List[str] ) -> "torch.device": logger.info("PyTorch: setting up devices" ) if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1: logger.warning( "torch.distributed process group is initialized, but local_rank == -1. " "In order to use Torch DDP, launch your script with `python -m torch.distributed.launch" ) if self.no_cuda: __SCREAMING_SNAKE_CASE = torch.device("cpu" ) __SCREAMING_SNAKE_CASE = 0 elif is_sagemaker_model_parallel_available(): __SCREAMING_SNAKE_CASE = smp.local_rank() __SCREAMING_SNAKE_CASE = torch.device("cuda" , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = 1 elif is_sagemaker_dp_enabled(): import smdistributed.dataparallel.torch.torch_smddp # noqa: F401 torch.distributed.init_process_group(backend="smddp" , timeout=self.ddp_timeout_delta ) __SCREAMING_SNAKE_CASE = int(os.getenv("SMDATAPARALLEL_LOCAL_RANK" ) ) __SCREAMING_SNAKE_CASE = torch.device("cuda" , self.local_rank ) __SCREAMING_SNAKE_CASE = 1 elif self.local_rank == -1: # if n_gpu is > 1 we'll use nn.DataParallel. # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0` # Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will # trigger an error that a device index is missing. Index 0 takes into account the # GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0` # will use the first GPU in that env, i.e. GPU#1 __SCREAMING_SNAKE_CASE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" ) # Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at # the default value. __SCREAMING_SNAKE_CASE = torch.cuda.device_count() else: # Here, we'll use torch.distributed. # Initializes the distributed backend which will take care of synchronizing nodes/GPUs if not torch.distributed.is_initialized(): torch.distributed.init_process_group(backend="nccl" , timeout=self.ddp_timeout_delta ) __SCREAMING_SNAKE_CASE = torch.device("cuda" , self.local_rank ) __SCREAMING_SNAKE_CASE = 1 if device.type == "cuda": torch.cuda.set_device(UpperCAmelCase__ ) return device @property def UpperCAmelCase_ ( self : Dict ) -> Any: if is_sagemaker_model_parallel_available(): return smp.dp_size() return super().world_size @property def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[Any]: return not is_sagemaker_model_parallel_available() @property def UpperCAmelCase_ ( self : Tuple ) -> int: return False
54
1
"""simple docstring""" import jax.numpy as jnp from ...utils import logging from ..ta.modeling_flax_ta import FlaxTaEncoderModel, FlaxTaForConditionalGeneration, FlaxTaModel from .configuration_mta import MTaConfig a__ : Union[str, Any] = logging.get_logger(__name__) a__ : str = '''T5Config''' def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = jnp.zeros_like(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = shifted_input_ids.at[:, 1:].set(input_ids[:, :-1] ) __SCREAMING_SNAKE_CASE = shifted_input_ids.at[:, 0].set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = jnp.where(shifted_input_ids == -100 , lowerCAmelCase_ , lowerCAmelCase_ ) return shifted_input_ids class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Any = "mt5" snake_case__ : List[str] = MTaConfig class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : int = "mt5" snake_case__ : Dict = MTaConfig class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Union[str, Any] = "mt5" snake_case__ : Optional[int] = MTaConfig
54
"""simple docstring""" import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Optional[int] ) -> List[str]: # For consistency across different places the DisjunctiveConstraint is called, # dc.token_ids is a list of integers. It is also initialized only by integers. __SCREAMING_SNAKE_CASE = [[1, 2, 4], [1, 2, 3, 4]] __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(UpperCAmelCase__ ) self.assertTrue(isinstance(dc.token_ids , UpperCAmelCase__ ) ) with self.assertRaises(UpperCAmelCase__ ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(UpperCAmelCase__ ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def UpperCAmelCase_ ( self : Any ) -> int: # We can't have constraints that are complete subsets of another. This leads to a preverse # interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint? # It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially # fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm # will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it). __SCREAMING_SNAKE_CASE = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(UpperCAmelCase__ ): DisjunctiveConstraint(UpperCAmelCase__ ) # fails here def UpperCAmelCase_ ( self : List[Any] ) -> Any: __SCREAMING_SNAKE_CASE = [[1, 2, 3], [1, 2, 4]] __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) __SCREAMING_SNAKE_CASE = stepped is True and completed is False and reset is False self.assertTrue(UpperCAmelCase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) __SCREAMING_SNAKE_CASE = stepped is True and completed is False and reset is False self.assertTrue(UpperCAmelCase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(3 ) __SCREAMING_SNAKE_CASE = stepped is True and completed is True and reset is False self.assertTrue(UpperCAmelCase__ ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def UpperCAmelCase_ ( self : str ) -> List[str]: __SCREAMING_SNAKE_CASE = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
54
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__ : List[Any] = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : List[str] = ["pixel_values"] def __init__( self : List[Any] , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Dict[str, int] = None , UpperCAmelCase__ : float = None , UpperCAmelCase__ : PILImageResampling = PILImageResampling.BILINEAR , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Union[int, float] = 1 / 2_5_5 , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Optional[Union[float, List[float]]] = None , UpperCAmelCase__ : Optional[Union[float, List[float]]] = None , **UpperCAmelCase__ : Optional[int] , ) -> None: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = size if size is not None else {"shortest_edge": 3_8_4} __SCREAMING_SNAKE_CASE = get_size_dict(UpperCAmelCase__ , default_to_square=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = do_resize __SCREAMING_SNAKE_CASE = size # Default value set here for backwards compatibility where the value in config is None __SCREAMING_SNAKE_CASE = crop_pct if crop_pct is not None else 2_2_4 / 2_5_6 __SCREAMING_SNAKE_CASE = resample __SCREAMING_SNAKE_CASE = do_rescale __SCREAMING_SNAKE_CASE = rescale_factor __SCREAMING_SNAKE_CASE = do_normalize __SCREAMING_SNAKE_CASE = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __SCREAMING_SNAKE_CASE = image_std if image_std is not None else IMAGENET_STANDARD_STD def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : Dict[str, int] , UpperCAmelCase__ : float , UpperCAmelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase__ : Tuple , ) -> np.ndarray: __SCREAMING_SNAKE_CASE = get_size_dict(UpperCAmelCase__ , default_to_square=UpperCAmelCase__ ) if "shortest_edge" not in size: raise ValueError(F"""Size dictionary must contain 'shortest_edge' key. Got {size.keys()}""" ) __SCREAMING_SNAKE_CASE = size["shortest_edge"] if shortest_edge < 3_8_4: # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct __SCREAMING_SNAKE_CASE = int(shortest_edge / crop_pct ) __SCREAMING_SNAKE_CASE = get_resize_output_image_size(UpperCAmelCase__ , size=UpperCAmelCase__ , default_to_square=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = resize(image=UpperCAmelCase__ , size=UpperCAmelCase__ , resample=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) # then crop to (shortest_edge, shortest_edge) return center_crop(image=UpperCAmelCase__ , size=(shortest_edge, shortest_edge) , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) else: # warping (no cropping) when evaluated at 384 or larger return resize( UpperCAmelCase__ , size=(shortest_edge, shortest_edge) , resample=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : Union[int, float] , UpperCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase__ : int , ) -> str: return rescale(UpperCAmelCase__ , scale=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : Union[float, List[float]] , UpperCAmelCase__ : Union[float, List[float]] , UpperCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase__ : Dict , ) -> np.ndarray: return normalize(UpperCAmelCase__ , mean=UpperCAmelCase__ , std=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : ImageInput , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : Dict[str, int] = None , UpperCAmelCase__ : float = None , UpperCAmelCase__ : PILImageResampling = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : float = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : Optional[Union[float, List[float]]] = None , UpperCAmelCase__ : Optional[Union[float, List[float]]] = None , UpperCAmelCase__ : Optional[Union[str, TensorType]] = None , UpperCAmelCase__ : ChannelDimension = ChannelDimension.FIRST , **UpperCAmelCase__ : Tuple , ) -> PIL.Image.Image: __SCREAMING_SNAKE_CASE = do_resize if do_resize is not None else self.do_resize __SCREAMING_SNAKE_CASE = crop_pct if crop_pct is not None else self.crop_pct __SCREAMING_SNAKE_CASE = resample if resample is not None else self.resample __SCREAMING_SNAKE_CASE = do_rescale if do_rescale is not None else self.do_rescale __SCREAMING_SNAKE_CASE = rescale_factor if rescale_factor is not None else self.rescale_factor __SCREAMING_SNAKE_CASE = do_normalize if do_normalize is not None else self.do_normalize __SCREAMING_SNAKE_CASE = image_mean if image_mean is not None else self.image_mean __SCREAMING_SNAKE_CASE = image_std if image_std is not None else self.image_std __SCREAMING_SNAKE_CASE = size if size is not None else self.size __SCREAMING_SNAKE_CASE = get_size_dict(UpperCAmelCase__ , default_to_square=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = make_list_of_images(UpperCAmelCase__ ) if not valid_images(UpperCAmelCase__ ): 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. __SCREAMING_SNAKE_CASE = [to_numpy_array(UpperCAmelCase__ ) for image in images] if do_resize: __SCREAMING_SNAKE_CASE = [self.resize(image=UpperCAmelCase__ , size=UpperCAmelCase__ , crop_pct=UpperCAmelCase__ , resample=UpperCAmelCase__ ) for image in images] if do_rescale: __SCREAMING_SNAKE_CASE = [self.rescale(image=UpperCAmelCase__ , scale=UpperCAmelCase__ ) for image in images] if do_normalize: __SCREAMING_SNAKE_CASE = [self.normalize(image=UpperCAmelCase__ , mean=UpperCAmelCase__ , std=UpperCAmelCase__ ) for image in images] __SCREAMING_SNAKE_CASE = [to_channel_dimension_format(UpperCAmelCase__ , UpperCAmelCase__ ) for image in images] __SCREAMING_SNAKE_CASE = {"pixel_values": images} return BatchFeature(data=UpperCAmelCase__ , tensor_type=UpperCAmelCase__ )
54
"""simple docstring""" from __future__ import annotations def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = None ): '''simple docstring''' if start is None: __SCREAMING_SNAKE_CASE = 0 if end is None: __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) - 1 if start >= end: return __SCREAMING_SNAKE_CASE = (start + end) // 2 slowsort(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) slowsort(lowerCAmelCase_ , mid + 1 , lowerCAmelCase_ ) if sequence[end] < sequence[mid]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = sequence[mid], sequence[end] slowsort(lowerCAmelCase_ , lowerCAmelCase_ , end - 1 ) if __name__ == "__main__": from doctest import testmod testmod()
54
1
"""simple docstring""" from __future__ import annotations def UpperCAmelCase__ (lowerCAmelCase_ = 4 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = abs(lowerCAmelCase_ ) or 4 return [[1 + x + y * row_size for x in range(lowerCAmelCase_ )] for y in range(lowerCAmelCase_ )] def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return reverse_row(transpose(lowerCAmelCase_ ) ) # OR.. transpose(reverse_column(matrix)) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return reverse_row(reverse_column(lowerCAmelCase_ ) ) # OR.. reverse_column(reverse_row(matrix)) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return reverse_column(transpose(lowerCAmelCase_ ) ) # OR.. transpose(reverse_row(matrix)) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [list(lowerCAmelCase_ ) for x in zip(*lowerCAmelCase_ )] return matrix def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = matrix[::-1] return matrix def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [x[::-1] for x in matrix] return matrix def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' for i in matrix: print(*lowerCAmelCase_ ) if __name__ == "__main__": a__ : Optional[Any] = make_matrix() print('''\norigin:\n''') print_matrix(matrix) print('''\nrotate 90 counterclockwise:\n''') print_matrix(rotate_aa(matrix)) a__ : Union[str, Any] = make_matrix() print('''\norigin:\n''') print_matrix(matrix) print('''\nrotate 180:\n''') print_matrix(rotate_aaa(matrix)) a__ : List[Any] = make_matrix() print('''\norigin:\n''') print_matrix(matrix) print('''\nrotate 270 counterclockwise:\n''') print_matrix(rotate_aaa(matrix))
54
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if number > 0: raise ValueError("input must be a negative integer" ) __SCREAMING_SNAKE_CASE = len(bin(lowerCAmelCase_ )[3:] ) __SCREAMING_SNAKE_CASE = bin(abs(lowerCAmelCase_ ) - (1 << binary_number_length) )[3:] __SCREAMING_SNAKE_CASE = ( ( "1" + "0" * (binary_number_length - len(lowerCAmelCase_ )) + twos_complement_number ) if number < 0 else "0" ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
54
1
"""simple docstring""" import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home a__ : List[str] = HUGGINGFACE_HUB_CACHE a__ : int = '''config.json''' a__ : List[str] = '''diffusion_pytorch_model.bin''' a__ : Optional[int] = '''diffusion_flax_model.msgpack''' a__ : str = '''model.onnx''' a__ : Optional[Any] = '''diffusion_pytorch_model.safetensors''' a__ : Union[str, Any] = '''weights.pb''' a__ : Optional[int] = '''https://huggingface.co''' a__ : Dict = default_cache_path a__ : Optional[int] = '''diffusers_modules''' a__ : Any = os.getenv('''HF_MODULES_CACHE''', os.path.join(hf_cache_home, '''modules''')) a__ : Any = ['''fp16''', '''non-ema'''] a__ : Dict = '''.self_attn'''
54
"""simple docstring""" import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Any = CLIPTokenizer snake_case__ : Dict = CLIPTokenizerFast snake_case__ : List[Any] = True snake_case__ : Optional[Any] = {} snake_case__ : Dict = False def UpperCAmelCase_ ( self : Any ) -> Any: super().setUp() # fmt: off __SCREAMING_SNAKE_CASE = ["l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"] # fmt: on __SCREAMING_SNAKE_CASE = dict(zip(UpperCAmelCase__ , range(len(UpperCAmelCase__ ) ) ) ) __SCREAMING_SNAKE_CASE = ["#version: 0.2", "l o", "lo w</w>", "e r</w>"] __SCREAMING_SNAKE_CASE = {"unk_token": "<unk>"} __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(UpperCAmelCase__ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(UpperCAmelCase__ ) ) def UpperCAmelCase_ ( self : List[Any] , **UpperCAmelCase__ : Tuple ) -> List[Any]: kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any , **UpperCAmelCase__ : Optional[Any] ) -> List[str]: kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = "lower newer" __SCREAMING_SNAKE_CASE = "lower newer" return input_text, output_text def UpperCAmelCase_ ( self : int ) -> List[str]: __SCREAMING_SNAKE_CASE = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __SCREAMING_SNAKE_CASE = "lower newer" __SCREAMING_SNAKE_CASE = ["lo", "w", "er</w>", "n", "e", "w", "er</w>"] __SCREAMING_SNAKE_CASE = tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokens + [tokenizer.unk_token] __SCREAMING_SNAKE_CASE = [1_0, 2, 1_6, 9, 3, 2, 1_6, 2_0] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , UpperCAmelCase__ ) @require_ftfy def UpperCAmelCase_ ( self : Optional[Any] ) -> int: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = "A\n'll 11p223RF☆ho!!to?'d'd''d of a cat to-$''d." __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways __SCREAMING_SNAKE_CASE = "xa\u0303y" + " " + "x\xe3y" __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Test that the tokenization is identical on unicode of space type __SCREAMING_SNAKE_CASE = [ "\u0009", # (horizontal tab, '\t') "\u000B", # (vertical tab) "\u000C", # (form feed) "\u0020", # (space, ' ') "\u200E", # (left-to-right mark):w "\u200F", # (right-to-left mark) ] for unicode_seq in spaces_unicodes: __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Test that the tokenization is identical on unicode of line break type __SCREAMING_SNAKE_CASE = [ "\u000A", # (line feed, '\n') "\r\n", # (carriage return and line feed, '\r\n') "\u000D", # (carriage return, '\r') "\r", # (carriage return, '\r') "\u000D", # (carriage return, '\r') "\u2028", # (line separator) "\u2029", # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Optional[Any]: # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = "hello" # `hello` is a token in the vocabulary of `pretrained_name` __SCREAMING_SNAKE_CASE = F"""{text_of_1_token} {text_of_1_token}""" __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(UpperCAmelCase__ ) + 1, len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , ) __SCREAMING_SNAKE_CASE = F""" {text}""" __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(UpperCAmelCase__ ) + 1, 1 + len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , ) def UpperCAmelCase_ ( self : str ) -> Optional[int]: # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(UpperCAmelCase__ ) as context: self.rust_tokenizer_class.from_pretrained("robot-test/old-clip-tokenizer" ) self.assertTrue( context.exception.args[0].startswith( "The `backend_tokenizer` provided does not match the expected format." ) ) @require_ftfy def UpperCAmelCase_ ( self : Optional[int] ) -> int: super().test_tokenization_python_rust_equals() def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[Any]: # CLIP always lower cases letters pass
54
1
"""simple docstring""" from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : List[str] = ["image_processor", "tokenizer"] snake_case__ : Any = "BlipImageProcessor" snake_case__ : Any = ("BertTokenizer", "BertTokenizerFast") def __init__( self : str , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any ) -> Any: __SCREAMING_SNAKE_CASE = False super().__init__(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.image_processor def __call__( self : Union[str, Any] , UpperCAmelCase__ : ImageInput = None , UpperCAmelCase__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Union[bool, str, PaddingStrategy] = False , UpperCAmelCase__ : Union[bool, str, TruncationStrategy] = None , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : int = 0 , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Optional[Union[str, TensorType]] = None , **UpperCAmelCase__ : Union[str, Any] , ) -> BatchEncoding: if images is None and text is None: raise ValueError("You have to specify either images or text." ) # Get only text if images is None: __SCREAMING_SNAKE_CASE = self.tokenizer __SCREAMING_SNAKE_CASE = self.tokenizer( text=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , padding=UpperCAmelCase__ , truncation=UpperCAmelCase__ , max_length=UpperCAmelCase__ , stride=UpperCAmelCase__ , pad_to_multiple_of=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , return_overflowing_tokens=UpperCAmelCase__ , return_special_tokens_mask=UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ , return_length=UpperCAmelCase__ , verbose=UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__ , ) return text_encoding # add pixel_values __SCREAMING_SNAKE_CASE = self.image_processor(UpperCAmelCase__ , return_tensors=UpperCAmelCase__ ) if text is not None: __SCREAMING_SNAKE_CASE = self.tokenizer( text=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , padding=UpperCAmelCase__ , truncation=UpperCAmelCase__ , max_length=UpperCAmelCase__ , stride=UpperCAmelCase__ , pad_to_multiple_of=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , return_overflowing_tokens=UpperCAmelCase__ , return_special_tokens_mask=UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ , return_length=UpperCAmelCase__ , verbose=UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__ , ) else: __SCREAMING_SNAKE_CASE = None if text_encoding is not None: encoding_image_processor.update(UpperCAmelCase__ ) return encoding_image_processor def UpperCAmelCase_ ( self : str , *UpperCAmelCase__ : str , **UpperCAmelCase__ : List[Any] ) -> List[str]: return self.tokenizer.batch_decode(*UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str , *UpperCAmelCase__ : Tuple , **UpperCAmelCase__ : Tuple ) -> List[str]: return self.tokenizer.decode(*UpperCAmelCase__ , **UpperCAmelCase__ ) @property def UpperCAmelCase_ ( self : Dict ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.tokenizer.model_input_names __SCREAMING_SNAKE_CASE = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
54
"""simple docstring""" import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( "kwargs, expected" , [ ({"num_shards": 0, "max_num_jobs": 1}, []), ({"num_shards": 10, "max_num_jobs": 1}, [range(10 )]), ({"num_shards": 10, "max_num_jobs": 10}, [range(lowerCAmelCase_ , i + 1 ) for i in range(10 )]), ({"num_shards": 1, "max_num_jobs": 10}, [range(1 )]), ({"num_shards": 10, "max_num_jobs": 3}, [range(0 , 4 ), range(4 , 7 ), range(7 , 10 )]), ({"num_shards": 3, "max_num_jobs": 10}, [range(0 , 1 ), range(1 , 2 ), range(2 , 3 )]), ] , ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = _distribute_shards(**lowerCAmelCase_ ) assert out == expected @pytest.mark.parametrize( "gen_kwargs, max_num_jobs, expected" , [ ({"foo": 0}, 10, [{"foo": 0}]), ({"shards": [0, 1, 2, 3]}, 1, [{"shards": [0, 1, 2, 3]}]), ({"shards": [0, 1, 2, 3]}, 4, [{"shards": [0]}, {"shards": [1]}, {"shards": [2]}, {"shards": [3]}]), ({"shards": [0, 1]}, 4, [{"shards": [0]}, {"shards": [1]}]), ({"shards": [0, 1, 2, 3]}, 2, [{"shards": [0, 1]}, {"shards": [2, 3]}]), ] , ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = _split_gen_kwargs(lowerCAmelCase_ , lowerCAmelCase_ ) assert out == expected @pytest.mark.parametrize( "gen_kwargs, expected" , [ ({"foo": 0}, 1), ({"shards": [0]}, 1), ({"shards": [0, 1, 2, 3]}, 4), ({"shards": [0, 1, 2, 3], "foo": 0}, 4), ({"shards": [0, 1, 2, 3], "other": (0, 1)}, 4), ({"shards": [0, 1, 2, 3], "shards2": [0, 1]}, RuntimeError), ] , ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if expected is RuntimeError: with pytest.raises(lowerCAmelCase_ ): _number_of_shards_in_gen_kwargs(lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = _number_of_shards_in_gen_kwargs(lowerCAmelCase_ ) assert out == expected
54
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig a__ : Optional[int] = { '''google/tapas-base-finetuned-sqa''': ( '''https://huggingface.co/google/tapas-base-finetuned-sqa/resolve/main/config.json''' ), '''google/tapas-base-finetuned-wtq''': ( '''https://huggingface.co/google/tapas-base-finetuned-wtq/resolve/main/config.json''' ), '''google/tapas-base-finetuned-wikisql-supervised''': ( '''https://huggingface.co/google/tapas-base-finetuned-wikisql-supervised/resolve/main/config.json''' ), '''google/tapas-base-finetuned-tabfact''': ( '''https://huggingface.co/google/tapas-base-finetuned-tabfact/resolve/main/config.json''' ), } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : List[str] = "tapas" def __init__( self : int , UpperCAmelCase__ : Any=3_0_5_2_2 , UpperCAmelCase__ : Dict=7_6_8 , UpperCAmelCase__ : Optional[Any]=1_2 , UpperCAmelCase__ : Optional[int]=1_2 , UpperCAmelCase__ : Any=3_0_7_2 , UpperCAmelCase__ : List[Any]="gelu" , UpperCAmelCase__ : List[Any]=0.1 , UpperCAmelCase__ : List[str]=0.1 , UpperCAmelCase__ : str=1_0_2_4 , UpperCAmelCase__ : Dict=[3, 2_5_6, 2_5_6, 2, 2_5_6, 2_5_6, 1_0] , UpperCAmelCase__ : Union[str, Any]=0.02 , UpperCAmelCase__ : Tuple=1E-12 , UpperCAmelCase__ : Any=0 , UpperCAmelCase__ : Any=10.0 , UpperCAmelCase__ : Dict=0 , UpperCAmelCase__ : str=1.0 , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : str=1.0 , UpperCAmelCase__ : Union[str, Any]=False , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : Tuple=1.0 , UpperCAmelCase__ : Any=1.0 , UpperCAmelCase__ : Optional[int]=False , UpperCAmelCase__ : str=False , UpperCAmelCase__ : List[str]="ratio" , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : Optional[int]=6_4 , UpperCAmelCase__ : Any=3_2 , UpperCAmelCase__ : Optional[Any]=False , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : List[str]=False , UpperCAmelCase__ : int=False , UpperCAmelCase__ : Any=True , UpperCAmelCase__ : List[Any]=False , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : Any=None , **UpperCAmelCase__ : Optional[int] , ) -> List[str]: super().__init__(pad_token_id=UpperCAmelCase__ , **UpperCAmelCase__ ) # BERT hyperparameters (with updated max_position_embeddings and type_vocab_sizes) __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_sizes __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps # Fine-tuning task hyperparameters __SCREAMING_SNAKE_CASE = positive_label_weight __SCREAMING_SNAKE_CASE = num_aggregation_labels __SCREAMING_SNAKE_CASE = aggregation_loss_weight __SCREAMING_SNAKE_CASE = use_answer_as_supervision __SCREAMING_SNAKE_CASE = answer_loss_importance __SCREAMING_SNAKE_CASE = use_normalized_answer_loss __SCREAMING_SNAKE_CASE = huber_loss_delta __SCREAMING_SNAKE_CASE = temperature __SCREAMING_SNAKE_CASE = aggregation_temperature __SCREAMING_SNAKE_CASE = use_gumbel_for_cells __SCREAMING_SNAKE_CASE = use_gumbel_for_aggregation __SCREAMING_SNAKE_CASE = average_approximation_function __SCREAMING_SNAKE_CASE = cell_selection_preference __SCREAMING_SNAKE_CASE = answer_loss_cutoff __SCREAMING_SNAKE_CASE = max_num_rows __SCREAMING_SNAKE_CASE = max_num_columns __SCREAMING_SNAKE_CASE = average_logits_per_cell __SCREAMING_SNAKE_CASE = select_one_column __SCREAMING_SNAKE_CASE = allow_empty_column_selection __SCREAMING_SNAKE_CASE = init_cell_selection_weights_to_zero __SCREAMING_SNAKE_CASE = reset_position_index_per_cell __SCREAMING_SNAKE_CASE = disable_per_token_loss # Aggregation hyperparameters __SCREAMING_SNAKE_CASE = aggregation_labels __SCREAMING_SNAKE_CASE = no_aggregation_label_index if isinstance(self.aggregation_labels , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = {int(UpperCAmelCase__ ): v for k, v in aggregation_labels.items()}
54
"""simple docstring""" import unittest from transformers.testing_utils import CaptureStdout from transformers.tools.python_interpreter import evaluate def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return x + 2 class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Any ) -> Any: __SCREAMING_SNAKE_CASE = "x = 3" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result == 3 self.assertDictEqual(UpperCAmelCase__ , {"x": 3} ) __SCREAMING_SNAKE_CASE = "x = y" __SCREAMING_SNAKE_CASE = {"y": 5} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 5, "y": 5} ) def UpperCAmelCase_ ( self : Dict ) -> List[str]: __SCREAMING_SNAKE_CASE = "y = add_two(x)" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 5} ) # Won't work without the tool with CaptureStdout() as out: __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result is None assert "tried to execute add_two" in out.out def UpperCAmelCase_ ( self : List[Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = "x = 3" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result == 3 self.assertDictEqual(UpperCAmelCase__ , {"x": 3} ) def UpperCAmelCase_ ( self : str ) -> Any: __SCREAMING_SNAKE_CASE = "test_dict = {'x': x, 'y': add_two(x)}" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 5} ) self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_dict": {"x": 3, "y": 5}} ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = "x = 3\ny = 5" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 5} ) def UpperCAmelCase_ ( self : Any ) -> Any: __SCREAMING_SNAKE_CASE = "text = f'This is x: {x}.'" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == "This is x: 3." self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "text": "This is x: 3."} ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = "if x <= 3:\n y = 2\nelse:\n y = 5" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 2 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 2} ) __SCREAMING_SNAKE_CASE = {"x": 8} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 8, "y": 5} ) def UpperCAmelCase_ ( self : Tuple ) -> str: __SCREAMING_SNAKE_CASE = "test_list = [x, add_two(x)]" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , [3, 5] ) self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_list": [3, 5]} ) def UpperCAmelCase_ ( self : Any ) -> int: __SCREAMING_SNAKE_CASE = "y = x" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result == 3 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 3} ) def UpperCAmelCase_ ( self : Tuple ) -> int: __SCREAMING_SNAKE_CASE = "test_list = [x, add_two(x)]\ntest_list[1]" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_list": [3, 5]} ) __SCREAMING_SNAKE_CASE = "test_dict = {'x': x, 'y': add_two(x)}\ntest_dict['y']" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_dict": {"x": 3, "y": 5}} ) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = "x = 0\nfor i in range(3):\n x = i" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"range": range} , state=UpperCAmelCase__ ) assert result == 2 self.assertDictEqual(UpperCAmelCase__ , {"x": 2, "i": 2} )
54
1
"""simple docstring""" import unittest from transformers.testing_utils import CaptureStdout from transformers.tools.python_interpreter import evaluate def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return x + 2 class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Any ) -> Any: __SCREAMING_SNAKE_CASE = "x = 3" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result == 3 self.assertDictEqual(UpperCAmelCase__ , {"x": 3} ) __SCREAMING_SNAKE_CASE = "x = y" __SCREAMING_SNAKE_CASE = {"y": 5} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 5, "y": 5} ) def UpperCAmelCase_ ( self : Dict ) -> List[str]: __SCREAMING_SNAKE_CASE = "y = add_two(x)" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 5} ) # Won't work without the tool with CaptureStdout() as out: __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result is None assert "tried to execute add_two" in out.out def UpperCAmelCase_ ( self : List[Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = "x = 3" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result == 3 self.assertDictEqual(UpperCAmelCase__ , {"x": 3} ) def UpperCAmelCase_ ( self : str ) -> Any: __SCREAMING_SNAKE_CASE = "test_dict = {'x': x, 'y': add_two(x)}" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 5} ) self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_dict": {"x": 3, "y": 5}} ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = "x = 3\ny = 5" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 5} ) def UpperCAmelCase_ ( self : Any ) -> Any: __SCREAMING_SNAKE_CASE = "text = f'This is x: {x}.'" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == "This is x: 3." self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "text": "This is x: 3."} ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = "if x <= 3:\n y = 2\nelse:\n y = 5" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 2 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 2} ) __SCREAMING_SNAKE_CASE = {"x": 8} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 8, "y": 5} ) def UpperCAmelCase_ ( self : Tuple ) -> str: __SCREAMING_SNAKE_CASE = "test_list = [x, add_two(x)]" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , [3, 5] ) self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_list": [3, 5]} ) def UpperCAmelCase_ ( self : Any ) -> int: __SCREAMING_SNAKE_CASE = "y = x" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result == 3 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 3} ) def UpperCAmelCase_ ( self : Tuple ) -> int: __SCREAMING_SNAKE_CASE = "test_list = [x, add_two(x)]\ntest_list[1]" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_list": [3, 5]} ) __SCREAMING_SNAKE_CASE = "test_dict = {'x': x, 'y': add_two(x)}\ntest_dict['y']" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_dict": {"x": 3, "y": 5}} ) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = "x = 0\nfor i in range(3):\n x = i" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"range": range} , state=UpperCAmelCase__ ) assert result == 2 self.assertDictEqual(UpperCAmelCase__ , {"x": 2, "i": 2} )
54
"""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__ : str = { '''configuration_roformer''': ['''ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''RoFormerConfig''', '''RoFormerOnnxConfig'''], '''tokenization_roformer''': ['''RoFormerTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = ['''RoFormerTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''RoFormerForCausalLM''', '''RoFormerForMaskedLM''', '''RoFormerForMultipleChoice''', '''RoFormerForQuestionAnswering''', '''RoFormerForSequenceClassification''', '''RoFormerForTokenClassification''', '''RoFormerLayer''', '''RoFormerModel''', '''RoFormerPreTrainedModel''', '''load_tf_weights_in_roformer''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = [ '''TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFRoFormerForCausalLM''', '''TFRoFormerForMaskedLM''', '''TFRoFormerForMultipleChoice''', '''TFRoFormerForQuestionAnswering''', '''TFRoFormerForSequenceClassification''', '''TFRoFormerForTokenClassification''', '''TFRoFormerLayer''', '''TFRoFormerModel''', '''TFRoFormerPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FlaxRoFormerForMaskedLM''', '''FlaxRoFormerForMultipleChoice''', '''FlaxRoFormerForQuestionAnswering''', '''FlaxRoFormerForSequenceClassification''', '''FlaxRoFormerForTokenClassification''', '''FlaxRoFormerModel''', '''FlaxRoFormerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys a__ : int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
54
1
"""simple docstring""" import qiskit def UpperCAmelCase__ (lowerCAmelCase_ = 2 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = qubits # Using Aer's simulator __SCREAMING_SNAKE_CASE = qiskit.Aer.get_backend("aer_simulator" ) # Creating a Quantum Circuit acting on the q register __SCREAMING_SNAKE_CASE = qiskit.QuantumCircuit(lowerCAmelCase_ , lowerCAmelCase_ ) # Adding a H gate on qubit 0 (now q0 in superposition) circuit.h(0 ) for i in range(1 , lowerCAmelCase_ ): # Adding CX (CNOT) gate circuit.cx(i - 1 , lowerCAmelCase_ ) # Mapping the quantum measurement to the classical bits circuit.measure(list(range(lowerCAmelCase_ ) ) , list(range(lowerCAmelCase_ ) ) ) # Now measuring any one qubit would affect other qubits to collapse # their super position and have same state as the measured one. # Executing the circuit on the simulator __SCREAMING_SNAKE_CASE = qiskit.execute(lowerCAmelCase_ , lowerCAmelCase_ , shots=1000 ) return job.result().get_counts(lowerCAmelCase_ ) if __name__ == "__main__": print(F"Total count for various states are: {quantum_entanglement(3)}")
54
"""simple docstring""" # Copyright 2022 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. import argparse import os import subprocess from packaging.version import Version, parse from accelerate.commands.config.config_args import default_config_file, load_config_from_file a__ : Tuple = '''Run commands across TPU VMs for initial setup before running `accelerate launch`.''' def UpperCAmelCase__ (lowerCAmelCase_=None ): '''simple docstring''' if subparsers is not None: __SCREAMING_SNAKE_CASE = subparsers.add_parser("tpu-config" , description=_description ) else: __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("Accelerate tpu-config command" , description=_description ) # Core arguments __SCREAMING_SNAKE_CASE = parser.add_argument_group( "Config Arguments" , "Arguments that can be configured through `accelerate config`." ) config_args.add_argument( "--config_file" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , help="Path to the config file to use for accelerate." , ) config_args.add_argument( "--tpu_name" , default=lowerCAmelCase_ , help="The name of the TPU to use. If not specified, will use the TPU specified in the config file." , ) config_args.add_argument( "--tpu_zone" , default=lowerCAmelCase_ , help="The zone of the TPU to use. If not specified, will use the zone specified in the config file." , ) __SCREAMING_SNAKE_CASE = parser.add_argument_group("TPU Arguments" , "Arguments for options ran inside the TPU." ) pod_args.add_argument( "--use_alpha" , action="store_true" , help="Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`." , ) pod_args.add_argument( "--command_file" , default=lowerCAmelCase_ , help="The path to the file containing the commands to run on the pod on startup." , ) pod_args.add_argument( "--command" , action="append" , nargs="+" , help="A command to run on the pod. Can be passed multiple times." , ) pod_args.add_argument( "--install_accelerate" , action="store_true" , help="Whether to install accelerate on the pod. Defaults to False." , ) pod_args.add_argument( "--accelerate_version" , default="latest" , help="The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify 'dev' to install from GitHub." , ) pod_args.add_argument( "--debug" , action="store_true" , help="If set, will print the command that would be run instead of running it." ) if subparsers is not None: parser.set_defaults(func=lowerCAmelCase_ ) return parser def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = None # Get the default from the config file if it exists. if args.config_file is not None or os.path.isfile(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = load_config_from_file(args.config_file ) if not args.command_file and defaults.command_file is not None and not args.command: __SCREAMING_SNAKE_CASE = defaults.command_file if not args.command and defaults.commands is not None: __SCREAMING_SNAKE_CASE = defaults.commands if not args.tpu_name: __SCREAMING_SNAKE_CASE = defaults.tpu_name if not args.tpu_zone: __SCREAMING_SNAKE_CASE = defaults.tpu_zone if args.accelerate_version == "dev": __SCREAMING_SNAKE_CASE = "git+https://github.com/huggingface/accelerate.git" elif args.accelerate_version == "latest": __SCREAMING_SNAKE_CASE = "accelerate -U" elif isinstance(parse(args.accelerate_version ) , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = f"""accelerate=={args.accelerate_version}""" if not args.command_file and not args.command: raise ValueError("You must specify either a command file or a command to run on the pod." ) if args.command_file: with open(args.command_file , "r" ) as f: __SCREAMING_SNAKE_CASE = [f.read().splitlines()] # To turn list of lists into list of strings if isinstance(args.command[0] , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = [line for cmd in args.command for line in cmd] # Default to the shared folder and install accelerate __SCREAMING_SNAKE_CASE = ["cd /usr/share"] if args.install_accelerate: new_cmd += [f"""pip install {args.accelerate_version}"""] new_cmd += args.command __SCREAMING_SNAKE_CASE = "; ".join(lowerCAmelCase_ ) # Then send it to gcloud # Eventually try to use google-api-core to do this instead of subprocess __SCREAMING_SNAKE_CASE = ["gcloud"] if args.use_alpha: cmd += ["alpha"] cmd += [ "compute", "tpus", "tpu-vm", "ssh", args.tpu_name, "--zone", args.tpu_zone, "--command", args.command, "--worker", "all", ] if args.debug: print(f"""Running {' '.join(lowerCAmelCase_ )}""" ) return subprocess.run(lowerCAmelCase_ ) print("Successfully setup pod." ) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = tpu_command_parser() __SCREAMING_SNAKE_CASE = parser.parse_args() tpu_command_launcher(lowerCAmelCase_ )
54
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a__ : int = { '''configuration_blip_2''': [ '''BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Blip2Config''', '''Blip2QFormerConfig''', '''Blip2VisionConfig''', ], '''processing_blip_2''': ['''Blip2Processor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ '''BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Blip2Model''', '''Blip2QFormerModel''', '''Blip2PreTrainedModel''', '''Blip2ForConditionalGeneration''', '''Blip2VisionModel''', ] if TYPE_CHECKING: from .configuration_blip_a import ( BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipaConfig, BlipaQFormerConfig, BlipaVisionConfig, ) from .processing_blip_a import BlipaProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip_a import ( BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST, BlipaForConditionalGeneration, BlipaModel, BlipaPreTrainedModel, BlipaQFormerModel, BlipaVisionModel, ) else: import sys a__ : Optional[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
54
"""simple docstring""" from abc import ABC, abstractmethod from argparse import ArgumentParser class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @staticmethod @abstractmethod def UpperCAmelCase_ ( UpperCAmelCase__ : ArgumentParser ) -> int: raise NotImplementedError() @abstractmethod def UpperCAmelCase_ ( self : int ) -> Optional[int]: raise NotImplementedError()
54
1
"""simple docstring""" import math def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = math.loga(math.sqrt(4 * positive_integer + 1 ) / 2 + 1 / 2 ) return exponent == int(lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ = 1 / 1_2345 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 3 while True: __SCREAMING_SNAKE_CASE = (integer**2 - 1) / 4 # if candidate is an integer, then there is a partition for k if partition_candidate == int(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = int(lowerCAmelCase_ ) total_partitions += 1 if check_partition_perfect(lowerCAmelCase_ ): perfect_partitions += 1 if perfect_partitions > 0: if perfect_partitions / total_partitions < max_proportion: return int(lowerCAmelCase_ ) integer += 1 if __name__ == "__main__": print(F"{solution() = }")
54
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def UpperCAmelCase__ (lowerCAmelCase_ = 100_0000 , lowerCAmelCase_ = 10 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = defaultdict(lowerCAmelCase_ ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: __SCREAMING_SNAKE_CASE = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: __SCREAMING_SNAKE_CASE = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(lowerCAmelCase_ , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 10 ) if __name__ == "__main__": print(F"{solution() = }")
54
1
"""simple docstring""" from functools import lru_cache @lru_cache def UpperCAmelCase__ (lowerCAmelCase_ ): '''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()
54
"""simple docstring""" import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html a__ : List[str] = '''platform''' import jax import jax.numpy as jnp import numpy as np from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel @require_flax class UpperCamelCase_ : """simple docstring""" snake_case__ : Dict = PegasusConfig snake_case__ : Union[str, Any] = {} snake_case__ : Any = "gelu" def __init__( self : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int=1_3 , UpperCAmelCase__ : Optional[int]=7 , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : Any=False , UpperCAmelCase__ : List[Any]=9_9 , UpperCAmelCase__ : int=3_2 , UpperCAmelCase__ : Dict=5 , UpperCAmelCase__ : Optional[int]=4 , UpperCAmelCase__ : List[Any]=3_7 , UpperCAmelCase__ : int=0.1 , UpperCAmelCase__ : int=0.1 , UpperCAmelCase__ : List[Any]=2_0 , UpperCAmelCase__ : int=2 , UpperCAmelCase__ : List[Any]=1 , UpperCAmelCase__ : Optional[Any]=0 , ) -> Any: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = eos_token_id __SCREAMING_SNAKE_CASE = pad_token_id __SCREAMING_SNAKE_CASE = bos_token_id def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ).clip(3 , self.vocab_size ) __SCREAMING_SNAKE_CASE = np.expand_dims(np.array([self.eos_token_id] * self.batch_size ) , 1 ) __SCREAMING_SNAKE_CASE = np.concatenate([input_ids, eos_tensor] , axis=1 ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) __SCREAMING_SNAKE_CASE = prepare_pegasus_inputs_dict(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) return config, inputs_dict def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] ) -> str: __SCREAMING_SNAKE_CASE = 2_0 __SCREAMING_SNAKE_CASE = model_class_name(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.encode(inputs_dict["input_ids"] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) __SCREAMING_SNAKE_CASE = model.init_cache(decoder_input_ids.shape[0] , UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="i4" ) __SCREAMING_SNAKE_CASE = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, :-1] , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, -1:] , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , past_key_values=outputs_cache.past_key_values , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = 2_0 __SCREAMING_SNAKE_CASE = model_class_name(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.encode(inputs_dict["input_ids"] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) __SCREAMING_SNAKE_CASE = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) __SCREAMING_SNAKE_CASE = model.init_cache(decoder_input_ids.shape[0] , UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, :-1] , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, -1:] , UpperCAmelCase__ , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=UpperCAmelCase__ , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=None , lowerCAmelCase_=None , ): '''simple docstring''' if attention_mask is None: __SCREAMING_SNAKE_CASE = np.not_equal(lowerCAmelCase_ , config.pad_token_id ).astype(np.inta ) if decoder_attention_mask is None: __SCREAMING_SNAKE_CASE = np.concatenate( [ np.ones(decoder_input_ids[:, :1].shape , dtype=np.inta ), np.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ).astype(np.inta ), ] , axis=-1 , ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, } @require_flax class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Tuple = ( ( FlaxPegasusForConditionalGeneration, FlaxPegasusModel, ) if is_flax_available() else () ) snake_case__ : Union[str, Any] = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else () snake_case__ : Tuple = True snake_case__ : Union[str, Any] = False snake_case__ : int = False snake_case__ : List[Any] = False def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = FlaxPegasusModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : Tuple ) -> Optional[int]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Tuple: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __SCREAMING_SNAKE_CASE = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) @jax.jit def encode_jitted(UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : int=None , **UpperCAmelCase__ : int ): return model.encode(input_ids=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) with self.subTest("JIT Enabled" ): __SCREAMING_SNAKE_CASE = encode_jitted(**UpperCAmelCase__ ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): __SCREAMING_SNAKE_CASE = encode_jitted(**UpperCAmelCase__ ).to_tuple() self.assertEqual(len(UpperCAmelCase__ ) , len(UpperCAmelCase__ ) ) for jitted_output, output in zip(UpperCAmelCase__ , UpperCAmelCase__ ): self.assertEqual(jitted_output.shape , output.shape ) def UpperCAmelCase_ ( self : Tuple ) -> Any: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.encode(inputs_dict["input_ids"] , inputs_dict["attention_mask"] ) __SCREAMING_SNAKE_CASE = { "decoder_input_ids": inputs_dict["decoder_input_ids"], "decoder_attention_mask": inputs_dict["decoder_attention_mask"], "encoder_outputs": encoder_outputs, } @jax.jit def decode_jitted(UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] ): return model.decode( decoder_input_ids=UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , encoder_outputs=UpperCAmelCase__ , ) with self.subTest("JIT Enabled" ): __SCREAMING_SNAKE_CASE = decode_jitted(**UpperCAmelCase__ ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): __SCREAMING_SNAKE_CASE = decode_jitted(**UpperCAmelCase__ ).to_tuple() self.assertEqual(len(UpperCAmelCase__ ) , len(UpperCAmelCase__ ) ) for jitted_output, output in zip(UpperCAmelCase__ , UpperCAmelCase__ ): self.assertEqual(jitted_output.shape , output.shape ) @slow def UpperCAmelCase_ ( self : Dict ) -> Tuple: for model_class_name in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class_name.from_pretrained("google/pegasus-large" , from_pt=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.ones((1, 1) ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : Optional[int] ) -> List[Any]: __SCREAMING_SNAKE_CASE = FlaxPegasusForConditionalGeneration.from_pretrained("google/pegasus-xsum" ) __SCREAMING_SNAKE_CASE = PegasusTokenizer.from_pretrained("google/pegasus-xsum" ) __SCREAMING_SNAKE_CASE = [ " PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.", " The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" ", ] __SCREAMING_SNAKE_CASE = [ "California's largest electricity provider has turned off power to hundreds of thousands of customers.", "Pop group N-Dubz have revealed they were surprised to get four nominations for this year's Mobo Awards.", ] __SCREAMING_SNAKE_CASE = tokenizer(UpperCAmelCase__ , return_tensors="np" , truncation=UpperCAmelCase__ , max_length=5_1_2 , padding=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate(**UpperCAmelCase__ , num_beams=2 ).sequences __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ ) assert tgt_text == decoded
54
1
"""simple docstring""" import sys def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [[0 for x in range(lowerCAmelCase_ )] for x in range(lowerCAmelCase_ )] __SCREAMING_SNAKE_CASE = [[0 for x in range(lowerCAmelCase_ )] for x in range(lowerCAmelCase_ )] for chain_length in range(2 , lowerCAmelCase_ ): for a in range(1 , n - chain_length + 1 ): __SCREAMING_SNAKE_CASE = a + chain_length - 1 __SCREAMING_SNAKE_CASE = sys.maxsize for c in range(lowerCAmelCase_ , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = ( matrix[a][c] + matrix[c + 1][b] + array[a - 1] * array[c] * array[b] ) if cost < matrix[a][b]: __SCREAMING_SNAKE_CASE = cost __SCREAMING_SNAKE_CASE = c return matrix, sol def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if i == j: print("A" + str(lowerCAmelCase_ ) , end=" " ) else: print("(" , end=" " ) print_optiomal_solution(lowerCAmelCase_ , lowerCAmelCase_ , optimal_solution[i][j] ) print_optiomal_solution(lowerCAmelCase_ , optimal_solution[i][j] + 1 , lowerCAmelCase_ ) print(")" , end=" " ) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = [30, 35, 15, 5, 10, 20, 25] __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) # Size of matrix created from above array will be # 30*35 35*15 15*5 5*10 10*20 20*25 __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = matrix_chain_order(lowerCAmelCase_ ) print("No. of Operation required: " + str(matrix[1][n - 1] ) ) print_optiomal_solution(lowerCAmelCase_ , 1 , n - 1 ) if __name__ == "__main__": main()
54
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ = 100_0000 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = set(range(3 , lowerCAmelCase_ , 2 ) ) primes.add(2 ) for p in range(3 , lowerCAmelCase_ , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , lowerCAmelCase_ , lowerCAmelCase_ ) ) ) __SCREAMING_SNAKE_CASE = [float(lowerCAmelCase_ ) for n in range(limit + 1 )] for p in primes: for n in range(lowerCAmelCase_ , limit + 1 , lowerCAmelCase_ ): phi[n] *= 1 - 1 / p return int(sum(phi[2:] ) ) if __name__ == "__main__": print(F"{solution() = }")
54
1
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.activations import gelu_new, gelu_python, get_activation @require_torch class lowercase_ ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" a = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) a = get_activation('''gelu''' ) self.assertTrue(torch.allclose(gelu_python(__UpperCAmelCase ) , torch_builtin(__UpperCAmelCase ) ) ) self.assertFalse(torch.allclose(gelu_python(__UpperCAmelCase ) , gelu_new(__UpperCAmelCase ) ) ) def __lowerCAmelCase ( self : Optional[Any] ) ->List[Any]: """simple docstring""" a = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) a = get_activation('''gelu''' ) a = get_activation('''gelu_10''' ) a = torch_builtin(__UpperCAmelCase ) a = geluaa(__UpperCAmelCase ) a = torch.where(y_gelu_aa < 10.0 , 1 , 0 ) self.assertTrue(torch.max(__UpperCAmelCase ).item() == 10.0 ) self.assertTrue(torch.allclose(y_gelu * clipped_mask , y_gelu_aa * clipped_mask ) ) def __lowerCAmelCase ( self : List[Any] ) ->Optional[int]: """simple docstring""" get_activation('''gelu''' ) get_activation('''gelu_10''' ) get_activation('''gelu_fast''' ) get_activation('''gelu_new''' ) get_activation('''gelu_python''' ) get_activation('''gelu_pytorch_tanh''' ) get_activation('''linear''' ) get_activation('''mish''' ) get_activation('''quick_gelu''' ) get_activation('''relu''' ) get_activation('''sigmoid''' ) get_activation('''silu''' ) get_activation('''swish''' ) get_activation('''tanh''' ) with self.assertRaises(__UpperCAmelCase ): get_activation('''bogus''' ) with self.assertRaises(__UpperCAmelCase ): get_activation(__UpperCAmelCase ) def __lowerCAmelCase ( self : Any ) ->str: """simple docstring""" a = get_activation('''gelu''' ) a = 1 a = get_activation('''gelu''' ) self.assertEqual(acta.a , 1 ) with self.assertRaises(__UpperCAmelCase ): a = acta.a
0
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if upper_limit < 0: raise ValueError("Limit for the Catalan sequence must be ≥ 0" ) __SCREAMING_SNAKE_CASE = [0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 __SCREAMING_SNAKE_CASE = 1 if upper_limit > 0: __SCREAMING_SNAKE_CASE = 1 # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i for i in range(2 , upper_limit + 1 ): for j in range(lowerCAmelCase_ ): catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1] return catalan_list if __name__ == "__main__": print('''\n********* Catalan Numbers Using Dynamic Programming ************\n''') print('''\n*** Enter -1 at any time to quit ***''') print('''\nEnter the upper limit (≥ 0) for the Catalan number sequence: ''', end='''''') try: while True: a__ : List[str] = int(input().strip()) if N < 0: print('''\n********* Goodbye!! ************''') break else: print(F"The Catalan numbers from 0 through {N} are:") print(catalan_numbers(N)) print('''Try another upper limit for the sequence: ''', end='''''') except (NameError, ValueError): print('''\n********* Invalid input, goodbye! ************\n''') import doctest doctest.testmod()
54
0
'''simple docstring''' import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available from transformers.models.gpta.tokenization_gpta import GPTaTokenizer from transformers.testing_utils import require_keras_nlp, require_tf, slow if is_tf_available(): import tensorflow as tf if is_keras_nlp_available(): from transformers.models.gpta import TFGPTaTokenizer SCREAMING_SNAKE_CASE_: Union[str, Any] =['gpt2'] SCREAMING_SNAKE_CASE_: Optional[int] ='gpt2' if is_tf_available(): class __A ( tf.Module ): def __init__(self : Union[str, Any] , __a : Union[str, Any] ): super().__init__() UpperCAmelCase_ = tokenizer UpperCAmelCase_ = AutoConfig.from_pretrained(__a ) UpperCAmelCase_ = TFGPTaLMHeadModel.from_config(__a ) @tf.function(input_signature=(tf.TensorSpec((None,) , tf.string , name="text" ),) ) def _lowercase (self : Tuple , __a : List[str] ): UpperCAmelCase_ = self.tokenizer(__a ) UpperCAmelCase_ = tokenized["input_ids"].to_tensor() UpperCAmelCase_ = tf.cast(input_ids_dense > 0 , tf.intaa ) # input_mask = tf.reshape(input_mask, [-1, MAX_SEQ_LEN]) UpperCAmelCase_ = self.model(input_ids=__a , attention_mask=__a )["logits"] return outputs @require_tf @require_keras_nlp class __A ( unittest.TestCase ): def _lowercase (self : List[Any] ): super().setUp() UpperCAmelCase_ = [GPTaTokenizer.from_pretrained(__a ) for checkpoint in (TOKENIZER_CHECKPOINTS)] UpperCAmelCase_ = [TFGPTaTokenizer.from_pretrained(__a ) for checkpoint in TOKENIZER_CHECKPOINTS] assert len(self.tokenizers ) == len(self.tf_tokenizers ) UpperCAmelCase_ = [ "This is a straightforward English test sentence.", "This one has some weird characters\rto\nsee\r\nif those\u00E9break things.", "Now we're going to add some Chinese: 一 二 三 一二三", "And some much more rare Chinese: 齉 堃 齉堃", "Je vais aussi écrire en français pour tester les accents", "Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ", ] UpperCAmelCase_ = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def _lowercase (self : List[str] ): for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in self.test_sentences: UpperCAmelCase_ = tokenizer([test_inputs] , return_tensors="tf" ) UpperCAmelCase_ = tf_tokenizer([test_inputs] ) for key in python_outputs.keys(): # convert them to numpy to avoid messing with ragged tensors UpperCAmelCase_ = python_outputs[key].numpy() UpperCAmelCase_ = tf_outputs[key].numpy() self.assertTrue(tf.reduce_all(python_outputs_values.shape == tf_outputs_values.shape ) ) self.assertTrue(tf.reduce_all(tf.cast(__a , tf.intaa ) == tf_outputs_values ) ) @slow def _lowercase (self : Optional[Any] ): for tf_tokenizer in self.tf_tokenizers: UpperCAmelCase_ = tf.function(__a ) for test_inputs in self.test_sentences: UpperCAmelCase_ = tf.constant(__a ) UpperCAmelCase_ = compiled_tokenizer(__a ) UpperCAmelCase_ = tf_tokenizer(__a ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def _lowercase (self : Tuple ): for tf_tokenizer in self.tf_tokenizers: UpperCAmelCase_ = ModelToSave(tokenizer=__a ) UpperCAmelCase_ = tf.convert_to_tensor([self.test_sentences[0]] ) UpperCAmelCase_ = model.serving(__a ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: UpperCAmelCase_ = Path(__a ) / "saved.model" tf.saved_model.save(__a , __a , signatures={"serving_default": model.serving} ) UpperCAmelCase_ = tf.saved_model.load(__a ) UpperCAmelCase_ = loaded_model.signatures["serving_default"](__a )["output_0"] # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertTrue(tf.reduce_all(out == loaded_output ) ) @slow def _lowercase (self : Optional[int] ): for tf_tokenizer in self.tf_tokenizers: UpperCAmelCase_ = tf.convert_to_tensor([self.test_sentences[0]] ) UpperCAmelCase_ = tf_tokenizer(__a ) # Build model with some sample inputs UpperCAmelCase_ = tf_tokenizer.get_config() UpperCAmelCase_ = TFGPTaTokenizer.from_config(__a ) UpperCAmelCase_ = model_from_config(__a ) for key in from_config_output.keys(): self.assertTrue(tf.reduce_all(from_config_output[key] == out[key] ) ) @slow def _lowercase (self : Tuple ): for tf_tokenizer in self.tf_tokenizers: # for the test to run UpperCAmelCase_ = 123123 for max_length in [3, 5, 1024]: UpperCAmelCase_ = tf.convert_to_tensor([self.test_sentences[0]] ) UpperCAmelCase_ = tf_tokenizer(__a , max_length=__a ) UpperCAmelCase_ = out["input_ids"].numpy().shape[1] assert out_length == max_length
1
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from itertools import chain from typing import Optional, Union import datasets import numpy as np import torch from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.tokenization_utils_base import PreTrainedTokenizerBase from transformers.trainer_utils import get_last_checkpoint from transformers.utils import PaddingStrategy, check_min_version, send_example_telemetry # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('''4.31.0''') a__ : Tuple = logging.getLogger(__name__) @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Pretrained config name or path if not the same as model_name"}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} , ) snake_case__ : str = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : Optional[str] = field(default=UpperCamelCase , metadata={"help": "The input training data file (a text file)."}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."} , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={"help": "Overwrite the cached training and evaluation sets"}) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={"help": "The number of processes to use for the preprocessing."} , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "The maximum total input sequence length after tokenization. If passed, sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={ "help": ( "Whether to pad all samples to the maximum sentence length. " "If False, will pad the samples dynamically when batching to the maximum length in the batch. More " "efficient on GPU but very bad for TPU." ) } , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: if self.train_file is not None: __SCREAMING_SNAKE_CASE = self.train_file.split("." )[-1] assert extension in ["csv", "json"], "`train_file` should be a csv or a json file." if self.validation_file is not None: __SCREAMING_SNAKE_CASE = self.validation_file.split("." )[-1] assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file." @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : PreTrainedTokenizerBase snake_case__ : Union[bool, str, PaddingStrategy] = True snake_case__ : Optional[int] = None snake_case__ : Optional[int] = None def __call__( self : int , UpperCAmelCase__ : Any ) -> str: __SCREAMING_SNAKE_CASE = "label" if "label" in features[0].keys() else "labels" __SCREAMING_SNAKE_CASE = [feature.pop(UpperCAmelCase__ ) for feature in features] __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = len(features[0]["input_ids"] ) __SCREAMING_SNAKE_CASE = [ [{k: v[i] for k, v in feature.items()} for i in range(UpperCAmelCase__ )] for feature in features ] __SCREAMING_SNAKE_CASE = list(chain(*UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = self.tokenizer.pad( UpperCAmelCase__ , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="pt" , ) # Un-flatten __SCREAMING_SNAKE_CASE = {k: v.view(UpperCAmelCase__ , UpperCAmelCase__ , -1 ) for k, v in batch.items()} # Add back labels __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ , dtype=torch.intaa ) return batch def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("run_swag" , lowerCAmelCase_ , lowerCAmelCase_ ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() __SCREAMING_SNAKE_CASE = training_args.get_process_log_level() logger.setLevel(lowerCAmelCase_ ) datasets.utils.logging.set_verbosity(lowerCAmelCase_ ) transformers.utils.logging.set_verbosity(lowerCAmelCase_ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + f"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(f"""Training/evaluation parameters {training_args}""" ) # Detecting last checkpoint. __SCREAMING_SNAKE_CASE = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: __SCREAMING_SNAKE_CASE = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. """ "Use --overwrite_output_dir to overcome." ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.train_file is not None or data_args.validation_file is not None: __SCREAMING_SNAKE_CASE = {} if data_args.train_file is not None: __SCREAMING_SNAKE_CASE = data_args.train_file if data_args.validation_file is not None: __SCREAMING_SNAKE_CASE = data_args.validation_file __SCREAMING_SNAKE_CASE = data_args.train_file.split("." )[-1] __SCREAMING_SNAKE_CASE = load_dataset( lowerCAmelCase_ , data_files=lowerCAmelCase_ , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) else: # Downloading and loading the swag dataset from the hub. __SCREAMING_SNAKE_CASE = load_dataset( "swag" , "regular" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) __SCREAMING_SNAKE_CASE = 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_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) __SCREAMING_SNAKE_CASE = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # When using your own dataset or a different dataset from swag, you will probably need to change this. __SCREAMING_SNAKE_CASE = [f"""ending{i}""" for i in range(4 )] __SCREAMING_SNAKE_CASE = "sent1" __SCREAMING_SNAKE_CASE = "sent2" if data_args.max_seq_length is None: __SCREAMING_SNAKE_CASE = tokenizer.model_max_length if max_seq_length > 1024: logger.warning( "The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value" " of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can" " override this default with `--block_size xxx`." ) __SCREAMING_SNAKE_CASE = 1024 else: if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( f"""The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the""" f"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.""" ) __SCREAMING_SNAKE_CASE = min(data_args.max_seq_length , tokenizer.model_max_length ) # Preprocessing the datasets. def preprocess_function(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = [[context] * 4 for context in examples[context_name]] __SCREAMING_SNAKE_CASE = examples[question_header_name] __SCREAMING_SNAKE_CASE = [ [f"""{header} {examples[end][i]}""" for end in ending_names] for i, header in enumerate(lowerCAmelCase_ ) ] # Flatten out __SCREAMING_SNAKE_CASE = list(chain(*lowerCAmelCase_ ) ) __SCREAMING_SNAKE_CASE = list(chain(*lowerCAmelCase_ ) ) # Tokenize __SCREAMING_SNAKE_CASE = tokenizer( lowerCAmelCase_ , lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=lowerCAmelCase_ , padding="max_length" if data_args.pad_to_max_length else False , ) # Un-flatten return {k: [v[i : i + 4] for i in range(0 , len(lowerCAmelCase_ ) , 4 )] for k, v in tokenized_examples.items()} if training_args.do_train: if "train" not in raw_datasets: raise ValueError("--do_train requires a train dataset" ) __SCREAMING_SNAKE_CASE = raw_datasets["train"] if data_args.max_train_samples is not None: __SCREAMING_SNAKE_CASE = min(len(lowerCAmelCase_ ) , data_args.max_train_samples ) __SCREAMING_SNAKE_CASE = train_dataset.select(range(lowerCAmelCase_ ) ) with training_args.main_process_first(desc="train dataset map pre-processing" ): __SCREAMING_SNAKE_CASE = train_dataset.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , ) if training_args.do_eval: if "validation" not in raw_datasets: raise ValueError("--do_eval requires a validation dataset" ) __SCREAMING_SNAKE_CASE = raw_datasets["validation"] if data_args.max_eval_samples is not None: __SCREAMING_SNAKE_CASE = min(len(lowerCAmelCase_ ) , data_args.max_eval_samples ) __SCREAMING_SNAKE_CASE = eval_dataset.select(range(lowerCAmelCase_ ) ) with training_args.main_process_first(desc="validation dataset map pre-processing" ): __SCREAMING_SNAKE_CASE = eval_dataset.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , ) # Data collator __SCREAMING_SNAKE_CASE = ( default_data_collator if data_args.pad_to_max_length else DataCollatorForMultipleChoice(tokenizer=lowerCAmelCase_ , pad_to_multiple_of=8 if training_args.fpaa else None ) ) # Metric def compute_metrics(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = eval_predictions __SCREAMING_SNAKE_CASE = np.argmax(lowerCAmelCase_ , axis=1 ) return {"accuracy": (preds == label_ids).astype(np.floataa ).mean().item()} # Initialize our Trainer __SCREAMING_SNAKE_CASE = Trainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , tokenizer=lowerCAmelCase_ , data_collator=lowerCAmelCase_ , compute_metrics=lowerCAmelCase_ , ) # Training if training_args.do_train: __SCREAMING_SNAKE_CASE = None if training_args.resume_from_checkpoint is not None: __SCREAMING_SNAKE_CASE = training_args.resume_from_checkpoint elif last_checkpoint is not None: __SCREAMING_SNAKE_CASE = last_checkpoint __SCREAMING_SNAKE_CASE = trainer.train(resume_from_checkpoint=lowerCAmelCase_ ) trainer.save_model() # Saves the tokenizer too for easy upload __SCREAMING_SNAKE_CASE = train_result.metrics __SCREAMING_SNAKE_CASE = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(lowerCAmelCase_ ) ) __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ , len(lowerCAmelCase_ ) ) trainer.log_metrics("train" , lowerCAmelCase_ ) trainer.save_metrics("train" , lowerCAmelCase_ ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("*** Evaluate ***" ) __SCREAMING_SNAKE_CASE = trainer.evaluate() __SCREAMING_SNAKE_CASE = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ , len(lowerCAmelCase_ ) ) trainer.log_metrics("eval" , lowerCAmelCase_ ) trainer.save_metrics("eval" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { "finetuned_from": model_args.model_name_or_path, "tasks": "multiple-choice", "dataset_tags": "swag", "dataset_args": "regular", "dataset": "SWAG", "language": "en", } if training_args.push_to_hub: trainer.push_to_hub(**lowerCAmelCase_ ) else: trainer.create_model_card(**lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' main() if __name__ == "__main__": main()
54
0
'''simple docstring''' def _SCREAMING_SNAKE_CASE (A ) -> bool: """simple docstring""" return sum(i for i in range(1 , number // 2 + 1 ) if number % i == 0 ) == number if __name__ == "__main__": print('Program to check whether a number is a Perfect number or not...') lowerCamelCase : Union[str, Any] = int(input('Enter number: ').strip()) print(f"""{number} is {'' if perfect(number) else 'not '}a Perfect Number.""")
2
"""simple docstring""" from PIL import Image def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = image.size __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = image.load() for i in range(lowerCAmelCase_ ): for j in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = pixels[j, i] mean += pixel mean //= width * height for j in range(lowerCAmelCase_ ): for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = 255 if pixels[i, j] > mean else 0 return image if __name__ == "__main__": a__ : List[str] = mean_threshold(Image.open('''path_to_image''').convert('''L''')) image.save('''output_image_path''')
54
0
'''simple docstring''' import pytest lowercase : Dict = '__dummy_dataset1__' lowercase : Optional[int] = '\nimport json\nimport os\n\nimport datasets\n\n\nREPO_URL = "https://huggingface.co/datasets/albertvillanova/tests-raw-jsonl/resolve/main/"\nURLS = {"train": REPO_URL + "wikiann-bn-train.jsonl", "validation": REPO_URL + "wikiann-bn-validation.jsonl"}\n\n\nclass __DummyDataset1__(datasets.GeneratorBasedBuilder):\n\n def _info(self):\n features = datasets.Features(\n {\n "tokens": datasets.Sequence(datasets.Value("string")),\n "ner_tags": datasets.Sequence(\n datasets.features.ClassLabel(\n names=[\n "O",\n "B-PER",\n "I-PER",\n "B-ORG",\n "I-ORG",\n "B-LOC",\n "I-LOC",\n ]\n )\n ),\n "langs": datasets.Sequence(datasets.Value("string")),\n "spans": datasets.Sequence(datasets.Value("string")),\n }\n )\n return datasets.DatasetInfo(features=features)\n\n def _split_generators(self, dl_manager):\n dl_path = dl_manager.download(URLS)\n return [\n datasets.SplitGenerator(datasets.Split.TRAIN, gen_kwargs={"filepath": dl_path["train"]}),\n datasets.SplitGenerator(datasets.Split.VALIDATION, gen_kwargs={"filepath": dl_path["validation"]}),\n ]\n\n def _generate_examples(self, filepath):\n with open(filepath, "r", encoding="utf-8") as f:\n for i, line in enumerate(f):\n yield i, json.loads(line)\n' @pytest.fixture def lowerCAmelCase_ ( ): '''simple docstring''' return DATASET_LOADING_SCRIPT_NAME @pytest.fixture def lowerCAmelCase_ ( ): '''simple docstring''' return DATASET_LOADING_SCRIPT_CODE @pytest.fixture def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' A : Optional[int] = dataset_loading_script_name A : Union[str, Any] = tmp_path / '''datasets''' / script_name script_dir.mkdir(parents=snake_case__ ) A : Union[str, Any] = script_dir / F'{script_name}.py' with open(snake_case__ , '''w''' ) as f: f.write(snake_case__ ) return str(snake_case__ )
3
"""simple docstring""" from jiwer import compute_measures import datasets a__ : Optional[int] = '''\ @inproceedings{inproceedings, author = {Morris, Andrew and Maier, Viktoria and Green, Phil}, year = {2004}, month = {01}, pages = {}, title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.} } ''' a__ : List[str] = '''\ Word error rate (WER) is a common metric of the performance of an automatic speech recognition system. The general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort. This problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate. Word error rate can then be computed as: WER = (S + D + I) / N = (S + D + I) / (S + D + C) where S is the number of substitutions, D is the number of deletions, I is the number of insertions, C is the number of correct words, N is the number of words in the reference (N=S+D+C). This value indicates the average number of errors per reference word. The lower the value, the better the performance of the ASR system with a WER of 0 being a perfect score. ''' a__ : Dict = ''' Compute WER score of transcribed segments against references. Args: references: List of references for each speech input. predictions: List of transcriptions to score. concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively. Returns: (float): the word error rate Examples: >>> predictions = ["this is the prediction", "there is an other sample"] >>> references = ["this is the reference", "there is another one"] >>> wer = datasets.load_metric("wer") >>> wer_score = wer.compute(predictions=predictions, references=references) >>> print(wer_score) 0.5 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class UpperCamelCase_ ( datasets.Metric): """simple docstring""" def UpperCAmelCase_ ( self : List[Any] ) -> str: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , codebase_urls=["https://github.com/jitsi/jiwer/"] , reference_urls=[ "https://en.wikipedia.org/wiki/Word_error_rate", ] , ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : Any=False ) -> Optional[int]: if concatenate_texts: return compute_measures(UpperCAmelCase__ , UpperCAmelCase__ )["wer"] else: __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for prediction, reference in zip(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = compute_measures(UpperCAmelCase__ , UpperCAmelCase__ ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
54
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __snake_case =logging.get_logger(__name__) __snake_case ={ """facebook/dpr-ctx_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/config.json""" ), """facebook/dpr-question_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/config.json""" ), """facebook/dpr-reader-single-nq-base""": ( """https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/config.json""" ), """facebook/dpr-ctx_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/config.json""" ), """facebook/dpr-question_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/config.json""" ), """facebook/dpr-reader-multiset-base""": ( """https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/config.json""" ), } class UpperCAmelCase_ ( __lowercase ): lowerCamelCase : List[str] = '''dpr''' def __init__( self : List[Any] , UpperCAmelCase__ : Tuple=3_0_5_2_2 , UpperCAmelCase__ : Tuple=7_6_8 , UpperCAmelCase__ : str=1_2 , UpperCAmelCase__ : str=1_2 , UpperCAmelCase__ : Tuple=3_0_7_2 , UpperCAmelCase__ : Any="gelu" , UpperCAmelCase__ : List[Any]=0.1 , UpperCAmelCase__ : Union[str, Any]=0.1 , UpperCAmelCase__ : Optional[int]=5_1_2 , UpperCAmelCase__ : Any=2 , UpperCAmelCase__ : Union[str, Any]=0.02 , UpperCAmelCase__ : Dict=1E-12 , UpperCAmelCase__ : Tuple=0 , UpperCAmelCase__ : Union[str, Any]="absolute" , UpperCAmelCase__ : int = 0 , **UpperCAmelCase__ : Union[str, Any] , ) -> List[str]: super().__init__(pad_token_id=UpperCAmelCase__ , **UpperCAmelCase__ ) lowerCAmelCase = vocab_size lowerCAmelCase = hidden_size lowerCAmelCase = num_hidden_layers lowerCAmelCase = num_attention_heads lowerCAmelCase = hidden_act lowerCAmelCase = intermediate_size lowerCAmelCase = hidden_dropout_prob lowerCAmelCase = attention_probs_dropout_prob lowerCAmelCase = max_position_embeddings lowerCAmelCase = type_vocab_size lowerCAmelCase = initializer_range lowerCAmelCase = layer_norm_eps lowerCAmelCase = projection_dim lowerCAmelCase = position_embedding_type
4
"""simple docstring""" from __future__ import annotations import pandas as pd def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [0] * no_of_processes __SCREAMING_SNAKE_CASE = [0] * no_of_processes # Copy the burst time into remaining_time[] for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = burst_time[i] __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 9_9999_9999 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = False # Process until all processes are completed while complete != no_of_processes: for j in range(lowerCAmelCase_ ): if arrival_time[j] <= increment_time and remaining_time[j] > 0: if remaining_time[j] < minm: __SCREAMING_SNAKE_CASE = remaining_time[j] __SCREAMING_SNAKE_CASE = j __SCREAMING_SNAKE_CASE = True if not check: increment_time += 1 continue remaining_time[short] -= 1 __SCREAMING_SNAKE_CASE = remaining_time[short] if minm == 0: __SCREAMING_SNAKE_CASE = 9_9999_9999 if remaining_time[short] == 0: complete += 1 __SCREAMING_SNAKE_CASE = False # Find finish time of current process __SCREAMING_SNAKE_CASE = increment_time + 1 # Calculate waiting time __SCREAMING_SNAKE_CASE = finish_time - arrival_time[short] __SCREAMING_SNAKE_CASE = finar - burst_time[short] if waiting_time[short] < 0: __SCREAMING_SNAKE_CASE = 0 # Increment time increment_time += 1 return waiting_time def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [0] * no_of_processes for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = burst_time[i] + waiting_time[i] return turn_around_time def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = total_waiting_time + waiting_time[i] __SCREAMING_SNAKE_CASE = total_turn_around_time + turn_around_time[i] print(f"""Average waiting time = {total_waiting_time / no_of_processes:.5f}""" ) print("Average turn around time =" , total_turn_around_time / no_of_processes ) if __name__ == "__main__": print('''Enter how many process you want to analyze''') a__ : Optional[Any] = int(input()) a__ : Optional[int] = [0] * no_of_processes a__ : int = [0] * no_of_processes a__ : List[Any] = list(range(1, no_of_processes + 1)) for i in range(no_of_processes): print('''Enter the arrival time and burst time for process:--''' + str(i + 1)) a__ , a__ : Tuple = map(int, input().split()) a__ : int = calculate_waitingtime(arrival_time, burst_time, no_of_processes) a__ : Dict = burst_time a__ : Any = no_of_processes a__ : Optional[int] = waiting_time a__ : Union[str, Any] = calculate_turnaroundtime(bt, n, wt) calculate_average_times(waiting_time, turn_around_time, no_of_processes) a__ : str = pd.DataFrame( list(zip(processes, burst_time, arrival_time, waiting_time, turn_around_time)), columns=[ '''Process''', '''BurstTime''', '''ArrivalTime''', '''WaitingTime''', '''TurnAroundTime''', ], ) # Printing the dataFrame pd.set_option('''display.max_rows''', fcfs.shape[0] + 1) print(fcfs)
54
0
from __future__ import annotations from bisect import bisect_left from functools import total_ordering from heapq import merge @total_ordering class lowerCamelCase__ ( lowerCAmelCase): def __lt__(self , UpperCAmelCase ) -> Union[str, Any]: return self[-1] < other[-1] def __eq__(self , UpperCAmelCase ) -> List[Any]: return self[-1] == other[-1] def UpperCAmelCase_ ( __snake_case ) -> list: """simple docstring""" _lowercase =[] # sort into stacks for element in collection: _lowercase =Stack([element] ) _lowercase =bisect_left(__snake_case , __snake_case ) if i != len(__snake_case ): stacks[i].append(__snake_case ) else: stacks.append(__snake_case ) # use a heap-based merge to merge stack efficiently _lowercase =merge(*(reversed(__snake_case ) for stack in stacks) ) return collection if __name__ == "__main__": UpperCAmelCase__ = input('''Enter numbers separated by a comma:\n''').strip() UpperCAmelCase__ = [int(item) for item in user_input.split(''',''')] print(patience_sort(unsorted))
5
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy a__ : Union[str, Any] = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : float , **UpperCAmelCase__ : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = feature_size __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = padding_value __SCREAMING_SNAKE_CASE = kwargs.pop("padding_side" , "right" ) __SCREAMING_SNAKE_CASE = kwargs.pop("return_attention_mask" , UpperCAmelCase__ ) super().__init__(**UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[ BatchFeature, List[BatchFeature], Dict[str, BatchFeature], Dict[str, List[BatchFeature]], List[Dict[str, BatchFeature]], ] , UpperCAmelCase__ : Union[bool, str, PaddingStrategy] = True , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[Union[str, TensorType]] = None , ) -> BatchFeature: # If we have a list of dicts, let's convert it in a dict of lists # We do this to allow using this method as a collate_fn function in PyTorch Dataloader if isinstance(UpperCAmelCase__ , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): __SCREAMING_SNAKE_CASE = { key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( "You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`" F""" to this method that includes {self.model_input_names[0]}, but you provided""" F""" {list(processed_features.keys() )}""" ) __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] __SCREAMING_SNAKE_CASE = ( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(UpperCAmelCase__ ) == 0: if return_attention_mask: __SCREAMING_SNAKE_CASE = [] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch __SCREAMING_SNAKE_CASE = required_input[0] if isinstance(UpperCAmelCase__ , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. __SCREAMING_SNAKE_CASE = 0 while len(required_input[index] ) == 0: index += 1 if index < len(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = required_input[index][0] if return_tensors is None: if is_tf_tensor(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = "tf" elif is_torch_tensor(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = "pt" elif isinstance(UpperCAmelCase__ , (int, float, list, tuple, np.ndarray) ): __SCREAMING_SNAKE_CASE = "np" else: raise ValueError( F"""type of {first_element} unknown: {type(UpperCAmelCase__ )}. """ "Should be one of a python, numpy, pytorch or tensorflow object." ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): __SCREAMING_SNAKE_CASE = to_numpy(UpperCAmelCase__ ) else: __SCREAMING_SNAKE_CASE = [to_numpy(UpperCAmelCase__ ) for v in value] # Convert padding_strategy in PaddingStrategy __SCREAMING_SNAKE_CASE = self._get_padding_strategies(padding=UpperCAmelCase__ , max_length=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) if not all(len(UpperCAmelCase__ ) == batch_size for v in processed_features.values() ): raise ValueError("Some items in the output dictionary have a different batch size than others." ) __SCREAMING_SNAKE_CASE = [] for i in range(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = {k: v[i] for k, v in processed_features.items()} # truncation __SCREAMING_SNAKE_CASE = self._truncate( UpperCAmelCase__ , max_length=UpperCAmelCase__ , pad_to_multiple_of=UpperCAmelCase__ , truncation=UpperCAmelCase__ , ) truncated_inputs.append(UpperCAmelCase__ ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length __SCREAMING_SNAKE_CASE = max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) __SCREAMING_SNAKE_CASE = PaddingStrategy.MAX_LENGTH __SCREAMING_SNAKE_CASE = {} for i in range(UpperCAmelCase__ ): # padding __SCREAMING_SNAKE_CASE = self._pad( truncated_inputs[i] , max_length=UpperCAmelCase__ , padding_strategy=UpperCAmelCase__ , pad_to_multiple_of=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , ) for key, value in outputs.items(): if key not in batch_outputs: __SCREAMING_SNAKE_CASE = [] if value.dtype is np.dtype(np.floataa ): __SCREAMING_SNAKE_CASE = value.astype(np.floataa ) batch_outputs[key].append(UpperCAmelCase__ ) return BatchFeature(UpperCAmelCase__ , tensor_type=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[Dict[str, np.ndarray], BatchFeature] , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , ) -> dict: __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __SCREAMING_SNAKE_CASE = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __SCREAMING_SNAKE_CASE = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(UpperCAmelCase__ ) < max_length if return_attention_mask and "attention_mask" not in processed_features: __SCREAMING_SNAKE_CASE = np.ones(len(UpperCAmelCase__ ) , dtype=np.intaa ) if needs_to_be_padded: __SCREAMING_SNAKE_CASE = max_length - len(UpperCAmelCase__ ) if self.padding_side == "right": if return_attention_mask: __SCREAMING_SNAKE_CASE = np.pad( processed_features["attention_mask"] , (0, difference) ) __SCREAMING_SNAKE_CASE = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) __SCREAMING_SNAKE_CASE = np.pad( UpperCAmelCase__ , UpperCAmelCase__ , "constant" , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: __SCREAMING_SNAKE_CASE = np.pad( processed_features["attention_mask"] , (difference, 0) ) __SCREAMING_SNAKE_CASE = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) __SCREAMING_SNAKE_CASE = np.pad( UpperCAmelCase__ , UpperCAmelCase__ , "constant" , constant_values=self.padding_value ) else: raise ValueError("Invalid padding strategy:" + str(self.padding_side ) ) return processed_features def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Union[Dict[str, np.ndarray], BatchFeature] , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , ) -> str: if not truncation: return processed_features elif truncation and max_length is None: raise ValueError("When setting ``truncation=True``, make sure that ``max_length`` is defined." ) __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __SCREAMING_SNAKE_CASE = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) > max_length if needs_to_be_truncated: __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: __SCREAMING_SNAKE_CASE = processed_features["attention_mask"][:max_length] return processed_features def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Optional[Any]=False , UpperCAmelCase__ : Optional[int]=None ) -> str: # Get padding strategy if padding is not False: if padding is True: __SCREAMING_SNAKE_CASE = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = PaddingStrategy(UpperCAmelCase__ ) elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = padding else: __SCREAMING_SNAKE_CASE = PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( F"""When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined""" ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( "Asking to pad but the feature_extractor does not have a padding value. Please select a value to use" " as `padding_value`. For example: `feature_extractor.padding_value = 0.0`." ) return padding_strategy
54
0
import unittest import numpy as np import requests from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: A : Optional[Any] = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class __A( unittest.TestCase ): def __init__( self , _snake_case , _snake_case=7 , _snake_case=3 , _snake_case=18 , _snake_case=30 , _snake_case=400 , _snake_case=None , _snake_case=True , _snake_case=True , _snake_case=None , ) -> Tuple: '''simple docstring''' __a = size if size is not None else {'''height''': 20, '''width''': 20} __a = parent __a = batch_size __a = num_channels __a = image_size __a = min_resolution __a = max_resolution __a = size __a = do_normalize __a = do_convert_rgb __a = [512, 1_024, 2_048, 4_096] __a = patch_size if patch_size is not None else {'''height''': 16, '''width''': 16} def SCREAMING_SNAKE_CASE_ ( self ) -> int: '''simple docstring''' return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def SCREAMING_SNAKE_CASE_ ( self ) -> str: '''simple docstring''' __a = '''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg''' __a = Image.open(requests.get(_snake_case , stream=_snake_case ).raw ).convert('''RGB''' ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='''`Pix2StructImageProcessor` requires `torch>=1.11.0`.''' , ) @require_torch @require_vision class __A( a , unittest.TestCase ): snake_case_ = PixaStructImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self ) -> List[str]: '''simple docstring''' __a = PixaStructImageProcessingTester(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''' __a = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_snake_case , '''do_normalize''' ) ) self.assertTrue(hasattr(_snake_case , '''do_convert_rgb''' ) ) def SCREAMING_SNAKE_CASE_ ( self ) -> Any: '''simple docstring''' __a = self.image_processor_tester.prepare_dummy_image() __a = self.image_processing_class(**self.image_processor_dict ) __a = 2_048 __a = image_processor(_snake_case , return_tensors='''pt''' , max_patches=_snake_case ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1E-3 , rtol=1E-3 ) ) def SCREAMING_SNAKE_CASE_ ( self ) -> Union[str, Any]: '''simple docstring''' __a = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __a = prepare_image_inputs(self.image_processor_tester , equal_resolution=_snake_case ) for image in image_inputs: self.assertIsInstance(_snake_case , Image.Image ) # Test not batched input __a = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __a = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=_snake_case ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __a = image_processor( _snake_case , return_tensors='''pt''' , max_patches=_snake_case ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def SCREAMING_SNAKE_CASE_ ( self ) -> Tuple: '''simple docstring''' __a = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __a = prepare_image_inputs(self.image_processor_tester , equal_resolution=_snake_case ) for image in image_inputs: self.assertIsInstance(_snake_case , Image.Image ) # Test not batched input __a = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 __a = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(_snake_case ): __a = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=_snake_case ).flattened_patches __a = '''Hello''' __a = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=_snake_case , header_text=_snake_case ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __a = image_processor( _snake_case , return_tensors='''pt''' , max_patches=_snake_case , header_text=_snake_case ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def SCREAMING_SNAKE_CASE_ ( self ) -> Union[str, Any]: '''simple docstring''' __a = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __a = prepare_image_inputs(self.image_processor_tester , equal_resolution=_snake_case , numpify=_snake_case ) for image in image_inputs: self.assertIsInstance(_snake_case , np.ndarray ) __a = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __a = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=_snake_case ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __a = image_processor( _snake_case , return_tensors='''pt''' , max_patches=_snake_case ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def SCREAMING_SNAKE_CASE_ ( self ) -> Any: '''simple docstring''' __a = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __a = prepare_image_inputs(self.image_processor_tester , equal_resolution=_snake_case , torchify=_snake_case ) for image in image_inputs: self.assertIsInstance(_snake_case , torch.Tensor ) # Test not batched input __a = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __a = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=_snake_case ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __a = image_processor( _snake_case , return_tensors='''pt''' , max_patches=_snake_case ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='''`Pix2StructImageProcessor` requires `torch>=1.11.0`.''' , ) @require_torch @require_vision class __A( a , unittest.TestCase ): snake_case_ = PixaStructImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self ) -> Dict: '''simple docstring''' __a = PixaStructImageProcessingTester(self , num_channels=4 ) __a = 3 @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 ) -> str: '''simple docstring''' __a = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_snake_case , '''do_normalize''' ) ) self.assertTrue(hasattr(_snake_case , '''do_convert_rgb''' ) ) def SCREAMING_SNAKE_CASE_ ( self ) -> List[str]: '''simple docstring''' __a = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __a = prepare_image_inputs(self.image_processor_tester , equal_resolution=_snake_case ) for image in image_inputs: self.assertIsInstance(_snake_case , Image.Image ) # Test not batched input __a = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __a = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=_snake_case ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __a = image_processor( _snake_case , return_tensors='''pt''' , max_patches=_snake_case ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
6
"""simple docstring""" import warnings from ...utils import is_sklearn_available, requires_backends if is_sklearn_available(): from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef a__ : Any = ( '''This metric will be removed from the library soon, metrics should be handled with the 🤗 Evaluate ''' '''library. You can have a look at this example script for pointers: ''' '''https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py''' ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) return (preds == labels).mean() def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) __SCREAMING_SNAKE_CASE = simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = fa_score(y_true=lowerCAmelCase_ , y_pred=lowerCAmelCase_ ) return { "acc": acc, "f1": fa, "acc_and_f1": (acc + fa) / 2, } def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) __SCREAMING_SNAKE_CASE = pearsonr(lowerCAmelCase_ , lowerCAmelCase_ )[0] __SCREAMING_SNAKE_CASE = spearmanr(lowerCAmelCase_ , lowerCAmelCase_ )[0] return { "pearson": pearson_corr, "spearmanr": spearman_corr, "corr": (pearson_corr + spearman_corr) / 2, } def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) assert len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ), f"""Predictions and labels have mismatched lengths {len(lowerCAmelCase_ )} and {len(lowerCAmelCase_ )}""" if task_name == "cola": return {"mcc": matthews_corrcoef(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "sst-2": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "mrpc": return acc_and_fa(lowerCAmelCase_ , lowerCAmelCase_ ) elif task_name == "sts-b": return pearson_and_spearman(lowerCAmelCase_ , lowerCAmelCase_ ) elif task_name == "qqp": return acc_and_fa(lowerCAmelCase_ , lowerCAmelCase_ ) elif task_name == "mnli": return {"mnli/acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "mnli-mm": return {"mnli-mm/acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "qnli": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "rte": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "wnli": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "hans": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} else: raise KeyError(lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) if len(lowerCAmelCase_ ) != len(lowerCAmelCase_ ): raise ValueError(f"""Predictions and labels have mismatched lengths {len(lowerCAmelCase_ )} and {len(lowerCAmelCase_ )}""" ) if task_name == "xnli": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} else: raise KeyError(lowerCAmelCase_ )
54
0
def _snake_case( SCREAMING_SNAKE_CASE__ : int = 600851475143 ) -> int: '''simple docstring''' try: A__ = int(SCREAMING_SNAKE_CASE__ ) except (TypeError, ValueError): raise TypeError('Parameter n must be int or castable to int.' ) if n <= 0: raise ValueError('Parameter n must be greater than or equal to one.' ) A__ = 2 A__ = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 A__ = i while n % i == 0: A__ = n // i i += 1 return int(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": print(f"""{solution() = }""")
7
"""simple docstring""" import math import random def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = False ): '''simple docstring''' if deriv: return value * (1 - value) return 1 / (1 + math.exp(-value )) # Initial Value a__ : Tuple = 0.02 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = float(2 * (random.randint(1 , 100 )) - 1 ) for _ in range(lowerCAmelCase_ ): # Forward propagation __SCREAMING_SNAKE_CASE = sigmoid_function(INITIAL_VALUE * weight ) # How much did we miss? __SCREAMING_SNAKE_CASE = (expected / 100) - layer_a # Error delta __SCREAMING_SNAKE_CASE = layer_1_error * sigmoid_function(lowerCAmelCase_ , lowerCAmelCase_ ) # Update weight weight += INITIAL_VALUE * layer_1_delta return layer_a * 100 if __name__ == "__main__": import doctest doctest.testmod() a__ : List[str] = int(input('''Expected value: ''')) a__ : str = int(input('''Number of propagations: ''')) print(forward_propagation(expected, number_propagations))
54
0
def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if exponent == 1: return base if exponent % 2 == 0: snake_case_ = _modexpt(SCREAMING_SNAKE_CASE__ , exponent // 2 , SCREAMING_SNAKE_CASE__ ) % modulo_value return (x * x) % modulo_value else: return (base * _modexpt(SCREAMING_SNAKE_CASE__ , exponent - 1 , SCREAMING_SNAKE_CASE__ )) % modulo_value def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ = 1777 , SCREAMING_SNAKE_CASE__ = 1855 , SCREAMING_SNAKE_CASE__ = 8 ): snake_case_ = base for _ in range(1 , SCREAMING_SNAKE_CASE__ ): snake_case_ = _modexpt(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 10**digits ) return result if __name__ == "__main__": print(f"""{solution() = }""")
8
"""simple docstring""" import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device a__ : Tuple = False class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" pass @slow @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = VersatileDiffusionImageVariationPipeline.from_pretrained("shi-labs/versatile-diffusion" ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( image=UpperCAmelCase__ , generator=UpperCAmelCase__ , guidance_scale=7.5 , num_inference_steps=5_0 , output_type="numpy" , ).images __SCREAMING_SNAKE_CASE = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __SCREAMING_SNAKE_CASE = np.array([0.0_441, 0.0_469, 0.0_507, 0.0_575, 0.0_632, 0.0_650, 0.0_865, 0.0_909, 0.0_945] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
54
0
from cva import destroyAllWindows, imread, imshow, waitKey def _UpperCamelCase ( lowercase__ ): # getting number of pixels in the image __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = img.shape[0], img.shape[1] # converting each pixel's color to its negative for i in range(lowercase__ ): for j in range(lowercase__ ): __SCREAMING_SNAKE_CASE : int = [255, 255, 255] - img[i][j] return img if __name__ == "__main__": # read original image __lowerCAmelCase : Optional[Any] =imread('image_data/lena.jpg', 1) # convert to its negative __lowerCAmelCase : Union[str, Any] =convert_to_negative(img) # show result image imshow('negative of original image', img) waitKey(0) destroyAllWindows()
9
"""simple docstring""" import importlib.util import json import os import warnings from dataclasses import dataclass, field import torch from ..training_args import TrainingArguments from ..utils import cached_property, is_sagemaker_dp_enabled, logging a__ : Union[str, Any] = logging.get_logger(__name__) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = os.getenv("SM_HP_MP_PARAMETERS" , "{}" ) try: # Parse it and check the field "partitions" is included, it is required for model parallel. __SCREAMING_SNAKE_CASE = json.loads(lowerCAmelCase_ ) if "partitions" not in smp_options: return False except json.JSONDecodeError: return False # Get the sagemaker specific framework parameters from mpi_options variable. __SCREAMING_SNAKE_CASE = os.getenv("SM_FRAMEWORK_PARAMS" , "{}" ) try: # Parse it and check the field "sagemaker_distributed_dataparallel_enabled". __SCREAMING_SNAKE_CASE = json.loads(lowerCAmelCase_ ) if not mpi_options.get("sagemaker_mpi_enabled" , lowerCAmelCase_ ): return False except json.JSONDecodeError: return False # Lastly, check if the `smdistributed` module is present. return importlib.util.find_spec("smdistributed" ) is not None if is_sagemaker_model_parallel_available(): import smdistributed.modelparallel.torch as smp smp.init() @dataclass class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = field( default="" , metadata={"help": "Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer"} , ) def UpperCAmelCase_ ( self : List[str] ) -> Any: super().__post_init__() warnings.warn( "`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use " "`TrainingArguments` instead." , UpperCAmelCase__ , ) @cached_property def UpperCAmelCase_ ( self : List[str] ) -> "torch.device": logger.info("PyTorch: setting up devices" ) if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1: logger.warning( "torch.distributed process group is initialized, but local_rank == -1. " "In order to use Torch DDP, launch your script with `python -m torch.distributed.launch" ) if self.no_cuda: __SCREAMING_SNAKE_CASE = torch.device("cpu" ) __SCREAMING_SNAKE_CASE = 0 elif is_sagemaker_model_parallel_available(): __SCREAMING_SNAKE_CASE = smp.local_rank() __SCREAMING_SNAKE_CASE = torch.device("cuda" , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = 1 elif is_sagemaker_dp_enabled(): import smdistributed.dataparallel.torch.torch_smddp # noqa: F401 torch.distributed.init_process_group(backend="smddp" , timeout=self.ddp_timeout_delta ) __SCREAMING_SNAKE_CASE = int(os.getenv("SMDATAPARALLEL_LOCAL_RANK" ) ) __SCREAMING_SNAKE_CASE = torch.device("cuda" , self.local_rank ) __SCREAMING_SNAKE_CASE = 1 elif self.local_rank == -1: # if n_gpu is > 1 we'll use nn.DataParallel. # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0` # Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will # trigger an error that a device index is missing. Index 0 takes into account the # GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0` # will use the first GPU in that env, i.e. GPU#1 __SCREAMING_SNAKE_CASE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" ) # Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at # the default value. __SCREAMING_SNAKE_CASE = torch.cuda.device_count() else: # Here, we'll use torch.distributed. # Initializes the distributed backend which will take care of synchronizing nodes/GPUs if not torch.distributed.is_initialized(): torch.distributed.init_process_group(backend="nccl" , timeout=self.ddp_timeout_delta ) __SCREAMING_SNAKE_CASE = torch.device("cuda" , self.local_rank ) __SCREAMING_SNAKE_CASE = 1 if device.type == "cuda": torch.cuda.set_device(UpperCAmelCase__ ) return device @property def UpperCAmelCase_ ( self : Dict ) -> Any: if is_sagemaker_model_parallel_available(): return smp.dp_size() return super().world_size @property def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[Any]: return not is_sagemaker_model_parallel_available() @property def UpperCAmelCase_ ( self : Tuple ) -> int: return False
54
0
import logging from transformers.configuration_utils import PretrainedConfig __A = logging.getLogger(__name__) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = "masked_bert" def __init__(self : Dict , UpperCAmelCase_ : Any=30_522 , UpperCAmelCase_ : List[Any]=768 , UpperCAmelCase_ : Optional[Any]=12 , UpperCAmelCase_ : str=12 , UpperCAmelCase_ : Tuple=3_072 , UpperCAmelCase_ : str="gelu" , UpperCAmelCase_ : Any=0.1 , UpperCAmelCase_ : Tuple=0.1 , UpperCAmelCase_ : Optional[Any]=512 , UpperCAmelCase_ : Union[str, Any]=2 , UpperCAmelCase_ : str=0.02 , UpperCAmelCase_ : str=1E-1_2 , UpperCAmelCase_ : Union[str, Any]=0 , UpperCAmelCase_ : str="topK" , UpperCAmelCase_ : List[str]="constant" , UpperCAmelCase_ : str=0.0 , **UpperCAmelCase_ : int , ) ->List[Any]: '''simple docstring''' super().__init__(pad_token_id=UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: Optional[int] =vocab_size lowerCamelCase__: Dict =hidden_size lowerCamelCase__: Optional[int] =num_hidden_layers lowerCamelCase__: Any =num_attention_heads lowerCamelCase__: List[Any] =hidden_act lowerCamelCase__: str =intermediate_size lowerCamelCase__: Dict =hidden_dropout_prob lowerCamelCase__: str =attention_probs_dropout_prob lowerCamelCase__: int =max_position_embeddings lowerCamelCase__: Tuple =type_vocab_size lowerCamelCase__: str =initializer_range lowerCamelCase__: List[Any] =layer_norm_eps lowerCamelCase__: str =pruning_method lowerCamelCase__: Union[str, Any] =mask_init lowerCamelCase__: Optional[Any] =mask_scale
10
"""simple docstring""" import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Optional[int] ) -> List[str]: # For consistency across different places the DisjunctiveConstraint is called, # dc.token_ids is a list of integers. It is also initialized only by integers. __SCREAMING_SNAKE_CASE = [[1, 2, 4], [1, 2, 3, 4]] __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(UpperCAmelCase__ ) self.assertTrue(isinstance(dc.token_ids , UpperCAmelCase__ ) ) with self.assertRaises(UpperCAmelCase__ ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(UpperCAmelCase__ ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def UpperCAmelCase_ ( self : Any ) -> int: # We can't have constraints that are complete subsets of another. This leads to a preverse # interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint? # It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially # fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm # will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it). __SCREAMING_SNAKE_CASE = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(UpperCAmelCase__ ): DisjunctiveConstraint(UpperCAmelCase__ ) # fails here def UpperCAmelCase_ ( self : List[Any] ) -> Any: __SCREAMING_SNAKE_CASE = [[1, 2, 3], [1, 2, 4]] __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) __SCREAMING_SNAKE_CASE = stepped is True and completed is False and reset is False self.assertTrue(UpperCAmelCase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) __SCREAMING_SNAKE_CASE = stepped is True and completed is False and reset is False self.assertTrue(UpperCAmelCase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(3 ) __SCREAMING_SNAKE_CASE = stepped is True and completed is True and reset is False self.assertTrue(UpperCAmelCase__ ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def UpperCAmelCase_ ( self : str ) -> List[str]: __SCREAMING_SNAKE_CASE = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
54
0
from __future__ import annotations def _UpperCAmelCase (UpperCamelCase__ : list ): if not nums: raise ValueError("List is empty" ) return sum(UpperCamelCase__ ) / len(UpperCamelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
11
"""simple docstring""" from __future__ import annotations def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = None ): '''simple docstring''' if start is None: __SCREAMING_SNAKE_CASE = 0 if end is None: __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) - 1 if start >= end: return __SCREAMING_SNAKE_CASE = (start + end) // 2 slowsort(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) slowsort(lowerCAmelCase_ , mid + 1 , lowerCAmelCase_ ) if sequence[end] < sequence[mid]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = sequence[mid], sequence[end] slowsort(lowerCAmelCase_ , lowerCAmelCase_ , end - 1 ) if __name__ == "__main__": from doctest import testmod testmod()
54
0
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ = logging.get_logger(__name__) UpperCAmelCase_ = { 'caidas/swin2sr-classicalsr-x2-64': ( 'https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json' ), } class lowerCamelCase__( __lowerCamelCase): UpperCAmelCase__ : Union[str, Any] = 'swin2sr' UpperCAmelCase__ : List[Any] = { 'hidden_size': 'embed_dim', 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers', } def __init__( self: List[str] , UpperCamelCase_: List[str]=64 , UpperCamelCase_: str=1 , UpperCamelCase_: int=3 , UpperCamelCase_: Any=1_80 , UpperCamelCase_: Optional[Any]=[6, 6, 6, 6, 6, 6] , UpperCamelCase_: Optional[int]=[6, 6, 6, 6, 6, 6] , UpperCamelCase_: Union[str, Any]=8 , UpperCamelCase_: Union[str, Any]=2.0 , UpperCamelCase_: Optional[int]=True , UpperCamelCase_: Tuple=0.0 , UpperCamelCase_: Optional[Any]=0.0 , UpperCamelCase_: Union[str, Any]=0.1 , UpperCamelCase_: int="gelu" , UpperCamelCase_: Optional[Any]=False , UpperCamelCase_: Any=0.02 , UpperCamelCase_: Any=1E-5 , UpperCamelCase_: str=2 , UpperCamelCase_: int=1.0 , UpperCamelCase_: str="1conv" , UpperCamelCase_: Any="pixelshuffle" , **UpperCamelCase_: Optional[Any] , ): super().__init__(**UpperCamelCase_ ) __lowerCamelCase = image_size __lowerCamelCase = patch_size __lowerCamelCase = num_channels __lowerCamelCase = embed_dim __lowerCamelCase = depths __lowerCamelCase = len(UpperCamelCase_ ) __lowerCamelCase = num_heads __lowerCamelCase = window_size __lowerCamelCase = mlp_ratio __lowerCamelCase = qkv_bias __lowerCamelCase = hidden_dropout_prob __lowerCamelCase = attention_probs_dropout_prob __lowerCamelCase = drop_path_rate __lowerCamelCase = hidden_act __lowerCamelCase = use_absolute_embeddings __lowerCamelCase = layer_norm_eps __lowerCamelCase = initializer_range __lowerCamelCase = upscale __lowerCamelCase = img_range __lowerCamelCase = resi_connection __lowerCamelCase = upsampler
12
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if number > 0: raise ValueError("input must be a negative integer" ) __SCREAMING_SNAKE_CASE = len(bin(lowerCAmelCase_ )[3:] ) __SCREAMING_SNAKE_CASE = bin(abs(lowerCAmelCase_ ) - (1 << binary_number_length) )[3:] __SCREAMING_SNAKE_CASE = ( ( "1" + "0" * (binary_number_length - len(lowerCAmelCase_ )) + twos_complement_number ) if number < 0 else "0" ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
54
0
def A_ ( _UpperCAmelCase , _UpperCAmelCase = False ): if not isinstance(_UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: str = f"Expected string as input, found {type(_UpperCAmelCase )}" raise ValueError(_UpperCAmelCase ) if not isinstance(_UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[Any] = f"Expected boolean as use_pascal parameter, found {type(_UpperCAmelCase )}" raise ValueError(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple = input_str.split("_" ) SCREAMING_SNAKE_CASE_: str = 0 if use_pascal else 1 SCREAMING_SNAKE_CASE_: int = words[start_index:] SCREAMING_SNAKE_CASE_: List[str] = [word[0].upper() + word[1:] for word in words_to_capitalize] SCREAMING_SNAKE_CASE_: List[Any] = "" if use_pascal else words[0] return "".join([initial_word, *capitalized_words] ) if __name__ == "__main__": from doctest import testmod testmod()
13
"""simple docstring""" import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Any = CLIPTokenizer snake_case__ : Dict = CLIPTokenizerFast snake_case__ : List[Any] = True snake_case__ : Optional[Any] = {} snake_case__ : Dict = False def UpperCAmelCase_ ( self : Any ) -> Any: super().setUp() # fmt: off __SCREAMING_SNAKE_CASE = ["l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"] # fmt: on __SCREAMING_SNAKE_CASE = dict(zip(UpperCAmelCase__ , range(len(UpperCAmelCase__ ) ) ) ) __SCREAMING_SNAKE_CASE = ["#version: 0.2", "l o", "lo w</w>", "e r</w>"] __SCREAMING_SNAKE_CASE = {"unk_token": "<unk>"} __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(UpperCAmelCase__ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(UpperCAmelCase__ ) ) def UpperCAmelCase_ ( self : List[Any] , **UpperCAmelCase__ : Tuple ) -> List[Any]: kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any , **UpperCAmelCase__ : Optional[Any] ) -> List[str]: kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = "lower newer" __SCREAMING_SNAKE_CASE = "lower newer" return input_text, output_text def UpperCAmelCase_ ( self : int ) -> List[str]: __SCREAMING_SNAKE_CASE = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __SCREAMING_SNAKE_CASE = "lower newer" __SCREAMING_SNAKE_CASE = ["lo", "w", "er</w>", "n", "e", "w", "er</w>"] __SCREAMING_SNAKE_CASE = tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokens + [tokenizer.unk_token] __SCREAMING_SNAKE_CASE = [1_0, 2, 1_6, 9, 3, 2, 1_6, 2_0] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , UpperCAmelCase__ ) @require_ftfy def UpperCAmelCase_ ( self : Optional[Any] ) -> int: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = "A\n'll 11p223RF☆ho!!to?'d'd''d of a cat to-$''d." __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways __SCREAMING_SNAKE_CASE = "xa\u0303y" + " " + "x\xe3y" __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Test that the tokenization is identical on unicode of space type __SCREAMING_SNAKE_CASE = [ "\u0009", # (horizontal tab, '\t') "\u000B", # (vertical tab) "\u000C", # (form feed) "\u0020", # (space, ' ') "\u200E", # (left-to-right mark):w "\u200F", # (right-to-left mark) ] for unicode_seq in spaces_unicodes: __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Test that the tokenization is identical on unicode of line break type __SCREAMING_SNAKE_CASE = [ "\u000A", # (line feed, '\n') "\r\n", # (carriage return and line feed, '\r\n') "\u000D", # (carriage return, '\r') "\r", # (carriage return, '\r') "\u000D", # (carriage return, '\r') "\u2028", # (line separator) "\u2029", # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Optional[Any]: # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = "hello" # `hello` is a token in the vocabulary of `pretrained_name` __SCREAMING_SNAKE_CASE = F"""{text_of_1_token} {text_of_1_token}""" __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(UpperCAmelCase__ ) + 1, len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , ) __SCREAMING_SNAKE_CASE = F""" {text}""" __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(UpperCAmelCase__ ) + 1, 1 + len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , ) def UpperCAmelCase_ ( self : str ) -> Optional[int]: # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(UpperCAmelCase__ ) as context: self.rust_tokenizer_class.from_pretrained("robot-test/old-clip-tokenizer" ) self.assertTrue( context.exception.args[0].startswith( "The `backend_tokenizer` provided does not match the expected format." ) ) @require_ftfy def UpperCAmelCase_ ( self : Optional[int] ) -> int: super().test_tokenization_python_rust_equals() def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[Any]: # CLIP always lower cases letters pass
54
0
import os import textwrap import pyarrow as pa import pytest from datasets import ClassLabel, Features, Image from datasets.packaged_modules.csv.csv import Csv from ..utils import require_pil @pytest.fixture def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Union[str, Any]: """simple docstring""" A__ = tmp_path / '''file.csv''' A__ = textwrap.dedent( '''\ header1,header2 1,2 10,20 ''' ) with open(lowercase_ , '''w''' ) as f: f.write(lowercase_ ) return str(lowercase_ ) @pytest.fixture def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Optional[Any]: """simple docstring""" A__ = tmp_path / '''malformed_file.csv''' A__ = textwrap.dedent( '''\ header1,header2 1,2 10,20, ''' ) with open(lowercase_ , '''w''' ) as f: f.write(lowercase_ ) return str(lowercase_ ) @pytest.fixture def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> str: """simple docstring""" A__ = tmp_path / '''csv_with_image.csv''' A__ = textwrap.dedent( f"""\ image {image_file} """ ) with open(lowercase_ , '''w''' ) as f: f.write(lowercase_ ) return str(lowercase_ ) @pytest.fixture def SCREAMING_SNAKE_CASE ( lowercase_ ) -> List[str]: """simple docstring""" A__ = tmp_path / '''csv_with_label.csv''' A__ = textwrap.dedent( '''\ label good bad good ''' ) with open(lowercase_ , '''w''' ) as f: f.write(lowercase_ ) return str(lowercase_ ) @pytest.fixture def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Tuple: """simple docstring""" A__ = tmp_path / '''csv_with_int_list.csv''' A__ = textwrap.dedent( '''\ int_list 1 2 3 4 5 6 7 8 9 ''' ) with open(lowercase_ , '''w''' ) as f: f.write(lowercase_ ) return str(lowercase_ ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> Dict: """simple docstring""" A__ = Csv() A__ = csv._generate_tables([[csv_file, malformed_csv_file]] ) with pytest.raises(lowercase_ , match='''Error tokenizing data''' ): for _ in generator: pass assert any( record.levelname == '''ERROR''' and '''Failed to read file''' in record.message and os.path.basename(lowercase_ ) in record.message for record in caplog.records ) @require_pil def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Union[str, Any]: """simple docstring""" with open(lowercase_ , encoding='''utf-8''' ) as f: A__ = f.read().splitlines()[1] A__ = Csv(encoding='''utf-8''' , features=Features({'''image''': Image()} ) ) A__ = csv._generate_tables([[csv_file_with_image]] ) A__ = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field('''image''' ).type == Image()() A__ = pa_table.to_pydict()['''image'''] assert generated_content == [{"path": image_file, "bytes": None}] def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Tuple: """simple docstring""" with open(lowercase_ , encoding='''utf-8''' ) as f: A__ = f.read().splitlines()[1:] A__ = Csv(encoding='''utf-8''' , features=Features({'''label''': ClassLabel(names=['''good''', '''bad'''] )} ) ) A__ = csv._generate_tables([[csv_file_with_label]] ) A__ = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field('''label''' ).type == ClassLabel(names=['''good''', '''bad'''] )() A__ = pa_table.to_pydict()['''label'''] assert generated_content == [ClassLabel(names=['''good''', '''bad'''] ).straint(lowercase_ ) for label in labels] def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Tuple: """simple docstring""" A__ = Csv(encoding='''utf-8''' , sep=''',''' , converters={'''int_list''': lambda lowercase_ : [int(lowercase_ ) for i in x.split()]} ) A__ = csv._generate_tables([[csv_file_with_int_list]] ) A__ = pa.concat_tables([table for _, table in generator] ) assert pa.types.is_list(pa_table.schema.field('''int_list''' ).type ) A__ = pa_table.to_pydict()['''int_list'''] assert generated_content == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
14
"""simple docstring""" import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( "kwargs, expected" , [ ({"num_shards": 0, "max_num_jobs": 1}, []), ({"num_shards": 10, "max_num_jobs": 1}, [range(10 )]), ({"num_shards": 10, "max_num_jobs": 10}, [range(lowerCAmelCase_ , i + 1 ) for i in range(10 )]), ({"num_shards": 1, "max_num_jobs": 10}, [range(1 )]), ({"num_shards": 10, "max_num_jobs": 3}, [range(0 , 4 ), range(4 , 7 ), range(7 , 10 )]), ({"num_shards": 3, "max_num_jobs": 10}, [range(0 , 1 ), range(1 , 2 ), range(2 , 3 )]), ] , ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = _distribute_shards(**lowerCAmelCase_ ) assert out == expected @pytest.mark.parametrize( "gen_kwargs, max_num_jobs, expected" , [ ({"foo": 0}, 10, [{"foo": 0}]), ({"shards": [0, 1, 2, 3]}, 1, [{"shards": [0, 1, 2, 3]}]), ({"shards": [0, 1, 2, 3]}, 4, [{"shards": [0]}, {"shards": [1]}, {"shards": [2]}, {"shards": [3]}]), ({"shards": [0, 1]}, 4, [{"shards": [0]}, {"shards": [1]}]), ({"shards": [0, 1, 2, 3]}, 2, [{"shards": [0, 1]}, {"shards": [2, 3]}]), ] , ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = _split_gen_kwargs(lowerCAmelCase_ , lowerCAmelCase_ ) assert out == expected @pytest.mark.parametrize( "gen_kwargs, expected" , [ ({"foo": 0}, 1), ({"shards": [0]}, 1), ({"shards": [0, 1, 2, 3]}, 4), ({"shards": [0, 1, 2, 3], "foo": 0}, 4), ({"shards": [0, 1, 2, 3], "other": (0, 1)}, 4), ({"shards": [0, 1, 2, 3], "shards2": [0, 1]}, RuntimeError), ] , ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if expected is RuntimeError: with pytest.raises(lowerCAmelCase_ ): _number_of_shards_in_gen_kwargs(lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = _number_of_shards_in_gen_kwargs(lowerCAmelCase_ ) assert out == expected
54
0
import os import unittest from transformers import MobileBertTokenizer, MobileBertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = MobileBertTokenizer snake_case_ = MobileBertTokenizerFast snake_case_ = True snake_case_ = True snake_case_ = filter_non_english snake_case_ = "google/mobilebert-uncased" def UpperCamelCase_ ( self : Optional[Any] ): super().setUp() __A = [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] __A = 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] ) ) __A = [ (tokenizer_def[0], self.pre_trained_model_path, tokenizer_def[2]) # else the 'google/' prefix is stripped for tokenizer_def in self.tokenizers_list ] def UpperCamelCase_ ( self : Tuple ,A : List[str] ): __A = "UNwant\u00E9d,running" __A = "unwanted, running" return input_text, output_text def UpperCamelCase_ ( self : str ): __A = self.tokenizer_class(self.vocab_file ) __A = tokenizer.tokenize("UNwant\u00E9d,running" ) self.assertListEqual(A ,["un", "##want", "##ed", ",", "runn", "##ing"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A ) ,[9, 6, 7, 12, 10, 11] ) def UpperCamelCase_ ( self : List[Any] ): if not self.test_rust_tokenizer: return __A = self.get_tokenizer() __A = self.get_rust_tokenizer() __A = "UNwant\u00E9d,running" __A = tokenizer.tokenize(A ) __A = rust_tokenizer.tokenize(A ) self.assertListEqual(A ,A ) __A = tokenizer.encode(A ,add_special_tokens=A ) __A = rust_tokenizer.encode(A ,add_special_tokens=A ) self.assertListEqual(A ,A ) __A = self.get_rust_tokenizer() __A = tokenizer.encode(A ) __A = rust_tokenizer.encode(A ) self.assertListEqual(A ,A ) # With lower casing __A = self.get_tokenizer(do_lower_case=A ) __A = self.get_rust_tokenizer(do_lower_case=A ) __A = "UNwant\u00E9d,running" __A = tokenizer.tokenize(A ) __A = rust_tokenizer.tokenize(A ) self.assertListEqual(A ,A ) __A = tokenizer.encode(A ,add_special_tokens=A ) __A = rust_tokenizer.encode(A ,add_special_tokens=A ) self.assertListEqual(A ,A ) __A = self.get_rust_tokenizer() __A = tokenizer.encode(A ) __A = rust_tokenizer.encode(A ) self.assertListEqual(A ,A ) def UpperCamelCase_ ( self : List[str] ): __A = BasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) ,["ah", "\u535A", "\u63A8", "zz"] ) def UpperCamelCase_ ( self : int ): __A = BasicTokenizer(do_lower_case=A ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) ,["hello", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) ,["hello"] ) def UpperCamelCase_ ( self : Tuple ): __A = BasicTokenizer(do_lower_case=A ,strip_accents=A ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) ,["hällo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) ,["h\u00E9llo"] ) def UpperCamelCase_ ( self : List[Any] ): __A = BasicTokenizer(do_lower_case=A ,strip_accents=A ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) ,["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) ,["hello"] ) def UpperCamelCase_ ( self : str ): __A = BasicTokenizer(do_lower_case=A ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) ,["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) ,["hello"] ) def UpperCamelCase_ ( self : List[str] ): __A = BasicTokenizer(do_lower_case=A ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) ,["HeLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCamelCase_ ( self : Tuple ): __A = BasicTokenizer(do_lower_case=A ,strip_accents=A ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) ,["HäLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCamelCase_ ( self : Union[str, Any] ): __A = BasicTokenizer(do_lower_case=A ,strip_accents=A ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) ,["HaLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCamelCase_ ( self : str ): __A = BasicTokenizer(do_lower_case=A ,never_split=["[UNK]"] ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]" ) ,["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] ) def UpperCamelCase_ ( self : Union[str, Any] ): __A = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] __A = {} for i, token in enumerate(A ): __A = i __A = WordpieceTokenizer(vocab=A ,unk_token="[UNK]" ) self.assertListEqual(tokenizer.tokenize("" ) ,[] ) self.assertListEqual(tokenizer.tokenize("unwanted running" ) ,["un", "##want", "##ed", "runn", "##ing"] ) self.assertListEqual(tokenizer.tokenize("unwantedX running" ) ,["[UNK]", "runn", "##ing"] ) def UpperCamelCase_ ( self : Union[str, Any] ): self.assertTrue(_is_whitespace(" " ) ) self.assertTrue(_is_whitespace("\t" ) ) self.assertTrue(_is_whitespace("\r" ) ) self.assertTrue(_is_whitespace("\n" ) ) self.assertTrue(_is_whitespace("\u00A0" ) ) self.assertFalse(_is_whitespace("A" ) ) self.assertFalse(_is_whitespace("-" ) ) def UpperCamelCase_ ( self : Union[str, Any] ): self.assertTrue(_is_control("\u0005" ) ) self.assertFalse(_is_control("A" ) ) self.assertFalse(_is_control(" " ) ) self.assertFalse(_is_control("\t" ) ) self.assertFalse(_is_control("\r" ) ) def UpperCamelCase_ ( self : Optional[int] ): self.assertTrue(_is_punctuation("-" ) ) self.assertTrue(_is_punctuation("$" ) ) self.assertTrue(_is_punctuation("`" ) ) self.assertTrue(_is_punctuation("." ) ) self.assertFalse(_is_punctuation("A" ) ) self.assertFalse(_is_punctuation(" " ) ) def UpperCamelCase_ ( self : List[Any] ): __A = self.get_tokenizer() __A = self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(A ) for t in ["Test", "\xad", "test"]] ,[["[UNK]"], [], ["[UNK]"]] ) self.assertListEqual( [rust_tokenizer.tokenize(A ) for t in ["Test", "\xad", "test"]] ,[["[UNK]"], [], ["[UNK]"]] ) @slow def UpperCamelCase_ ( self : Any ): __A = self.tokenizer_class.from_pretrained("google/mobilebert-uncased" ) __A = tokenizer.encode("sequence builders" ,add_special_tokens=A ) __A = tokenizer.encode("multi-sequence build" ,add_special_tokens=A ) __A = tokenizer.build_inputs_with_special_tokens(A ) __A = tokenizer.build_inputs_with_special_tokens(A ,A ) assert encoded_sentence == [1_01] + text + [1_02] assert encoded_pair == [1_01] + text + [1_02] + text_a + [1_02] def UpperCamelCase_ ( self : str ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): __A = self.rust_tokenizer_class.from_pretrained(A ,**A ) __A = f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' __A = tokenizer_r.encode_plus( A ,return_attention_mask=A ,return_token_type_ids=A ,return_offsets_mapping=A ,add_special_tokens=A ,) __A = tokenizer_r.do_lower_case if hasattr(A ,"do_lower_case" ) else False __A = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "A"), ((1, 2), ","), ((3, 5), "na"), ((5, 6), "##ï"), ((6, 8), "##ve"), ((9, 15), tokenizer_r.mask_token), ((16, 21), "Allen"), ((21, 23), "##NL"), ((23, 24), "##P"), ((25, 33), "sentence"), ((33, 34), "."), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "a"), ((1, 2), ","), ((3, 8), "naive"), ((9, 15), tokenizer_r.mask_token), ((16, 21), "allen"), ((21, 23), "##nl"), ((23, 24), "##p"), ((25, 33), "sentence"), ((33, 34), "."), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] ,tokenizer_r.convert_ids_to_tokens(tokens["input_ids"] ) ) self.assertEqual([e[0] for e in expected_results] ,tokens["offset_mapping"] ) def UpperCamelCase_ ( self : Optional[int] ): __A = ["的", "人", "有"] __A = "".join(A ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): __A = True __A = self.tokenizer_class.from_pretrained(A ,**A ) __A = self.rust_tokenizer_class.from_pretrained(A ,**A ) __A = tokenizer_p.encode(A ,add_special_tokens=A ) __A = tokenizer_r.encode(A ,add_special_tokens=A ) __A = tokenizer_r.convert_ids_to_tokens(A ) __A = tokenizer_p.convert_ids_to_tokens(A ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(A ,A ) self.assertListEqual(A ,A ) __A = False __A = self.rust_tokenizer_class.from_pretrained(A ,**A ) __A = self.tokenizer_class.from_pretrained(A ,**A ) __A = tokenizer_r.encode(A ,add_special_tokens=A ) __A = tokenizer_p.encode(A ,add_special_tokens=A ) __A = tokenizer_r.convert_ids_to_tokens(A ) __A = tokenizer_p.convert_ids_to_tokens(A ) # it is expected that only the first Chinese character is not preceded by "##". __A = [ f'''##{token}''' if idx != 0 else token for idx, token in enumerate(A ) ] self.assertListEqual(A ,A ) self.assertListEqual(A ,A )
15
"""simple docstring""" import unittest from transformers.testing_utils import CaptureStdout from transformers.tools.python_interpreter import evaluate def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return x + 2 class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Any ) -> Any: __SCREAMING_SNAKE_CASE = "x = 3" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result == 3 self.assertDictEqual(UpperCAmelCase__ , {"x": 3} ) __SCREAMING_SNAKE_CASE = "x = y" __SCREAMING_SNAKE_CASE = {"y": 5} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 5, "y": 5} ) def UpperCAmelCase_ ( self : Dict ) -> List[str]: __SCREAMING_SNAKE_CASE = "y = add_two(x)" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 5} ) # Won't work without the tool with CaptureStdout() as out: __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result is None assert "tried to execute add_two" in out.out def UpperCAmelCase_ ( self : List[Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = "x = 3" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result == 3 self.assertDictEqual(UpperCAmelCase__ , {"x": 3} ) def UpperCAmelCase_ ( self : str ) -> Any: __SCREAMING_SNAKE_CASE = "test_dict = {'x': x, 'y': add_two(x)}" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 5} ) self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_dict": {"x": 3, "y": 5}} ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = "x = 3\ny = 5" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 5} ) def UpperCAmelCase_ ( self : Any ) -> Any: __SCREAMING_SNAKE_CASE = "text = f'This is x: {x}.'" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == "This is x: 3." self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "text": "This is x: 3."} ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = "if x <= 3:\n y = 2\nelse:\n y = 5" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 2 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 2} ) __SCREAMING_SNAKE_CASE = {"x": 8} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 8, "y": 5} ) def UpperCAmelCase_ ( self : Tuple ) -> str: __SCREAMING_SNAKE_CASE = "test_list = [x, add_two(x)]" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , [3, 5] ) self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_list": [3, 5]} ) def UpperCAmelCase_ ( self : Any ) -> int: __SCREAMING_SNAKE_CASE = "y = x" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result == 3 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 3} ) def UpperCAmelCase_ ( self : Tuple ) -> int: __SCREAMING_SNAKE_CASE = "test_list = [x, add_two(x)]\ntest_list[1]" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_list": [3, 5]} ) __SCREAMING_SNAKE_CASE = "test_dict = {'x': x, 'y': add_two(x)}\ntest_dict['y']" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_dict": {"x": 3, "y": 5}} ) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = "x = 0\nfor i in range(3):\n x = i" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"range": range} , state=UpperCAmelCase__ ) assert result == 2 self.assertDictEqual(UpperCAmelCase__ , {"x": 2, "i": 2} )
54
0
"""simple docstring""" from __future__ import annotations import unittest from transformers import AutoTokenizer, MBartConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel @require_tf class __A : '''simple docstring''' lowerCAmelCase : List[Any] = MBartConfig lowerCAmelCase : int = {} lowerCAmelCase : Optional[int] = "gelu" def __init__( self : str ,_snake_case : Any ,_snake_case : Optional[int]=13 ,_snake_case : str=7 ,_snake_case : Any=True ,_snake_case : Union[str, Any]=False ,_snake_case : List[str]=99 ,_snake_case : Any=32 ,_snake_case : Optional[int]=2 ,_snake_case : Dict=4 ,_snake_case : str=37 ,_snake_case : Optional[int]=0.1 ,_snake_case : Dict=0.1 ,_snake_case : List[str]=20 ,_snake_case : Optional[Any]=2 ,_snake_case : Optional[Any]=1 ,_snake_case : Optional[int]=0 ,) -> Optional[int]: """simple docstring""" lowercase__ : List[str] = parent lowercase__ : Optional[Any] = batch_size lowercase__ : Union[str, Any] = seq_length lowercase__ : Tuple = is_training lowercase__ : Optional[Any] = use_labels lowercase__ : Any = vocab_size lowercase__ : Tuple = hidden_size lowercase__ : Dict = num_hidden_layers lowercase__ : Optional[Any] = num_attention_heads lowercase__ : Any = intermediate_size lowercase__ : Any = hidden_dropout_prob lowercase__ : Optional[int] = attention_probs_dropout_prob lowercase__ : str = max_position_embeddings lowercase__ : Union[str, Any] = eos_token_id lowercase__ : List[Any] = pad_token_id lowercase__ : Tuple = bos_token_id def UpperCAmelCase ( self : int ) -> Optional[int]: """simple docstring""" lowercase__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length - 1] ,self.vocab_size ) lowercase__ : List[str] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) ,1 ) lowercase__ : Optional[int] = tf.concat([input_ids, eos_tensor] ,axis=1 ) lowercase__ : str = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) lowercase__ : Union[str, Any] = self.config_cls( vocab_size=self.vocab_size ,d_model=self.hidden_size ,encoder_layers=self.num_hidden_layers ,decoder_layers=self.num_hidden_layers ,encoder_attention_heads=self.num_attention_heads ,decoder_attention_heads=self.num_attention_heads ,encoder_ffn_dim=self.intermediate_size ,decoder_ffn_dim=self.intermediate_size ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,eos_token_ids=[2] ,bos_token_id=self.bos_token_id ,pad_token_id=self.pad_token_id ,decoder_start_token_id=self.pad_token_id ,**self.config_updates ,) lowercase__ : Tuple = prepare_mbart_inputs_dict(_snake_case ,_snake_case ,_snake_case ) return config, inputs_dict def UpperCAmelCase ( self : int ,_snake_case : Dict ,_snake_case : Optional[Any] ) -> str: """simple docstring""" lowercase__ : Union[str, Any] = TFMBartModel(config=_snake_case ).get_decoder() lowercase__ : List[str] = inputs_dict['''input_ids'''] lowercase__ : Dict = input_ids[:1, :] lowercase__ : Any = inputs_dict['''attention_mask'''][:1, :] lowercase__ : List[Any] = inputs_dict['''head_mask'''] lowercase__ : List[Any] = 1 # first forward pass lowercase__ : Any = model(_snake_case ,attention_mask=_snake_case ,head_mask=_snake_case ,use_cache=_snake_case ) lowercase__ , lowercase__ : int = outputs.to_tuple() lowercase__ : Dict = past_key_values[1] def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=None , ) -> int: if attention_mask is None: lowercase__ : int = tf.cast(tf.math.not_equal(__lowerCamelCase , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: lowercase__ : str = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: lowercase__ : Optional[int] = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: lowercase__ : List[Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: lowercase__ : Any = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class __A ( A_ ,A_ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase : Optional[Any] = (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else () lowerCAmelCase : Any = (TFMBartForConditionalGeneration,) if is_tf_available() else () lowerCAmelCase : Optional[Any] = ( { "conversational": TFMBartForConditionalGeneration, "feature-extraction": TFMBartModel, "summarization": TFMBartForConditionalGeneration, "text2text-generation": TFMBartForConditionalGeneration, "translation": TFMBartForConditionalGeneration, } if is_tf_available() else {} ) lowerCAmelCase : Optional[int] = True lowerCAmelCase : Optional[Any] = False lowerCAmelCase : str = False def UpperCAmelCase ( self : Optional[Any] ,_snake_case : List[Any] ,_snake_case : Dict ,_snake_case : int ,_snake_case : List[Any] ,_snake_case : List[Any] ) -> List[str]: """simple docstring""" if pipeline_test_casse_name != "FeatureExtractionPipelineTests": # Exception encountered when calling layer '...' return True return False def UpperCAmelCase ( self : int ) -> List[str]: """simple docstring""" lowercase__ : Dict = TFMBartModelTester(self ) lowercase__ : Optional[Any] = ConfigTester(self ,config_class=_snake_case ) def UpperCAmelCase ( self : Any ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() def UpperCAmelCase ( self : List[str] ) -> List[Any]: """simple docstring""" lowercase__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*_snake_case ) @require_sentencepiece @require_tokenizers @require_tf class __A ( unittest.TestCase ): '''simple docstring''' lowerCAmelCase : List[Any] = [ " UN Chief Says There Is No Military Solution in Syria", ] lowerCAmelCase : Dict = [ "Şeful ONU declară că nu există o soluţie militară în Siria", ] lowerCAmelCase : str = "facebook/mbart-large-en-ro" @cached_property def UpperCAmelCase ( self : Tuple ) -> Optional[int]: """simple docstring""" return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def UpperCAmelCase ( self : List[str] ) -> Optional[int]: """simple docstring""" lowercase__ : Dict = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def UpperCAmelCase ( self : List[Any] ,**_snake_case : str ) -> Optional[int]: """simple docstring""" lowercase__ : Dict = self.translate_src_text(**_snake_case ) self.assertListEqual(self.expected_text ,_snake_case ) def UpperCAmelCase ( self : Any ,**_snake_case : List[str] ) -> Optional[Any]: """simple docstring""" lowercase__ : str = self.tokenizer(self.src_text ,**_snake_case ,return_tensors='''tf''' ) lowercase__ : Dict = self.model.generate( model_inputs.input_ids ,attention_mask=model_inputs.attention_mask ,num_beams=2 ) lowercase__ : List[str] = self.tokenizer.batch_decode(_snake_case ,skip_special_tokens=_snake_case ) return generated_words @slow def UpperCAmelCase ( self : List[str] ) -> Union[str, Any]: """simple docstring""" self._assert_generated_batch_equal_expected()
16
"""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__ : str = { '''configuration_roformer''': ['''ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''RoFormerConfig''', '''RoFormerOnnxConfig'''], '''tokenization_roformer''': ['''RoFormerTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = ['''RoFormerTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''RoFormerForCausalLM''', '''RoFormerForMaskedLM''', '''RoFormerForMultipleChoice''', '''RoFormerForQuestionAnswering''', '''RoFormerForSequenceClassification''', '''RoFormerForTokenClassification''', '''RoFormerLayer''', '''RoFormerModel''', '''RoFormerPreTrainedModel''', '''load_tf_weights_in_roformer''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = [ '''TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFRoFormerForCausalLM''', '''TFRoFormerForMaskedLM''', '''TFRoFormerForMultipleChoice''', '''TFRoFormerForQuestionAnswering''', '''TFRoFormerForSequenceClassification''', '''TFRoFormerForTokenClassification''', '''TFRoFormerLayer''', '''TFRoFormerModel''', '''TFRoFormerPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FlaxRoFormerForMaskedLM''', '''FlaxRoFormerForMultipleChoice''', '''FlaxRoFormerForQuestionAnswering''', '''FlaxRoFormerForSequenceClassification''', '''FlaxRoFormerForTokenClassification''', '''FlaxRoFormerModel''', '''FlaxRoFormerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys a__ : int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
54
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) _a = { 'configuration_mobilevit': ['MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MobileViTConfig', 'MobileViTOnnxConfig'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a = ['MobileViTFeatureExtractor'] _a = ['MobileViTImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a = [ 'MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'MobileViTForImageClassification', 'MobileViTForSemanticSegmentation', 'MobileViTModel', 'MobileViTPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a = [ 'TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFMobileViTForImageClassification', 'TFMobileViTForSemanticSegmentation', 'TFMobileViTModel', 'TFMobileViTPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mobilevit import MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileViTConfig, MobileViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilevit import MobileViTFeatureExtractor from .image_processing_mobilevit import MobileViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilevit import ( MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel, MobileViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilevit import ( TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel, TFMobileViTPreTrainedModel, ) else: import sys _a = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
17
"""simple docstring""" # Copyright 2022 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. import argparse import os import subprocess from packaging.version import Version, parse from accelerate.commands.config.config_args import default_config_file, load_config_from_file a__ : Tuple = '''Run commands across TPU VMs for initial setup before running `accelerate launch`.''' def UpperCAmelCase__ (lowerCAmelCase_=None ): '''simple docstring''' if subparsers is not None: __SCREAMING_SNAKE_CASE = subparsers.add_parser("tpu-config" , description=_description ) else: __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("Accelerate tpu-config command" , description=_description ) # Core arguments __SCREAMING_SNAKE_CASE = parser.add_argument_group( "Config Arguments" , "Arguments that can be configured through `accelerate config`." ) config_args.add_argument( "--config_file" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , help="Path to the config file to use for accelerate." , ) config_args.add_argument( "--tpu_name" , default=lowerCAmelCase_ , help="The name of the TPU to use. If not specified, will use the TPU specified in the config file." , ) config_args.add_argument( "--tpu_zone" , default=lowerCAmelCase_ , help="The zone of the TPU to use. If not specified, will use the zone specified in the config file." , ) __SCREAMING_SNAKE_CASE = parser.add_argument_group("TPU Arguments" , "Arguments for options ran inside the TPU." ) pod_args.add_argument( "--use_alpha" , action="store_true" , help="Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`." , ) pod_args.add_argument( "--command_file" , default=lowerCAmelCase_ , help="The path to the file containing the commands to run on the pod on startup." , ) pod_args.add_argument( "--command" , action="append" , nargs="+" , help="A command to run on the pod. Can be passed multiple times." , ) pod_args.add_argument( "--install_accelerate" , action="store_true" , help="Whether to install accelerate on the pod. Defaults to False." , ) pod_args.add_argument( "--accelerate_version" , default="latest" , help="The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify 'dev' to install from GitHub." , ) pod_args.add_argument( "--debug" , action="store_true" , help="If set, will print the command that would be run instead of running it." ) if subparsers is not None: parser.set_defaults(func=lowerCAmelCase_ ) return parser def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = None # Get the default from the config file if it exists. if args.config_file is not None or os.path.isfile(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = load_config_from_file(args.config_file ) if not args.command_file and defaults.command_file is not None and not args.command: __SCREAMING_SNAKE_CASE = defaults.command_file if not args.command and defaults.commands is not None: __SCREAMING_SNAKE_CASE = defaults.commands if not args.tpu_name: __SCREAMING_SNAKE_CASE = defaults.tpu_name if not args.tpu_zone: __SCREAMING_SNAKE_CASE = defaults.tpu_zone if args.accelerate_version == "dev": __SCREAMING_SNAKE_CASE = "git+https://github.com/huggingface/accelerate.git" elif args.accelerate_version == "latest": __SCREAMING_SNAKE_CASE = "accelerate -U" elif isinstance(parse(args.accelerate_version ) , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = f"""accelerate=={args.accelerate_version}""" if not args.command_file and not args.command: raise ValueError("You must specify either a command file or a command to run on the pod." ) if args.command_file: with open(args.command_file , "r" ) as f: __SCREAMING_SNAKE_CASE = [f.read().splitlines()] # To turn list of lists into list of strings if isinstance(args.command[0] , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = [line for cmd in args.command for line in cmd] # Default to the shared folder and install accelerate __SCREAMING_SNAKE_CASE = ["cd /usr/share"] if args.install_accelerate: new_cmd += [f"""pip install {args.accelerate_version}"""] new_cmd += args.command __SCREAMING_SNAKE_CASE = "; ".join(lowerCAmelCase_ ) # Then send it to gcloud # Eventually try to use google-api-core to do this instead of subprocess __SCREAMING_SNAKE_CASE = ["gcloud"] if args.use_alpha: cmd += ["alpha"] cmd += [ "compute", "tpus", "tpu-vm", "ssh", args.tpu_name, "--zone", args.tpu_zone, "--command", args.command, "--worker", "all", ] if args.debug: print(f"""Running {' '.join(lowerCAmelCase_ )}""" ) return subprocess.run(lowerCAmelCase_ ) print("Successfully setup pod." ) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = tpu_command_parser() __SCREAMING_SNAKE_CASE = parser.parse_args() tpu_command_launcher(lowerCAmelCase_ )
54
0
import argparse import json from typing import List from ltp import LTP from transformers import BertTokenizer def _snake_case ( lowerCAmelCase : Dict ): """simple docstring""" if ( (cp >= 0X4_E_0_0 and cp <= 0X9_F_F_F) or (cp >= 0X3_4_0_0 and cp <= 0X4_D_B_F) # or (cp >= 0X2_0_0_0_0 and cp <= 0X2_A_6_D_F) # or (cp >= 0X2_A_7_0_0 and cp <= 0X2_B_7_3_F) # or (cp >= 0X2_B_7_4_0 and cp <= 0X2_B_8_1_F) # or (cp >= 0X2_B_8_2_0 and cp <= 0X2_C_E_A_F) # or (cp >= 0XF_9_0_0 and cp <= 0XF_A_F_F) or (cp >= 0X2_F_8_0_0 and cp <= 0X2_F_A_1_F) # ): # return True return False def _snake_case ( lowerCAmelCase : str ): """simple docstring""" for char in word: SCREAMING_SNAKE_CASE_ : Any = ord(lowerCAmelCase ) if not _is_chinese_char(lowerCAmelCase ): return 0 return 1 def _snake_case ( lowerCAmelCase : List[str] ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = set() for token in tokens: SCREAMING_SNAKE_CASE_ : int = len(lowerCAmelCase ) > 1 and is_chinese(lowerCAmelCase ) if chinese_word: word_set.add(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = list(lowerCAmelCase ) return word_list def _snake_case ( lowerCAmelCase : List[str] , lowerCAmelCase : set() ): """simple docstring""" if not chinese_word_set: return bert_tokens SCREAMING_SNAKE_CASE_ : str = max([len(lowerCAmelCase ) for w in chinese_word_set] ) SCREAMING_SNAKE_CASE_ : int = bert_tokens SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = 0, len(lowerCAmelCase ) while start < end: SCREAMING_SNAKE_CASE_ : Optional[int] = True if is_chinese(bert_word[start] ): SCREAMING_SNAKE_CASE_ : List[str] = min(end - start , lowerCAmelCase ) for i in range(lowerCAmelCase , 1 , -1 ): SCREAMING_SNAKE_CASE_ : Tuple = "".join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1 , start + i ): SCREAMING_SNAKE_CASE_ : Optional[int] = "##" + bert_word[j] SCREAMING_SNAKE_CASE_ : int = start + i SCREAMING_SNAKE_CASE_ : Optional[Any] = False break if single_word: start += 1 return bert_word def _snake_case ( lowerCAmelCase : List[str] , lowerCAmelCase : LTP , lowerCAmelCase : BertTokenizer ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] for i in range(0 , len(lowerCAmelCase ) , 1_0_0 ): SCREAMING_SNAKE_CASE_ : Optional[int] = ltp_tokenizer.seg(lines[i : i + 1_0_0] )[0] SCREAMING_SNAKE_CASE_ : List[Any] = [get_chinese_word(lowerCAmelCase ) for r in res] ltp_res.extend(lowerCAmelCase ) assert len(lowerCAmelCase ) == len(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] for i in range(0 , len(lowerCAmelCase ) , 1_0_0 ): SCREAMING_SNAKE_CASE_ : str = bert_tokenizer(lines[i : i + 1_0_0] , add_special_tokens=lowerCAmelCase , truncation=lowerCAmelCase , max_length=5_1_2 ) bert_res.extend(res["input_ids"] ) assert len(lowerCAmelCase ) == len(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : int = [] for input_ids, chinese_word in zip(lowerCAmelCase , lowerCAmelCase ): SCREAMING_SNAKE_CASE_ : str = [] for id in input_ids: SCREAMING_SNAKE_CASE_ : Tuple = bert_tokenizer._convert_id_to_token(lowerCAmelCase ) input_tokens.append(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : Any = add_sub_symbol(lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : Tuple = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(lowerCAmelCase ): if token[:2] == "##": SCREAMING_SNAKE_CASE_ : List[Any] = token[2:] # save chinese tokens' pos if len(lowerCAmelCase ) == 1 and _is_chinese_char(ord(lowerCAmelCase ) ): ref_id.append(lowerCAmelCase ) ref_ids.append(lowerCAmelCase ) assert len(lowerCAmelCase ) == len(lowerCAmelCase ) return ref_ids def _snake_case ( lowerCAmelCase : Optional[int] ): """simple docstring""" with open(args.file_name , "r" , encoding="utf-8" ) as f: SCREAMING_SNAKE_CASE_ : List[Any] = f.readlines() SCREAMING_SNAKE_CASE_ : int = [line.strip() for line in data if len(lowerCAmelCase ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' SCREAMING_SNAKE_CASE_ : Union[str, Any] = LTP(args.ltp ) # faster in GPU device SCREAMING_SNAKE_CASE_ : Tuple = BertTokenizer.from_pretrained(args.bert ) SCREAMING_SNAKE_CASE_ : List[str] = prepare_ref(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) with open(args.save_path , "w" , encoding="utf-8" ) as f: SCREAMING_SNAKE_CASE_ : Optional[int] = [json.dumps(lowerCAmelCase ) + "\n" for ref in ref_ids] f.writelines(lowerCAmelCase ) if __name__ == "__main__": __lowerCamelCase : Any = argparse.ArgumentParser(description='''prepare_chinese_ref''') parser.add_argument( '''--file_name''', type=str, default='''./resources/chinese-demo.txt''', help='''file need process, same as training data in lm''', ) parser.add_argument( '''--ltp''', type=str, default='''./resources/ltp''', help='''resources for LTP tokenizer, usually a path''' ) parser.add_argument('''--bert''', type=str, default='''./resources/robert''', help='''resources for Bert tokenizer''') parser.add_argument('''--save_path''', type=str, default='''./resources/ref.txt''', help='''path to save res''') __lowerCamelCase : int = parser.parse_args() main(args)
18
"""simple docstring""" from abc import ABC, abstractmethod from argparse import ArgumentParser class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @staticmethod @abstractmethod def UpperCAmelCase_ ( UpperCAmelCase__ : ArgumentParser ) -> int: raise NotImplementedError() @abstractmethod def UpperCAmelCase_ ( self : int ) -> Optional[int]: raise NotImplementedError()
54
0
import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoFeatureExtractor, WavaVecaFeatureExtractor from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test sys.path.append(str(Path(__file__).parent.parent / '''utils''')) from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 __A =get_tests_dir('''fixtures''') class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_( self ) -> List[str]: # A mock response for an HTTP head request to emulate server down lowerCamelCase_ = mock.Mock() lowerCamelCase_ = 500 lowerCamelCase_ = {} lowerCamelCase_ = HTTPError lowerCamelCase_ = {} # Download this model to make sure it's in the cache. lowerCamelCase_ = WavaVecaFeatureExtractor.from_pretrained("hf-internal-testing/tiny-random-wav2vec2" ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch("requests.Session.request" , return_value=lowercase ) as mock_head: lowerCamelCase_ = WavaVecaFeatureExtractor.from_pretrained("hf-internal-testing/tiny-random-wav2vec2" ) # This check we did call the fake head request mock_head.assert_called() def SCREAMING_SNAKE_CASE_( self ) -> Optional[Any]: # This test is for deprecated behavior and can be removed in v5 lowerCamelCase_ = WavaVecaFeatureExtractor.from_pretrained( "https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json" ) @is_staging_test class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): @classmethod def SCREAMING_SNAKE_CASE_( cls ) -> Optional[Any]: lowerCamelCase_ = TOKEN HfFolder.save_token(lowercase ) @classmethod def SCREAMING_SNAKE_CASE_( cls ) -> List[str]: try: delete_repo(token=cls._token , repo_id="test-feature-extractor" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="valid_org/test-feature-extractor-org" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="test-dynamic-feature-extractor" ) except HTTPError: pass def SCREAMING_SNAKE_CASE_( self ) -> Optional[Any]: lowerCamelCase_ = WavaVecaFeatureExtractor.from_pretrained(lowercase ) feature_extractor.push_to_hub("test-feature-extractor" , use_auth_token=self._token ) lowerCamelCase_ = WavaVecaFeatureExtractor.from_pretrained(f'{USER}/test-feature-extractor' ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(lowercase , getattr(lowercase , lowercase ) ) # Reset repo delete_repo(token=self._token , repo_id="test-feature-extractor" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained( lowercase , repo_id="test-feature-extractor" , push_to_hub=lowercase , use_auth_token=self._token ) lowerCamelCase_ = WavaVecaFeatureExtractor.from_pretrained(f'{USER}/test-feature-extractor' ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(lowercase , getattr(lowercase , lowercase ) ) def SCREAMING_SNAKE_CASE_( self ) -> List[Any]: lowerCamelCase_ = WavaVecaFeatureExtractor.from_pretrained(lowercase ) feature_extractor.push_to_hub("valid_org/test-feature-extractor" , use_auth_token=self._token ) lowerCamelCase_ = WavaVecaFeatureExtractor.from_pretrained("valid_org/test-feature-extractor" ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(lowercase , getattr(lowercase , lowercase ) ) # Reset repo delete_repo(token=self._token , repo_id="valid_org/test-feature-extractor" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained( lowercase , repo_id="valid_org/test-feature-extractor-org" , push_to_hub=lowercase , use_auth_token=self._token ) lowerCamelCase_ = WavaVecaFeatureExtractor.from_pretrained("valid_org/test-feature-extractor-org" ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(lowercase , getattr(lowercase , lowercase ) ) def SCREAMING_SNAKE_CASE_( self ) -> Any: CustomFeatureExtractor.register_for_auto_class() lowerCamelCase_ = CustomFeatureExtractor.from_pretrained(lowercase ) feature_extractor.push_to_hub("test-dynamic-feature-extractor" , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual( feature_extractor.auto_map , {"AutoFeatureExtractor": "custom_feature_extraction.CustomFeatureExtractor"} , ) lowerCamelCase_ = AutoFeatureExtractor.from_pretrained( f'{USER}/test-dynamic-feature-extractor' , trust_remote_code=lowercase ) # Can't make an isinstance check because the new_feature_extractor is from the CustomFeatureExtractor class of a dynamic module self.assertEqual(new_feature_extractor.__class__.__name__ , "CustomFeatureExtractor" )
19
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def UpperCAmelCase__ (lowerCAmelCase_ = 100_0000 , lowerCAmelCase_ = 10 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = defaultdict(lowerCAmelCase_ ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: __SCREAMING_SNAKE_CASE = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: __SCREAMING_SNAKE_CASE = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(lowerCAmelCase_ , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 10 ) if __name__ == "__main__": print(F"{solution() = }")
54
0