code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
import unittest import numpy as np from diffusers import LMSDiscreteScheduler, OnnxStableDiffusionInpaintPipeline from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class _a (SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' pass @nightly @require_onnxruntime @require_torch_gpu class _a (unittest.TestCase ): '''simple docstring''' @property def __A ( self ): return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def __A ( self ): A__ : Optional[int] = ort.SessionOptions() A__ : List[str] = False return options def __A ( self ): A__ : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo.png""" ) A__ : Any = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo_mask.png""" ) A__ : Union[str, Any] = OnnxStableDiffusionInpaintPipeline.from_pretrained( """runwayml/stable-diffusion-inpainting""" , revision="""onnx""" , safety_checker=_lowercase , feature_extractor=_lowercase , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=_lowercase ) A__ : Optional[int] = """A red cat sitting on a park bench""" A__ : Optional[Any] = np.random.RandomState(0 ) A__ : Tuple = pipe( prompt=_lowercase , image=_lowercase , mask_image=_lowercase , guidance_scale=7.5 , num_inference_steps=10 , generator=_lowercase , output_type="""np""" , ) A__ : str = output.images A__ : Any = images[0, 255:258, 255:258, -1] assert images.shape == (1, 512, 512, 3) A__ : Any = np.array([0.2_5_1_4, 0.3_0_0_7, 0.3_5_1_7, 0.1_7_9_0, 0.2_3_8_2, 0.3_1_6_7, 0.1_9_4_4, 0.2_2_7_3, 0.2_4_6_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __A ( self ): A__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo.png""" ) A__ : Any = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo_mask.png""" ) A__ : Dict = LMSDiscreteScheduler.from_pretrained( """runwayml/stable-diffusion-inpainting""" , subfolder="""scheduler""" , revision="""onnx""" ) A__ : str = OnnxStableDiffusionInpaintPipeline.from_pretrained( """runwayml/stable-diffusion-inpainting""" , revision="""onnx""" , scheduler=_lowercase , safety_checker=_lowercase , feature_extractor=_lowercase , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=_lowercase ) A__ : List[Any] = """A red cat sitting on a park bench""" A__ : List[Any] = np.random.RandomState(0 ) A__ : List[Any] = pipe( prompt=_lowercase , image=_lowercase , mask_image=_lowercase , guidance_scale=7.5 , num_inference_steps=20 , generator=_lowercase , output_type="""np""" , ) A__ : Tuple = output.images A__ : int = images[0, 255:258, 255:258, -1] assert images.shape == (1, 512, 512, 3) A__ : Optional[int] = np.array([0.0_0_8_6, 0.0_0_7_7, 0.0_0_8_3, 0.0_0_9_3, 0.0_1_0_7, 0.0_1_3_9, 0.0_0_9_4, 0.0_0_9_7, 0.0_1_2_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
721
import io import itertools import json from dataclasses import dataclass from typing import Optional import pyarrow as pa import pyarrow.json as paj import datasets from datasets.table import table_cast from datasets.utils.file_utils import readline A_ : Tuple = datasets.utils.logging.get_logger(__name__) @dataclass class _a (datasets.BuilderConfig ): '''simple docstring''' UpperCAmelCase__: Optional[datasets.Features] = None UpperCAmelCase__: str = "utf-8" UpperCAmelCase__: Optional[str] = None UpperCAmelCase__: Optional[str] = None UpperCAmelCase__: bool = True # deprecated UpperCAmelCase__: Optional[int] = None # deprecated UpperCAmelCase__: int = 10 << 20 # 10MB UpperCAmelCase__: Optional[bool] = None class _a (datasets.ArrowBasedBuilder ): '''simple docstring''' UpperCAmelCase__: List[str] = JsonConfig def __A ( self ): if self.config.block_size is not None: logger.warning("""The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead""" ) A__ : Union[str, Any] = self.config.block_size if self.config.use_threads is not True: logger.warning( """The JSON loader parameter `use_threads` is deprecated and doesn't have any effect anymore.""" ) if self.config.newlines_in_values is not None: raise ValueError("""The JSON loader parameter `newlines_in_values` is no longer supported""" ) return datasets.DatasetInfo(features=self.config.features ) def __A ( self , A__ ): if not self.config.data_files: raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}""" ) A__ : int = dl_manager.download_and_extract(self.config.data_files ) if isinstance(A__ , (str, list, tuple) ): A__ : Optional[Any] = data_files if isinstance(A__ , A__ ): A__ : List[str] = [files] A__ : int = [dl_manager.iter_files(A__ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""files""": files} )] A__ : List[str] = [] for split_name, files in data_files.items(): if isinstance(A__ , A__ ): A__ : Optional[int] = [files] A__ : Optional[int] = [dl_manager.iter_files(A__ ) for file in files] splits.append(datasets.SplitGenerator(name=A__ , gen_kwargs={"""files""": files} ) ) return splits def __A ( self , A__ ): if self.config.features is not None: # adding missing columns for column_name in set(self.config.features ) - set(pa_table.column_names ): A__ : Optional[Any] = self.config.features.arrow_schema.field(A__ ).type A__ : str = pa_table.append_column(A__ , pa.array([None] * len(A__ ) , type=A__ ) ) # more expensive cast to support nested structures with keys in a different order # allows str <-> int/float or str to Audio for example A__ : Optional[int] = table_cast(A__ , self.config.features.arrow_schema ) return pa_table def __A ( self , A__ ): for file_idx, file in enumerate(itertools.chain.from_iterable(A__ ) ): # If the file is one json object and if we need to look at the list of items in one specific field if self.config.field is not None: with open(A__ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: A__ : Optional[Any] = json.load(A__ ) # We keep only the field we are interested in A__ : Optional[int] = dataset[self.config.field] # We accept two format: a list of dicts or a dict of lists if isinstance(A__ , (list, tuple) ): A__ : Union[str, Any] = set().union(*[row.keys() for row in dataset] ) A__ : Any = {col: [row.get(A__ ) for row in dataset] for col in keys} else: A__ : Any = dataset A__ : Any = pa.Table.from_pydict(A__ ) yield file_idx, self._cast_table(A__ ) # If the file has one json object per line else: with open(A__ , """rb""" ) as f: A__ : List[str] = 0 # Use block_size equal to the chunk size divided by 32 to leverage multithreading # Set a default minimum value of 16kB if the chunk size is really small A__ : List[str] = max(self.config.chunksize // 32 , 16 << 10 ) A__ : Any = ( self.config.encoding_errors if self.config.encoding_errors is not None else """strict""" ) while True: A__ : Dict = f.read(self.config.chunksize ) if not batch: break # Finish current line try: batch += f.readline() except (AttributeError, io.UnsupportedOperation): batch += readline(A__ ) # PyArrow only accepts utf-8 encoded bytes if self.config.encoding != "utf-8": A__ : List[Any] = batch.decode(self.config.encoding , errors=A__ ).encode("""utf-8""" ) try: while True: try: A__ : str = paj.read_json( io.BytesIO(A__ ) , read_options=paj.ReadOptions(block_size=A__ ) ) break except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e: if ( isinstance(A__ , pa.ArrowInvalid ) and "straddling" not in str(A__ ) or block_size > len(A__ ) ): raise else: # Increase the block size in case it was too small. # The block size will be reset for the next file. logger.debug( F"""Batch of {len(A__ )} bytes couldn't be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.""" ) block_size *= 2 except pa.ArrowInvalid as e: try: with open( A__ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: A__ : Optional[Any] = json.load(A__ ) except json.JSONDecodeError: logger.error(F"""Failed to read file '{file}' with error {type(A__ )}: {e}""" ) raise e # If possible, parse the file as a list of json objects and exit the loop if isinstance(A__ , A__ ): # list is the only sequence type supported in JSON try: A__ : str = set().union(*[row.keys() for row in dataset] ) A__ : List[str] = {col: [row.get(A__ ) for row in dataset] for col in keys} A__ : int = pa.Table.from_pydict(A__ ) except (pa.ArrowInvalid, AttributeError) as e: logger.error(F"""Failed to read file '{file}' with error {type(A__ )}: {e}""" ) raise ValueError(F"""Not able to read records in the JSON file at {file}.""" ) from None yield file_idx, self._cast_table(A__ ) break else: logger.error(F"""Failed to read file '{file}' with error {type(A__ )}: {e}""" ) raise ValueError( F"""Not able to read records in the JSON file at {file}. """ F"""You should probably indicate the field of the JSON file containing your records. """ F"""This JSON file contain the following fields: {str(list(dataset.keys() ) )}. """ F"""Select the correct one and provide it as `field='XXX'` to the dataset loading method. """ ) from None # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(A__ ) batch_idx += 1
64
0
from jiwer import compute_measures import datasets A_ : str = '\\n@inproceedings{inproceedings,\n author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n year = {2004},\n month = {01},\n pages = {},\n title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n' A_ : Tuple = '\\nWord error rate (WER) is a common metric of the performance of an automatic speech recognition system.\n\nThe 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.\n\nThis 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.\n\nWord error rate can then be computed as:\n\nWER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct words,\nN is the number of words in the reference (N=S+D+C).\n\nThis value indicates the average number of errors per reference word. The lower the value, the better the\nperformance of the ASR system with a WER of 0 being a perfect score.\n' A_ : List[Any] = '\nCompute WER score of transcribed segments against references.\n\nArgs:\n references: List of references for each speech input.\n predictions: List of transcriptions to score.\n concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.\n\nReturns:\n (float): the word error rate\n\nExamples:\n\n >>> predictions = ["this is the prediction", "there is an other sample"]\n >>> references = ["this is the reference", "there is another one"]\n >>> wer = datasets.load_metric("wer")\n >>> wer_score = wer.compute(predictions=predictions, references=references)\n >>> print(wer_score)\n 0.5\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _a (datasets.Metric ): '''simple docstring''' def __A ( self ): 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 __A ( self , A__=None , A__=None , A__=False ): if concatenate_texts: return compute_measures(A_ , A_ )["wer"] else: A__ : List[Any] = 0 A__ : List[str] = 0 for prediction, reference in zip(A_ , A_ ): A__ : List[Any] = compute_measures(A_ , A_ ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
700
import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore A_ : Dict = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" A_ : Optional[Any] = [file for file in filepaths if file != file.lower()] if upper_files: print(f'''{len(upper_files)} files contain uppercase characters:''') print('\n'.join(upper_files) + '\n') A_ : Tuple = [file for file in filepaths if ' ' in file] if space_files: print(f'''{len(space_files)} files contain space characters:''') print('\n'.join(space_files) + '\n') A_ : Any = [file for file in filepaths if '-' in file] if hyphen_files: print(f'''{len(hyphen_files)} files contain hyphen characters:''') print('\n'.join(hyphen_files) + '\n') A_ : List[str] = [file for file in filepaths if os.sep not in file] if nodir_files: print(f'''{len(nodir_files)} files are not in a directory:''') print('\n'.join(nodir_files) + '\n') A_ : Any = len(upper_files + space_files + hyphen_files + nodir_files) if bad_files: import sys sys.exit(bad_files)
64
0
from __future__ import annotations import math import random from typing import Any class _a : '''simple docstring''' def __init__( self ): A__ : Optional[Any] = [] A__ : List[Any] = 0 A__ : List[Any] = 0 def __A ( self ): return self.head == self.tail def __A ( self , A__ ): self.data.append(A__ ) A__ : List[str] = self.tail + 1 def __A ( self ): A__ : List[Any] = self.data[self.head] A__ : str = self.head + 1 return ret def __A ( self ): return self.tail - self.head def __A ( self ): print(self.data ) print("""**************""" ) print(self.data[self.head : self.tail] ) class _a : '''simple docstring''' def __init__( self , A__ ): A__ : List[Any] = data A__ : int = None A__ : Optional[int] = None A__ : List[str] = 1 def __A ( self ): return self.data def __A ( self ): return self.left def __A ( self ): return self.right def __A ( self ): return self.height def __A ( self , A__ ): A__ : List[str] = data def __A ( self , A__ ): A__ : int = node def __A ( self , A__ ): A__ : Any = node def __A ( self , A__ ): A__ : Dict = height def UpperCamelCase (lowercase_: Tuple ) -> int: if node is None: return 0 return node.get_height() def UpperCamelCase (lowercase_: Any , lowercase_: str ) -> int: if a > b: return a return b def UpperCamelCase (lowercase_: Union[str, Any] ) -> MyNode: print("""left rotation node:""" , node.get_data() ) A__ : Any = node.get_left() assert ret is not None node.set_left(ret.get_right() ) ret.set_right(__SCREAMING_SNAKE_CASE ) A__ : Union[str, Any] = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(__SCREAMING_SNAKE_CASE ) A__ : str = my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(__SCREAMING_SNAKE_CASE ) return ret def UpperCamelCase (lowercase_: str ) -> MyNode: print("""right rotation node:""" , node.get_data() ) A__ : List[Any] = node.get_right() assert ret is not None node.set_right(ret.get_left() ) ret.set_left(__SCREAMING_SNAKE_CASE ) A__ : str = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(__SCREAMING_SNAKE_CASE ) A__ : Any = my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(__SCREAMING_SNAKE_CASE ) return ret def UpperCamelCase (lowercase_: List[Any] ) -> MyNode: A__ : str = node.get_left() assert left_child is not None node.set_left(left_rotation(__SCREAMING_SNAKE_CASE ) ) return right_rotation(__SCREAMING_SNAKE_CASE ) def UpperCamelCase (lowercase_: Union[str, Any] ) -> MyNode: A__ : Tuple = node.get_right() assert right_child is not None node.set_right(right_rotation(__SCREAMING_SNAKE_CASE ) ) return left_rotation(__SCREAMING_SNAKE_CASE ) def UpperCamelCase (lowercase_: str , lowercase_: Optional[int] ) -> MyNode | None: if node is None: return MyNode(__SCREAMING_SNAKE_CASE ) if data < node.get_data(): node.set_left(insert_node(node.get_left() , __SCREAMING_SNAKE_CASE ) ) if ( get_height(node.get_left() ) - get_height(node.get_right() ) == 2 ): # an unbalance detected A__ : Union[str, Any] = node.get_left() assert left_child is not None if ( data < left_child.get_data() ): # new node is the left child of the left child A__ : List[Any] = right_rotation(__SCREAMING_SNAKE_CASE ) else: A__ : int = lr_rotation(__SCREAMING_SNAKE_CASE ) else: node.set_right(insert_node(node.get_right() , __SCREAMING_SNAKE_CASE ) ) if get_height(node.get_right() ) - get_height(node.get_left() ) == 2: A__ : List[str] = node.get_right() assert right_child is not None if data < right_child.get_data(): A__ : Any = rl_rotation(__SCREAMING_SNAKE_CASE ) else: A__ : str = left_rotation(__SCREAMING_SNAKE_CASE ) A__ : Union[str, Any] = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(__SCREAMING_SNAKE_CASE ) return node def UpperCamelCase (lowercase_: Dict ) -> Any: while True: A__ : int = root.get_right() if right_child is None: break A__ : Optional[int] = right_child return root.get_data() def UpperCamelCase (lowercase_: List[str] ) -> Any: while True: A__ : Dict = root.get_left() if left_child is None: break A__ : Optional[int] = left_child return root.get_data() def UpperCamelCase (lowercase_: Union[str, Any] , lowercase_: Optional[int] ) -> MyNode | None: A__ : Optional[int] = root.get_left() A__ : Optional[int] = root.get_right() if root.get_data() == data: if left_child is not None and right_child is not None: A__ : str = get_left_most(__SCREAMING_SNAKE_CASE ) root.set_data(__SCREAMING_SNAKE_CASE ) root.set_right(del_node(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) elif left_child is not None: A__ : Optional[int] = left_child elif right_child is not None: A__ : List[str] = right_child else: return None elif root.get_data() > data: if left_child is None: print("""No such data""" ) return root else: root.set_left(del_node(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) else: # root.get_data() < data if right_child is None: return root else: root.set_right(del_node(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) if get_height(__SCREAMING_SNAKE_CASE ) - get_height(__SCREAMING_SNAKE_CASE ) == 2: assert right_child is not None if get_height(right_child.get_right() ) > get_height(right_child.get_left() ): A__ : Optional[Any] = left_rotation(__SCREAMING_SNAKE_CASE ) else: A__ : List[str] = rl_rotation(__SCREAMING_SNAKE_CASE ) elif get_height(__SCREAMING_SNAKE_CASE ) - get_height(__SCREAMING_SNAKE_CASE ) == -2: assert left_child is not None if get_height(left_child.get_left() ) > get_height(left_child.get_right() ): A__ : Any = right_rotation(__SCREAMING_SNAKE_CASE ) else: A__ : Any = lr_rotation(__SCREAMING_SNAKE_CASE ) A__ : List[Any] = my_max(get_height(root.get_right() ) , get_height(root.get_left() ) ) + 1 root.set_height(__SCREAMING_SNAKE_CASE ) return root class _a : '''simple docstring''' def __init__( self ): A__ : Any = None def __A ( self ): return get_height(self.root ) def __A ( self , A__ ): print("""insert:""" + str(A__ ) ) A__ : str = insert_node(self.root , A__ ) def __A ( self , A__ ): print("""delete:""" + str(A__ ) ) if self.root is None: print("""Tree is empty!""" ) return A__ : Optional[int] = del_node(self.root , A__ ) def __str__( self , ): # a level traversale, gives a more intuitive look on the tree A__ : int = """""" A__ : int = MyQueue() q.push(self.root ) A__ : Optional[int] = self.get_height() if layer == 0: return output A__ : List[str] = 0 while not q.is_empty(): A__ : List[Any] = q.pop() A__ : List[str] = """ """ * int(math.pow(2 , layer - 1 ) ) output += space if node is None: output += "*" q.push(A__ ) q.push(A__ ) else: output += str(node.get_data() ) q.push(node.get_left() ) q.push(node.get_right() ) output += space A__ : List[Any] = cnt + 1 for i in range(100 ): if cnt == math.pow(2 , A__ ) - 1: A__ : int = layer - 1 if layer == 0: output += "\n*************************************" return output output += "\n" break output += "\n*************************************" return output def UpperCamelCase () -> None: import doctest doctest.testmod() if __name__ == "__main__": _test() A_ : Optional[Any] = AVLtree() A_ : List[str] = list(range(10)) random.shuffle(lst) for i in lst: t.insert(i) print(str(t)) random.shuffle(lst) for i in lst: t.del_node(i) print(str(t))
701
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def UpperCamelCase (*lowercase_: Optional[int] , lowercase_: Optional[Union[Dict, Any]] = None , lowercase_: Dict=True , lowercase_: Tuple=2 ) -> Dict: from .. import __version__ A__ : Dict = take_from A__ : str = () if not isinstance(args[0] , lowercase_ ): A__ : int = (args,) for attribute, version_name, message in args: if version.parse(version.parse(lowercase_ ).base_version ) >= version.parse(lowercase_ ): raise ValueError( f"""The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers'""" f""" version {__version__} is >= {version_name}""" ) A__ : Any = None if isinstance(lowercase_ , lowercase_ ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(lowercase_ ),) A__ : List[str] = f"""The `{attribute}` argument is deprecated and will be removed in version {version_name}.""" elif hasattr(lowercase_ , lowercase_ ): values += (getattr(lowercase_ , lowercase_ ),) A__ : Optional[Any] = f"""The `{attribute}` attribute is deprecated and will be removed in version {version_name}.""" elif deprecated_kwargs is None: A__ : int = f"""`{attribute}` is deprecated and will be removed in version {version_name}.""" if warning is not None: A__ : int = warning + """ """ if standard_warn else """""" warnings.warn(warning + message , lowercase_ , stacklevel=lowercase_ ) if isinstance(lowercase_ , lowercase_ ) and len(lowercase_ ) > 0: A__ : Union[str, Any] = inspect.getouterframes(inspect.currentframe() )[1] A__ : Optional[Any] = call_frame.filename A__ : Optional[int] = call_frame.lineno A__ : Any = call_frame.function A__ , A__ : List[str] = next(iter(deprecated_kwargs.items() ) ) raise TypeError(f"""{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`""" ) if len(lowercase_ ) == 0: return elif len(lowercase_ ) == 1: return values[0] return values
64
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A_ : Dict = { 'configuration_clipseg': [ 'CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CLIPSegConfig', 'CLIPSegTextConfig', 'CLIPSegVisionConfig', ], 'processing_clipseg': ['CLIPSegProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Dict = [ 'CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST', 'CLIPSegModel', 'CLIPSegPreTrainedModel', 'CLIPSegTextModel', 'CLIPSegVisionModel', 'CLIPSegForImageSegmentation', ] if TYPE_CHECKING: from .configuration_clipseg import ( CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPSegConfig, CLIPSegTextConfig, CLIPSegVisionConfig, ) from .processing_clipseg import CLIPSegProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clipseg import ( CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPSegForImageSegmentation, CLIPSegModel, CLIPSegPreTrainedModel, CLIPSegTextModel, CLIPSegVisionModel, ) else: import sys A_ : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
702
import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import ( rename_keys, ) from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME from transformers.utils.hub import convert_file_size_to_int def UpperCamelCase (lowercase_: List[str] , lowercase_: str ) -> Optional[Any]: if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer A__ : Union[str, Any] = flax_key_tuple[:-1] + ("""weight""",) A__ : Optional[int] = torch.permute(lowercase_ , (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(lowercase_ ): # linear layer A__ : Optional[Any] = flax_key_tuple[:-1] + ("""weight""",) A__ : int = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: A__ : Optional[int] = flax_key_tuple[:-1] + ("""weight""",) return flax_key_tuple, flax_tensor def UpperCamelCase (lowercase_: Tuple , lowercase_: Optional[int] , lowercase_: str ) -> Union[str, Any]: if "metadata" in layer: A__ : Tuple = layer.split("""metadata""" ) A__ : Optional[Any] = """""".join(split_layer[0] )[:-1] A__ : Optional[Any] = [tuple(("""metadata""" + split_layer[1]).split("""/""" ) )] elif "kvstore" in layer: A__ : str = layer.split("""kvstore""" ) A__ : int = """""".join(split_layer[0] )[:-1] A__ : Optional[int] = [tuple(("""kvstore""" + split_layer[1]).split("""/""" ) )] else: A__ : Any = layer.split("""/""" ) A__ : int = """/""".join(split_layer[:-1] ) A__ : str = (split_layer[-1],) if "kvstore/path" in layer: A__ : Dict = f"""{switch_checkpoint_path}/{checkpoint_info[layer]}""" elif "kvstore/driver" in layer: A__ : Optional[int] = """file""" else: A__ : str = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def UpperCamelCase (lowercase_: str , lowercase_: List[Any] ) -> int: A__ : int = rename_keys(lowercase_ ) A__ : Any = {} for k, v in current_block.items(): A__ : Dict = v A__ : str = new_current_block torch.save(lowercase_ , lowercase_ ) def UpperCamelCase (lowercase_: Dict , lowercase_: Optional[Any] , lowercase_: Optional[Any] , lowercase_: Optional[int] , lowercase_: str = WEIGHTS_NAME ) -> Tuple: A__ : Optional[int] = convert_file_size_to_int(lowercase_ ) A__ : List[Any] = [] A__ : int = {} A__ : List[str] = 0 A__ : Any = 0 os.makedirs(lowercase_ , exist_ok=lowercase_ ) with gfile.GFile(switch_checkpoint_path + """/checkpoint""" , """rb""" ) as fp: A__ : Optional[Any] = serialization.msgpack_restore(fp.read() )["""optimizer"""]["""target"""] A__ : Dict = flatten_dict(lowercase_ , sep="""/""" ) A__ : Any = {} for layer in checkpoint_info.keys(): A__ , A__ , A__ : Union[str, Any] = get_key_and_tensorstore_dict( lowercase_ , lowercase_ , lowercase_ ) if curr_real_layer_name in all_layers: A__ : Optional[int] = content else: A__ : List[Any] = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file A__ : Optional[Any] = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() A__ : List[Any] = torch.tensor(lowercase_ ) A__ : List[Any] = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts A__ , A__ : Any = rename_base_flax_keys(tuple(key.split("""/""" ) ) , lowercase_ ) A__ : Any = """/""".join(lowercase_ ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: A__ : List[Any] = os.path.join( lowercase_ , weights_name.replace(""".bin""" , f"""-{len(lowercase_ )+1:05d}-of-???.bin""" ) ) rename_and_save_block(lowercase_ , lowercase_ ) sharded_state_dicts.append(current_block.keys() ) del current_block A__ : Any = {} A__ : str = 0 A__ : List[str] = raw_weights.to(getattr(lowercase_ , lowercase_ ) ) current_block_size += weight_size total_size += weight_size # Add the last block A__ : Union[str, Any] = os.path.join(lowercase_ , weights_name.replace(""".bin""" , f"""-{len(lowercase_ )+1:05d}-of-???.bin""" ) ) rename_and_save_block(lowercase_ , lowercase_ ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(lowercase_ ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index A__ : str = {} A__ : Any = {} for idx, shard in enumerate(lowercase_ ): A__ : Any = weights_name.replace( """.bin""" , f"""-{idx+1:05d}-of-{len(lowercase_ ):05d}.bin""" ) # len(sharded_state_dicts):05d} A__ : Dict = os.path.join(lowercase_ , weights_name.replace(""".bin""" , f"""-{idx+1:05d}-of-???.bin""" ) ) os.rename(lowercase_ , os.path.join(lowercase_ , lowercase_ ) ) A__ : str = shard for key in shard: A__ : Any = shard_file # Add the metadata A__ : Tuple = {"""total_size""": total_size} A__ : Union[str, Any] = {"""metadata""": metadata, """weight_map""": weight_map} with open(os.path.join(lowercase_ , lowercase_ ) , """w""" , encoding="""utf-8""" ) as f: A__ : Dict = json.dumps(lowercase_ , indent=2 , sort_keys=lowercase_ ) + """\n""" f.write(lowercase_ ) return metadata, index if __name__ == "__main__": A_ : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--switch_t5x_checkpoint_path', default='/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600', type=str, required=False, help='Path to a directory containing a folder per layer. Follows the original Google format.', ) parser.add_argument('--max_shard_size', default='10GB', required=False, help='Max shard size') parser.add_argument('--dtype', default='bfloat16', type=str, required=False, help='dtype of the saved model') parser.add_argument( '--pytorch_dump_folder_path', default='/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted', type=str, required=False, help='Path to the output pytorch model.', ) A_ : Dict = parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def UpperCamelCase () -> int: from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer A__ : str = SwitchTransformersConfig.from_pretrained("""google/switch-base-8""" ) config.save_pretrained("""/home/arthur_huggingface_co/transformers/switch_converted""" ) A__ : str = SwitchTransformersForConditionalGeneration.from_pretrained( """/home/arthur_huggingface_co/transformers/switch_converted""" , device_map="""auto""" ) A__ : Tuple = TaTokenizer.from_pretrained("""t5-small""" ) A__ : Dict = """A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.""" A__ : Union[str, Any] = tokenizer(lowercase_ , return_tensors="""pt""" ).input_ids A__ : Tuple = model.generate(lowercase_ , decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
64
0
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_big_bird import BigBirdTokenizer else: A_ : Dict = None A_ : Tuple = logging.get_logger(__name__) A_ : Dict = {"""vocab_file""": """spiece.model""", """tokenizer_file""": """tokenizer.json"""} A_ : Optional[Any] = { """vocab_file""": { """google/bigbird-roberta-base""": """https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model""", """google/bigbird-roberta-large""": ( """https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model""" ), """google/bigbird-base-trivia-itc""": ( """https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model""" ), }, """tokenizer_file""": { """google/bigbird-roberta-base""": ( """https://huggingface.co/google/bigbird-roberta-base/resolve/main/tokenizer.json""" ), """google/bigbird-roberta-large""": ( """https://huggingface.co/google/bigbird-roberta-large/resolve/main/tokenizer.json""" ), """google/bigbird-base-trivia-itc""": ( """https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/tokenizer.json""" ), }, } A_ : int = { """google/bigbird-roberta-base""": 4096, """google/bigbird-roberta-large""": 4096, """google/bigbird-base-trivia-itc""": 4096, } A_ : List[str] = """▁""" class _a (UpperCamelCase_ ): '''simple docstring''' UpperCAmelCase__: Optional[int] = VOCAB_FILES_NAMES UpperCAmelCase__: Any = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__: int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__: Any = BigBirdTokenizer UpperCAmelCase__: str = ['''input_ids''', '''attention_mask'''] UpperCAmelCase__: List[str] = [] def __init__( self , A__=None , A__=None , A__="<unk>" , A__="<s>" , A__="</s>" , A__="<pad>" , A__="[SEP]" , A__="[MASK]" , A__="[CLS]" , **A__ , ): A__ : Tuple = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else bos_token A__ : Union[str, Any] = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else eos_token A__ : Union[str, Any] = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else unk_token A__ : Optional[int] = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else pad_token A__ : int = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else cls_token A__ : str = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else sep_token # Mask token behave like a normal word, i.e. include the space before it A__ : Union[str, Any] = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token super().__init__( __A , tokenizer_file=__A , bos_token=__A , eos_token=__A , unk_token=__A , sep_token=__A , pad_token=__A , cls_token=__A , mask_token=__A , **__A , ) A__ : List[Any] = vocab_file A__ : Tuple = False if not self.vocab_file else True def __A ( self , A__ , A__ = None ): A__ : str = [self.sep_token_id] A__ : List[str] = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def __A ( self , A__ , A__ = None , A__ = False ): if already_has_special_tokens: if token_ids_a is not None: raise ValueError( """You should not supply a second sequence if the provided sequence of """ """ids is already formatted with special tokens for the model.""" ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is None: return [1] + ([0] * len(__A )) + [1] return [1] + ([0] * len(__A )) + [1] + ([0] * len(__A )) + [1] def __A ( self , A__ , A__ = None ): A__ : Union[str, Any] = [self.sep_token_id] A__ : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __A ( self , A__ , A__ = None ): if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(__A ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return A__ : Any = os.path.join( __A , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__A ): copyfile(self.vocab_file , __A ) return (out_vocab_file,)
703
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available A_ : Optional[Any] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : str = ['BartphoTokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bartpho import BartphoTokenizer else: import sys A_ : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
64
0
from .glue import glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels from .squad import SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features from .utils import DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor from .xnli import xnli_output_modes, xnli_processors, xnli_tasks_num_labels
704
import argparse import hashlib import os import urllib import warnings import torch from torch import nn from tqdm import tqdm from transformers import WhisperConfig, WhisperForConditionalGeneration A_ : Dict = { 'tiny.en': 'https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt', 'tiny': 'https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt', 'base.en': 'https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt', 'base': 'https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt', 'small.en': 'https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt', 'small': 'https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt', 'medium.en': 'https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt', 'medium': 'https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt', 'large': 'https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt', 'large-v2': 'https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt', } def UpperCamelCase (lowercase_: Optional[Any] ) -> Optional[int]: A__ : List[Any] = ["""layers""", """blocks"""] for k in ignore_keys: state_dict.pop(lowercase_ , lowercase_ ) A_ : Any = { 'blocks': 'layers', 'mlp.0': 'fc1', 'mlp.2': 'fc2', 'mlp_ln': 'final_layer_norm', '.attn.query': '.self_attn.q_proj', '.attn.key': '.self_attn.k_proj', '.attn.value': '.self_attn.v_proj', '.attn_ln': '.self_attn_layer_norm', '.attn.out': '.self_attn.out_proj', '.cross_attn.query': '.encoder_attn.q_proj', '.cross_attn.key': '.encoder_attn.k_proj', '.cross_attn.value': '.encoder_attn.v_proj', '.cross_attn_ln': '.encoder_attn_layer_norm', '.cross_attn.out': '.encoder_attn.out_proj', 'decoder.ln.': 'decoder.layer_norm.', 'encoder.ln.': 'encoder.layer_norm.', 'token_embedding': 'embed_tokens', 'encoder.positional_embedding': 'encoder.embed_positions.weight', 'decoder.positional_embedding': 'decoder.embed_positions.weight', 'ln_post': 'layer_norm', } def UpperCamelCase (lowercase_: str ) -> Any: A__ : Dict = list(s_dict.keys() ) for key in keys: A__ : List[str] = key for k, v in WHISPER_MAPPING.items(): if k in key: A__ : List[Any] = new_key.replace(lowercase_ , lowercase_ ) print(f"""{key} -> {new_key}""" ) A__ : Tuple = s_dict.pop(lowercase_ ) return s_dict def UpperCamelCase (lowercase_: Tuple ) -> Optional[int]: A__ , A__ : Any = emb.weight.shape A__ : str = nn.Linear(lowercase_ , lowercase_ , bias=lowercase_ ) A__ : Union[str, Any] = emb.weight.data return lin_layer def UpperCamelCase (lowercase_: str , lowercase_: str ) -> bytes: os.makedirs(lowercase_ , exist_ok=lowercase_ ) A__ : Tuple = os.path.basename(lowercase_ ) A__ : int = url.split("""/""" )[-2] A__ : Dict = os.path.join(lowercase_ , lowercase_ ) if os.path.exists(lowercase_ ) and not os.path.isfile(lowercase_ ): raise RuntimeError(f"""{download_target} exists and is not a regular file""" ) if os.path.isfile(lowercase_ ): A__ : Optional[Any] = open(lowercase_ , """rb""" ).read() if hashlib.shaaaa(lowercase_ ).hexdigest() == expected_shaaaa: return model_bytes else: warnings.warn(f"""{download_target} exists, but the SHA256 checksum does not match; re-downloading the file""" ) with urllib.request.urlopen(lowercase_ ) as source, open(lowercase_ , """wb""" ) as output: with tqdm( total=int(source.info().get("""Content-Length""" ) ) , ncols=80 , unit="""iB""" , unit_scale=lowercase_ , unit_divisor=1024 ) as loop: while True: A__ : Any = source.read(8192 ) if not buffer: break output.write(lowercase_ ) loop.update(len(lowercase_ ) ) A__ : Dict = open(lowercase_ , """rb""" ).read() if hashlib.shaaaa(lowercase_ ).hexdigest() != expected_shaaaa: raise RuntimeError( """Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model.""" ) return model_bytes def UpperCamelCase (lowercase_: List[Any] , lowercase_: Tuple ) -> Optional[Any]: if ".pt" not in checkpoint_path: A__ : Tuple = _download(_MODELS[checkpoint_path] ) else: A__ : Optional[int] = torch.load(lowercase_ , map_location="""cpu""" ) A__ : str = original_checkpoint["""dims"""] A__ : List[Any] = original_checkpoint["""model_state_dict"""] A__ : Optional[Any] = state_dict["""decoder.token_embedding.weight"""] remove_ignore_keys_(lowercase_ ) rename_keys(lowercase_ ) A__ : List[str] = True A__ : Optional[Any] = state_dict["""decoder.layers.0.fc1.weight"""].shape[0] A__ : List[Any] = WhisperConfig( vocab_size=dimensions["""n_vocab"""] , encoder_ffn_dim=lowercase_ , decoder_ffn_dim=lowercase_ , num_mel_bins=dimensions["""n_mels"""] , d_model=dimensions["""n_audio_state"""] , max_target_positions=dimensions["""n_text_ctx"""] , encoder_layers=dimensions["""n_audio_layer"""] , encoder_attention_heads=dimensions["""n_audio_head"""] , decoder_layers=dimensions["""n_text_layer"""] , decoder_attention_heads=dimensions["""n_text_state"""] , max_source_positions=dimensions["""n_audio_ctx"""] , ) A__ : Optional[Any] = WhisperForConditionalGeneration(lowercase_ ) A__ , A__ : List[Any] = model.model.load_state_dict(lowercase_ , strict=lowercase_ ) if len(lowercase_ ) > 0 and not set(lowercase_ ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( """Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,""" f""" but all the following weights are missing {missing}""" ) if tie_embeds: A__ : Any = make_linear_from_emb(model.model.decoder.embed_tokens ) else: A__ : str = proj_out_weights model.save_pretrained(lowercase_ ) if __name__ == "__main__": A_ : Any = argparse.ArgumentParser() # # Required parameters parser.add_argument('--checkpoint_path', type=str, help='Patht to the downloaded checkpoints') parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') A_ : Tuple = parser.parse_args() convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)
64
0
import gc import unittest from diffusers import FlaxControlNetModel, FlaxStableDiffusionControlNetPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class _a (unittest.TestCase ): '''simple docstring''' def __A ( self ): super().tearDown() gc.collect() def __A ( self ): A__ : Tuple = FlaxControlNetModel.from_pretrained( """lllyasviel/sd-controlnet-canny""" , from_pt=_a , dtype=jnp.bfloataa ) A__ : Dict = FlaxStableDiffusionControlNetPipeline.from_pretrained( """runwayml/stable-diffusion-v1-5""" , controlnet=_a , from_pt=_a , dtype=jnp.bfloataa ) A__ : List[str] = controlnet_params A__ : Any = """bird""" A__ : str = jax.device_count() A__ : Tuple = pipe.prepare_text_inputs([prompts] * num_samples ) A__ : Any = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png""" ) A__ : Union[str, Any] = pipe.prepare_image_inputs([canny_image] * num_samples ) A__ : Optional[Any] = jax.random.PRNGKey(0 ) A__ : Union[str, Any] = jax.random.split(_a , jax.device_count() ) A__ : int = replicate(_a ) A__ : List[str] = shard(_a ) A__ : str = shard(_a ) A__ : Optional[Any] = pipe( prompt_ids=_a , image=_a , params=_a , prng_seed=_a , num_inference_steps=50 , jit=_a , ).images assert images.shape == (jax.device_count(), 1, 768, 512, 3) A__ : str = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) A__ : Union[str, Any] = images[0, 253:256, 253:256, -1] A__ : Optional[Any] = jnp.asarray(jax.device_get(image_slice.flatten() ) ) A__ : Optional[int] = jnp.array( [0.1_6_7_9_6_9, 0.1_1_6_6_9_9, 0.0_8_1_5_4_3, 0.1_5_4_2_9_7, 0.1_3_2_8_1_2, 0.1_0_8_8_8_7, 0.1_6_9_9_2_2, 0.1_6_9_9_2_2, 0.2_0_5_0_7_8] ) print(F"""output_slice: {output_slice}""" ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2 def __A ( self ): A__ : Dict = FlaxControlNetModel.from_pretrained( """lllyasviel/sd-controlnet-openpose""" , from_pt=_a , dtype=jnp.bfloataa ) A__ : int = FlaxStableDiffusionControlNetPipeline.from_pretrained( """runwayml/stable-diffusion-v1-5""" , controlnet=_a , from_pt=_a , dtype=jnp.bfloataa ) A__ : Tuple = controlnet_params A__ : int = """Chef in the kitchen""" A__ : Any = jax.device_count() A__ : Any = pipe.prepare_text_inputs([prompts] * num_samples ) A__ : Union[str, Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/pose.png""" ) A__ : str = pipe.prepare_image_inputs([pose_image] * num_samples ) A__ : Optional[Any] = jax.random.PRNGKey(0 ) A__ : Dict = jax.random.split(_a , jax.device_count() ) A__ : Any = replicate(_a ) A__ : Union[str, Any] = shard(_a ) A__ : int = shard(_a ) A__ : str = pipe( prompt_ids=_a , image=_a , params=_a , prng_seed=_a , num_inference_steps=50 , jit=_a , ).images assert images.shape == (jax.device_count(), 1, 768, 512, 3) A__ : Optional[int] = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) A__ : Union[str, Any] = images[0, 253:256, 253:256, -1] A__ : List[Any] = jnp.asarray(jax.device_get(image_slice.flatten() ) ) A__ : Optional[Any] = jnp.array( [[0.2_7_1_4_8_4, 0.2_6_1_7_1_9, 0.2_7_5_3_9_1, 0.2_7_7_3_4_4, 0.2_7_9_2_9_7, 0.2_9_1_0_1_6, 0.2_9_4_9_2_2, 0.3_0_2_7_3_4, 0.3_0_2_7_3_4]] ) print(F"""output_slice: {output_slice}""" ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
705
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DPMSolverMultistepScheduler, TextToVideoSDPipeline, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class _a (__magic_name__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: Any = TextToVideoSDPipeline UpperCAmelCase__: Any = TEXT_TO_IMAGE_PARAMS UpperCAmelCase__: Optional[Any] = TEXT_TO_IMAGE_BATCH_PARAMS # No `output_type`. UpperCAmelCase__: Optional[int] = frozenset( [ '''num_inference_steps''', '''generator''', '''latents''', '''return_dict''', '''callback''', '''callback_steps''', ] ) def __A ( self ): torch.manual_seed(0 ) A__ : Optional[int] = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """DownBlock3D""") , up_block_types=("""UpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""") , cross_attention_dim=32 , attention_head_dim=4 , ) A__ : Optional[int] = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule="""scaled_linear""" , clip_sample=A__ , set_alpha_to_one=A__ , ) torch.manual_seed(0 ) A__ : Union[str, Any] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) A__ : Union[str, Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act="""gelu""" , projection_dim=512 , ) A__ : Union[str, Any] = CLIPTextModel(A__ ) A__ : Tuple = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) A__ : Dict = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, } return components def __A ( self , A__ , A__=0 ): if str(A__ ).startswith("""mps""" ): A__ : Tuple = torch.manual_seed(A__ ) else: A__ : List[str] = torch.Generator(device=A__ ).manual_seed(A__ ) A__ : List[str] = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """pt""", } return inputs def __A ( self ): A__ : List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator A__ : Union[str, Any] = self.get_dummy_components() A__ : Union[str, Any] = TextToVideoSDPipeline(**A__ ) A__ : int = sd_pipe.to(A__ ) sd_pipe.set_progress_bar_config(disable=A__ ) A__ : int = self.get_dummy_inputs(A__ ) A__ : int = """np""" A__ : Any = sd_pipe(**A__ ).frames A__ : Dict = frames[0][-3:, -3:, -1] assert frames[0].shape == (64, 64, 3) A__ : Optional[Any] = np.array([1_5_8.0, 1_6_0.0, 1_5_3.0, 1_2_5.0, 1_0_0.0, 1_2_1.0, 1_1_1.0, 9_3.0, 1_1_3.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __A ( self ): self._test_attention_slicing_forward_pass(test_mean_pixel_difference=A__ , expected_max_diff=3e-3 ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def __A ( self ): self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=A__ , expected_max_diff=1e-2 ) @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def __A ( self ): pass @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def __A ( self ): pass @unittest.skip(reason="""`num_images_per_prompt` argument is not supported for this pipeline.""" ) def __A ( self ): pass def __A ( self ): return super().test_progress_bar() @slow @skip_mps class _a (unittest.TestCase ): '''simple docstring''' def __A ( self ): A__ : Union[str, Any] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy""" ) A__ : Tuple = TextToVideoSDPipeline.from_pretrained("""damo-vilab/text-to-video-ms-1.7b""" ) A__ : Any = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) A__ : int = pipe.to("""cuda""" ) A__ : Optional[Any] = """Spiderman is surfing""" A__ : List[str] = torch.Generator(device="""cpu""" ).manual_seed(0 ) A__ : Optional[Any] = pipe(A__ , generator=A__ , num_inference_steps=25 , output_type="""pt""" ).frames A__ : Dict = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5e-2 def __A ( self ): A__ : List[Any] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy""" ) A__ : Optional[int] = TextToVideoSDPipeline.from_pretrained("""damo-vilab/text-to-video-ms-1.7b""" ) A__ : List[str] = pipe.to("""cuda""" ) A__ : Dict = """Spiderman is surfing""" A__ : Union[str, Any] = torch.Generator(device="""cpu""" ).manual_seed(0 ) A__ : Optional[int] = pipe(A__ , generator=A__ , num_inference_steps=2 , output_type="""pt""" ).frames A__ : Optional[int] = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5e-2
64
0
import argparse import math import traceback import dateutil.parser as date_parser import requests def UpperCamelCase ( lowercase_: Any ) -> int: A__ : Dict = {} A__ : Union[str, Any] = job["""started_at"""] A__ : Any = job["""completed_at"""] A__ : Optional[int] = date_parser.parse(snake_case__ ) A__ : List[str] = date_parser.parse(snake_case__ ) A__ : int = round((end_datetime - start_datetime).total_seconds() / 60.0 ) A__ : Dict = start A__ : Dict = end A__ : Any = duration_in_min return job_info def UpperCamelCase ( lowercase_: Tuple , lowercase_: Tuple=None ) -> List[Any]: A__ : Optional[Any] = None if token is not None: A__ : List[str] = {"""Accept""": """application/vnd.github+json""", """Authorization""": f"""Bearer {token}"""} A__ : Tuple = f"""https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100""" A__ : Optional[Any] = requests.get(snake_case__ , headers=snake_case__ ).json() A__ : int = {} try: job_time.update({job["""name"""]: extract_time_from_single_job(snake_case__ ) for job in result["""jobs"""]} ) A__ : Optional[int] = math.ceil((result["""total_count"""] - 100) / 100 ) for i in range(snake_case__ ): A__ : List[str] = requests.get(url + f"""&page={i + 2}""" , headers=snake_case__ ).json() job_time.update({job["""name"""]: extract_time_from_single_job(snake_case__ ) for job in result["""jobs"""]} ) return job_time except Exception: print(f"""Unknown error, could not fetch links:\n{traceback.format_exc()}""" ) return {} if __name__ == "__main__": A_ : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument('--workflow_run_id', type=str, required=True, help='A GitHub Actions workflow run id.') A_ : Optional[int] = parser.parse_args() A_ : Any = get_job_time(args.workflow_run_id) A_ : List[str] = dict(sorted(job_time.items(), key=lambda item: item[1]["duration"], reverse=True)) for k, v in job_time.items(): print(f'''{k}: {v["duration"]}''')
706
def UpperCamelCase (lowercase_: int ) -> int: if not isinstance(lowercase_ , lowercase_ ): raise TypeError("""Input value must be an 'int' type""" ) A__ : int = 0 while number: position += 1 number >>= 1 return position if __name__ == "__main__": import doctest doctest.testmod()
64
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A_ : Any = logging.get_logger(__name__) A_ : Union[str, Any] = { 'andreasmadsen/efficient_mlm_m0.40': ( 'https://huggingface.co/andreasmadsen/efficient_mlm_m0.40/resolve/main/config.json' ), } class _a (__magic_name__ ): '''simple docstring''' UpperCAmelCase__: Tuple = '''roberta-prelayernorm''' def __init__( self , A__=5_0265 , A__=768 , A__=12 , A__=12 , A__=3072 , A__="gelu" , A__=0.1 , A__=0.1 , A__=512 , A__=2 , A__=0.0_2 , A__=1e-12 , A__=1 , A__=0 , A__=2 , A__="absolute" , A__=True , A__=None , **A__ , ): super().__init__(pad_token_id=__lowerCAmelCase , bos_token_id=__lowerCAmelCase , eos_token_id=__lowerCAmelCase , **__lowerCAmelCase ) A__ : int = vocab_size A__ : Any = hidden_size A__ : int = num_hidden_layers A__ : Dict = num_attention_heads A__ : Optional[Any] = hidden_act A__ : List[str] = intermediate_size A__ : Tuple = hidden_dropout_prob A__ : List[str] = attention_probs_dropout_prob A__ : Union[str, Any] = max_position_embeddings A__ : Optional[int] = type_vocab_size A__ : Optional[Any] = initializer_range A__ : Optional[Any] = layer_norm_eps A__ : Optional[int] = position_embedding_type A__ : Any = use_cache A__ : int = classifier_dropout class _a (__magic_name__ ): '''simple docstring''' @property def __A ( self ): if self.task == "multiple-choice": A__ : List[str] = {0: """batch""", 1: """choice""", 2: """sequence"""} else: A__ : str = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
707
from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def UpperCamelCase (lowercase_: np.ndarray , lowercase_: np.ndarray , lowercase_: np.ndarray , lowercase_: int , lowercase_: int ) -> np.ndarray: A__ : Any = cva.getAffineTransform(lowercase_ , lowercase_ ) return cva.warpAffine(lowercase_ , lowercase_ , (rows, cols) ) if __name__ == "__main__": # read original image A_ : List[Any] = cva.imread( str(Path(__file__).resolve().parent.parent / 'image_data' / 'lena.jpg') ) # turn image in gray scale value A_ : List[Any] = cva.cvtColor(image, cva.COLOR_BGR2GRAY) # get image shape A_ , A_ : Optional[Any] = gray_img.shape # set different points to rotate image A_ : str = np.array([[50, 50], [200, 50], [50, 200]], np.floataa) A_ : Dict = np.array([[10, 100], [200, 50], [100, 250]], np.floataa) A_ : Optional[int] = np.array([[50, 50], [150, 50], [120, 200]], np.floataa) A_ : Optional[int] = np.array([[10, 100], [80, 50], [180, 250]], np.floataa) # add all rotated images in a list A_ : Dict = [ 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_ : Union[str, Any] = plt.figure(1) A_ : Union[str, Any] = ['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()
64
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available A_ = { "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST", "ErnieForCausalLM", "ErnieForMaskedLM", "ErnieForMultipleChoice", "ErnieForNextSentencePrediction", "ErnieForPreTraining", "ErnieForQuestionAnswering", "ErnieForSequenceClassification", "ErnieForTokenClassification", "ErnieModel", "ErniePreTrainedModel", ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys A_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
708
import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class _a (unittest.TestCase ): '''simple docstring''' def __A ( self , A__ ): for model_result in results.values(): for batch_size, sequence_length in zip(model_result["""bs"""] , model_result["""ss"""] ): A__ : str = model_result["""result"""][batch_size][sequence_length] self.assertIsNotNone(A__ ) def __A ( self ): A__ : Dict = """sshleifer/tiny-gpt2""" A__ : Tuple = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : int = PyTorchBenchmark(A__ ) A__ : List[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ): A__ : Dict = """sgugger/tiny-distilbert-classification""" A__ : Dict = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , only_pretrain_model=A__ , ) A__ : str = PyTorchBenchmark(A__ ) A__ : List[str] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ): A__ : Any = """sshleifer/tiny-gpt2""" A__ : List[Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , torchscript=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : Tuple = PyTorchBenchmark(A__ ) A__ : str = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == """cpu""" , """Cant do half precision""" ) def __A ( self ): A__ : Optional[Any] = """sshleifer/tiny-gpt2""" A__ : Optional[Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , fpaa=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : str = PyTorchBenchmark(A__ ) A__ : Any = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ): A__ : Optional[Any] = """sshleifer/tiny-gpt2""" A__ : Tuple = AutoConfig.from_pretrained(A__ ) # set architectures equal to `None` A__ : List[Any] = None A__ : str = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : List[str] = PyTorchBenchmark(A__ , configs=[config] ) A__ : Any = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ): A__ : Optional[int] = """sshleifer/tiny-gpt2""" A__ : Optional[int] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : Any = PyTorchBenchmark(A__ ) A__ : Dict = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == """cpu""" , """Can't do half precision""" ) def __A ( self ): A__ : Optional[int] = """sshleifer/tiny-gpt2""" A__ : List[str] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , fpaa=A__ , multi_process=A__ , ) A__ : Dict = PyTorchBenchmark(A__ ) A__ : Optional[int] = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __A ( self ): A__ : int = """sshleifer/tiny-gpt2""" A__ : Optional[int] = AutoConfig.from_pretrained(A__ ) A__ : str = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : int = PyTorchBenchmark(A__ , configs=[config] ) A__ : Tuple = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ): A__ : List[str] = """sshleifer/tinier_bart""" A__ : List[str] = AutoConfig.from_pretrained(A__ ) A__ : List[str] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : Union[str, Any] = PyTorchBenchmark(A__ , configs=[config] ) A__ : str = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ): A__ : Optional[int] = """sshleifer/tiny-gpt2""" A__ : Union[str, Any] = AutoConfig.from_pretrained(A__ ) A__ : Tuple = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : int = PyTorchBenchmark(A__ , configs=[config] ) A__ : Tuple = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __A ( self ): A__ : Dict = """sshleifer/tinier_bart""" A__ : int = AutoConfig.from_pretrained(A__ ) A__ : Union[str, Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : List[Any] = PyTorchBenchmark(A__ , configs=[config] ) A__ : Optional[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __A ( self ): A__ : int = """sshleifer/tiny-gpt2""" with tempfile.TemporaryDirectory() as tmp_dir: A__ : Dict = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , save_to_csv=A__ , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(A__ , """inf_time.csv""" ) , train_memory_csv_file=os.path.join(A__ , """train_mem.csv""" ) , inference_memory_csv_file=os.path.join(A__ , """inf_mem.csv""" ) , train_time_csv_file=os.path.join(A__ , """train_time.csv""" ) , env_info_csv_file=os.path.join(A__ , """env.csv""" ) , multi_process=A__ , ) A__ : Optional[Any] = PyTorchBenchmark(A__ ) benchmark.run() self.assertTrue(Path(os.path.join(A__ , """inf_time.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(A__ , """train_time.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(A__ , """inf_mem.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(A__ , """train_mem.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(A__ , """env.csv""" ) ).exists() ) def __A ( self ): A__ : Optional[int] = """sshleifer/tiny-gpt2""" def _check_summary_is_not_empty(A__ ): self.assertTrue(hasattr(A__ , """sequential""" ) ) self.assertTrue(hasattr(A__ , """cumulative""" ) ) self.assertTrue(hasattr(A__ , """current""" ) ) self.assertTrue(hasattr(A__ , """total""" ) ) with tempfile.TemporaryDirectory() as tmp_dir: A__ : Dict = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(A__ , """log.txt""" ) , log_print=A__ , trace_memory_line_by_line=A__ , multi_process=A__ , ) A__ : Dict = PyTorchBenchmark(A__ ) A__ : str = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(A__ , """log.txt""" ) ).exists() )
64
0
import random def UpperCamelCase (lowercase_: list , lowercase_: Optional[Any] ) -> tuple: A__ : List[Any] = [], [], [] for element in data: if element < pivot: less.append(_lowercase ) elif element > pivot: greater.append(_lowercase ) else: equal.append(_lowercase ) return less, equal, greater def UpperCamelCase (lowercase_: list , lowercase_: int ) -> Dict: if index >= len(_lowercase ) or index < 0: return None A__ : Optional[int] = items[random.randint(0 , len(_lowercase ) - 1 )] A__ : Dict = 0 A__ : str = _partition(_lowercase , _lowercase ) A__ : List[Any] = len(_lowercase ) A__ : int = len(_lowercase ) # index is the pivot if m <= index < m + count: return pivot # must be in smaller elif m > index: return quick_select(_lowercase , _lowercase ) # must be in larger else: return quick_select(_lowercase , index - (m + count) )
709
# tests directory-specific settings - this file is run automatically # by pytest before any tests are run import doctest import sys import warnings from os.path import abspath, dirname, join import _pytest from transformers.testing_utils import HfDoctestModule, HfDocTestParser # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. A_ : Optional[int] = abspath(join(dirname(__file__), 'src')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='ignore', category=FutureWarning) def UpperCamelCase (lowercase_: List[str] ) -> Any: config.addinivalue_line( """markers""" , """is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested""" ) config.addinivalue_line( """markers""" , """is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested""" ) config.addinivalue_line("""markers""" , """is_pipeline_test: mark test to run only when pipelines are tested""" ) config.addinivalue_line("""markers""" , """is_staging_test: mark test to run only in the staging environment""" ) config.addinivalue_line("""markers""" , """accelerate_tests: mark test that require accelerate""" ) config.addinivalue_line("""markers""" , """tool_tests: mark the tool tests that are run on their specific schedule""" ) def UpperCamelCase (lowercase_: Optional[int] ) -> Optional[Any]: from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(lowercase_ ) def UpperCamelCase (lowercase_: List[str] ) -> Optional[Any]: from transformers.testing_utils import pytest_terminal_summary_main A__ : List[Any] = terminalreporter.config.getoption("""--make-reports""" ) if make_reports: pytest_terminal_summary_main(lowercase_ , id=lowercase_ ) def UpperCamelCase (lowercase_: Union[str, Any] , lowercase_: int ) -> List[str]: # If no tests are collected, pytest exists with code 5, which makes the CI fail. if exitstatus == 5: A__ : Tuple = 0 # Doctest custom flag to ignore output. A_ : Tuple = doctest.register_optionflag('IGNORE_RESULT') A_ : Dict = doctest.OutputChecker class _a (__magic_name__ ): '''simple docstring''' def __A ( self , A__ , A__ , A__ ): if IGNORE_RESULT & optionflags: return True return OutputChecker.check_output(self , A__ , A__ , A__ ) A_ : str = CustomOutputChecker A_ : Dict = HfDoctestModule A_ : Optional[int] = HfDocTestParser
64
0
import torch from torch import nn from transformers import CLIPPreTrainedModel, CLIPVisionModel from ...models.attention import BasicTransformerBlock from ...utils import logging A_ : List[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name class _a (UpperCAmelCase__ ): '''simple docstring''' def __init__( self , A__ , A__=768 ): super().__init__(__lowerCAmelCase ) A__ : Optional[Any] = proj_size A__ : List[Any] = CLIPVisionModel(__lowerCAmelCase ) A__ : List[str] = PaintByExampleMapper(__lowerCAmelCase ) A__ : Union[str, Any] = nn.LayerNorm(config.hidden_size ) A__ : List[Any] = nn.Linear(config.hidden_size , self.proj_size ) # uncondition for scaling A__ : Tuple = nn.Parameter(torch.randn((1, 1, self.proj_size) ) ) def __A ( self , A__ , A__=False ): A__ : Union[str, Any] = self.model(pixel_values=__lowerCAmelCase ) A__ : Tuple = clip_output.pooler_output A__ : Any = self.mapper(latent_states[:, None] ) A__ : Any = self.final_layer_norm(__lowerCAmelCase ) A__ : Tuple = self.proj_out(__lowerCAmelCase ) if return_uncond_vector: return latent_states, self.uncond_vector return latent_states class _a (nn.Module ): '''simple docstring''' def __init__( self , A__ ): super().__init__() A__ : Optional[Any] = (config.num_hidden_layers + 1) // 5 A__ : Optional[Any] = config.hidden_size A__ : Any = 1 A__ : Optional[Any] = nn.ModuleList( [ BasicTransformerBlock(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , activation_fn="""gelu""" , attention_bias=__lowerCAmelCase ) for _ in range(__lowerCAmelCase ) ] ) def __A ( self , A__ ): for block in self.blocks: A__ : Union[str, Any] = block(__lowerCAmelCase ) return hidden_states
710
from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, 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, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class _a : '''simple docstring''' UpperCAmelCase__: List[Any] = PegasusConfig UpperCAmelCase__: Optional[int] = {} UpperCAmelCase__: List[str] = '''gelu''' def __init__( self , A__ , A__=13 , A__=7 , A__=True , A__=False , A__=99 , A__=32 , A__=2 , A__=4 , A__=37 , A__=0.1 , A__=0.1 , A__=40 , A__=2 , A__=1 , A__=0 , ): A__ : Dict = parent A__ : Dict = batch_size A__ : Any = seq_length A__ : Optional[Any] = is_training A__ : int = use_labels A__ : Any = vocab_size A__ : Union[str, Any] = hidden_size A__ : Tuple = num_hidden_layers A__ : Tuple = num_attention_heads A__ : List[Any] = intermediate_size A__ : Union[str, Any] = hidden_dropout_prob A__ : Optional[Any] = attention_probs_dropout_prob A__ : List[Any] = max_position_embeddings A__ : Any = eos_token_id A__ : List[Any] = pad_token_id A__ : List[Any] = bos_token_id def __A ( self ): A__ : str = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) A__ : Dict = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) A__ : List[Any] = tf.concat([input_ids, eos_tensor] , axis=1 ) A__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ : Tuple = 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 , ) A__ : str = prepare_pegasus_inputs_dict(A__ , A__ , A__ ) return config, inputs_dict def __A ( self , A__ , A__ ): A__ : int = TFPegasusModel(config=A__ ).get_decoder() A__ : List[Any] = inputs_dict["""input_ids"""] A__ : Any = input_ids[:1, :] A__ : Optional[Any] = inputs_dict["""attention_mask"""][:1, :] A__ : Optional[int] = inputs_dict["""head_mask"""] A__ : Any = 1 # first forward pass A__ : Tuple = model(A__ , attention_mask=A__ , head_mask=A__ , use_cache=A__ ) A__ , A__ : Dict = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids A__ : Tuple = ids_tensor((self.batch_size, 3) , config.vocab_size ) A__ : Optional[Any] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and A__ : List[Any] = tf.concat([input_ids, next_tokens] , axis=-1 ) A__ : Tuple = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) A__ : Optional[Any] = model(A__ , attention_mask=A__ )[0] A__ : Any = model(A__ , attention_mask=A__ , past_key_values=A__ )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice A__ : int = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) A__ : Any = output_from_no_past[:, -3:, random_slice_idx] A__ : Tuple = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(A__ , A__ , rtol=1e-3 ) def UpperCamelCase (lowercase_: Union[str, Any] , lowercase_: Dict , lowercase_: List[Any] , lowercase_: Dict=None , lowercase_: int=None , lowercase_: List[Any]=None , lowercase_: List[Any]=None , lowercase_: str=None , ) -> int: if attention_mask is None: A__ : List[str] = tf.cast(tf.math.not_equal(lowercase_ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: A__ : Dict = 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: A__ : Any = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: A__ : Tuple = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: A__ : List[str] = 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 (__magic_name__ , __magic_name__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: List[Any] = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () UpperCAmelCase__: Tuple = (TFPegasusForConditionalGeneration,) if is_tf_available() else () UpperCAmelCase__: Tuple = ( { '''conversational''': TFPegasusForConditionalGeneration, '''feature-extraction''': TFPegasusModel, '''summarization''': TFPegasusForConditionalGeneration, '''text2text-generation''': TFPegasusForConditionalGeneration, '''translation''': TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) UpperCAmelCase__: int = True UpperCAmelCase__: Union[str, Any] = False UpperCAmelCase__: List[str] = False def __A ( self ): A__ : Optional[Any] = TFPegasusModelTester(self ) A__ : Tuple = ConfigTester(self , config_class=A__ ) def __A ( self ): self.config_tester.run_common_tests() def __A ( self ): A__ : int = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*A__ ) @require_sentencepiece @require_tokenizers @require_tf class _a (unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: Optional[int] = [ ''' 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!" ''', ] UpperCAmelCase__: Any = [ '''California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to''' ''' reduce the risk of wildfires.''', '''N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.''', ] # differs slightly from pytorch, likely due to numerical differences in linear layers UpperCAmelCase__: List[str] = '''google/pegasus-xsum''' @cached_property def __A ( self ): return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def __A ( self ): A__ : int = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def __A ( self , **A__ ): A__ : str = self.translate_src_text(**A__ ) assert self.expected_text == generated_words def __A ( self , **A__ ): A__ : List[str] = self.tokenizer(self.src_text , **A__ , padding=A__ , return_tensors="""tf""" ) A__ : Optional[int] = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=A__ , ) A__ : Dict = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=A__ ) return generated_words @slow def __A ( self ): self._assert_generated_batch_equal_expected()
64
0
from bisect import bisect from itertools import accumulate def UpperCamelCase (lowercase_: List[str] , lowercase_: List[Any] , lowercase_: Union[str, Any] , lowercase_: Dict ) -> Dict: A__ : Dict = sorted(zip(_snake_case , _snake_case ) , key=lambda lowercase_ : x[0] / x[1] , reverse=_snake_case ) A__ , A__ : Dict = [i[0] for i in r], [i[1] for i in r] A__ : int = list(accumulate(_snake_case ) ) A__ : Optional[int] = bisect(_snake_case , _snake_case ) return ( 0 if k == 0 else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k] ) ) if __name__ == "__main__": import doctest doctest.testmod()
711
class _a : '''simple docstring''' def __init__( self ): A__ : str = """""" A__ : Any = """""" A__ : List[Any] = [] def __A ( self , A__ , A__ ): if m == -1: return n + 1 elif n == -1: return m + 1 elif self.dp[m][n] > -1: return self.dp[m][n] else: if self.worda[m] == self.worda[n]: A__ : Optional[Any] = self.__min_dist_top_down_dp(m - 1 , n - 1 ) else: A__ : Union[str, Any] = self.__min_dist_top_down_dp(A__ , n - 1 ) A__ : Union[str, Any] = self.__min_dist_top_down_dp(m - 1 , A__ ) A__ : Union[str, Any] = self.__min_dist_top_down_dp(m - 1 , n - 1 ) A__ : List[Any] = 1 + min(A__ , A__ , A__ ) return self.dp[m][n] def __A ( self , A__ , A__ ): A__ : Tuple = worda A__ : Dict = worda A__ : Optional[Any] = [[-1 for _ in range(len(A__ ) )] for _ in range(len(A__ ) )] return self.__min_dist_top_down_dp(len(A__ ) - 1 , len(A__ ) - 1 ) def __A ( self , A__ , A__ ): A__ : Optional[Any] = worda A__ : Dict = worda A__ : Union[str, Any] = len(A__ ) A__ : List[str] = len(A__ ) A__ : int = [[0 for _ in range(n + 1 )] for _ in range(m + 1 )] for i in range(m + 1 ): for j in range(n + 1 ): if i == 0: # first string is empty A__ : Tuple = j elif j == 0: # second string is empty A__ : Dict = i elif worda[i - 1] == worda[j - 1]: # last characters are equal A__ : str = self.dp[i - 1][j - 1] else: A__ : Union[str, Any] = self.dp[i][j - 1] A__ : str = self.dp[i - 1][j] A__ : Union[str, Any] = self.dp[i - 1][j - 1] A__ : Tuple = 1 + min(A__ , A__ , A__ ) return self.dp[m][n] if __name__ == "__main__": A_ : Union[str, Any] = EditDistance() print('****************** Testing Edit Distance DP Algorithm ******************') print() A_ : int = input('Enter the first string: ').strip() A_ : List[str] = input('Enter the second string: ').strip() print() print(f'''The minimum edit distance is: {solver.min_dist_top_down(Sa, Sa)}''') print(f'''The minimum edit distance is: {solver.min_dist_bottom_up(Sa, Sa)}''') print() print('*************** End of Testing Edit Distance DP Algorithm ***************')
64
0
from typing import Dict import numpy as np import torch from . import residue_constants as rc from .tensor_utils import tensor_tree_map, tree_map def UpperCamelCase (lowercase_: Optional[Any] ) -> int: A__ : Optional[Any] = [] A__ : int = [] A__ : str = [] for rt in rc.restypes: A__ : str = rc.restype_name_to_atomaa_names[rc.restype_atoa[rt]] restype_atomaa_to_atomaa_list.append([(rc.atom_order[name] if name else 0) for name in atom_names] ) A__ : List[Any] = {name: i for i, name in enumerate(_lowercase )} restype_atomaa_to_atomaa_list.append( [(atom_name_to_idxaa[name] if name in atom_name_to_idxaa else 0) for name in rc.atom_types] ) restype_atomaa_mask_list.append([(1.0 if name else 0.0) for name in atom_names] ) # Add dummy mapping for restype 'UNK' restype_atomaa_to_atomaa_list.append([0] * 14 ) restype_atomaa_to_atomaa_list.append([0] * 37 ) restype_atomaa_mask_list.append([0.0] * 14 ) A__ : Dict = torch.tensor( _lowercase , dtype=torch.intaa , device=protein["""aatype"""].device , ) A__ : int = torch.tensor( _lowercase , dtype=torch.intaa , device=protein["""aatype"""].device , ) A__ : Optional[Any] = torch.tensor( _lowercase , dtype=torch.floataa , device=protein["""aatype"""].device , ) A__ : Optional[int] = protein['''aatype'''].to(torch.long ) # create the mapping for (residx, atom14) --> atom37, i.e. an array # with shape (num_res, 14) containing the atom37 indices for this protein A__ : Optional[int] = restype_atomaa_to_atomaa[protein_aatype] A__ : Optional[int] = restype_atomaa_mask[protein_aatype] A__ : List[Any] = residx_atomaa_mask A__ : Optional[int] = residx_atomaa_to_atomaa.long() # create the gather indices for mapping back A__ : List[str] = restype_atomaa_to_atomaa[protein_aatype] A__ : Union[str, Any] = residx_atomaa_to_atomaa.long() # create the corresponding mask A__ : Optional[Any] = torch.zeros([21, 37] , dtype=torch.floataa , device=protein["""aatype"""].device ) for restype, restype_letter in enumerate(rc.restypes ): A__ : str = rc.restype_atoa[restype_letter] A__ : Optional[Any] = rc.residue_atoms[restype_name] for atom_name in atom_names: A__ : Union[str, Any] = rc.atom_order[atom_name] A__ : Optional[int] = 1 A__ : Optional[int] = restype_atomaa_mask[protein_aatype] A__ : Union[str, Any] = residx_atomaa_mask return protein def UpperCamelCase (lowercase_: Optional[Any] ) -> str: A__ : Tuple = tree_map(lambda lowercase_ : torch.tensor(_lowercase , device=batch["""aatype"""].device ) , _lowercase , np.ndarray ) A__ : Optional[int] = tensor_tree_map(lambda lowercase_ : np.array(_lowercase ) , make_atomaa_masks(_lowercase ) ) return out
712
def UpperCamelCase (lowercase_: int , lowercase_: int ) -> int: while second != 0: A__ : int = first & second first ^= second A__ : int = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() A_ : Optional[Any] = int(input('Enter the first number: ').strip()) A_ : List[str] = int(input('Enter the second number: ').strip()) print(f'''{add(first, second) = }''')
64
0
import math import os import re import sys import unittest from pathlib import Path from typing import Tuple from unittest.mock import patch from parameterized import parameterized from transformers.testing_utils import ( CaptureStderr, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, get_torch_dist_unique_port, require_apex, require_bitsandbytes, require_fairscale, require_torch, require_torch_gpu, require_torch_multi_gpu, require_torch_non_multi_gpu, slow, ) from transformers.trainer_callback import TrainerState from transformers.trainer_utils import set_seed A_ : Union[str, Any] = os.path.abspath(os.path.dirname(__file__)) with ExtendSysPath(f'''{bindir}/../../examples/pytorch/translation'''): from run_translation import main # noqa set_seed(42) A_ : List[Any] = 'sshleifer/student_marian_en_ro_6_1' A_ : str = 'sshleifer/tiny-mbart' @require_torch class _a (__magic_name__ ): '''simple docstring''' def __A ( self , A__=False , A__=None , A__=True , A__=True , A__=True , A__=True , ): A__ : Optional[int] = self.run_trainer( eval_steps=1 , max_len=12 , model_name=_SCREAMING_SNAKE_CASE , num_train_epochs=1 , distributed=_SCREAMING_SNAKE_CASE , extra_args_str=_SCREAMING_SNAKE_CASE , predict_with_generate=_SCREAMING_SNAKE_CASE , do_train=_SCREAMING_SNAKE_CASE , do_eval=_SCREAMING_SNAKE_CASE , do_predict=_SCREAMING_SNAKE_CASE , ) A__ : str = TrainerState.load_from_json(os.path.join(_SCREAMING_SNAKE_CASE , """trainer_state.json""" ) ).log_history if not do_eval: return A__ : Optional[int] = [log for log in logs if """eval_loss""" in log.keys()] A__ : Tuple = eval_metrics[0] if predict_with_generate: assert "eval_bleu" in first_step_stats A__ : Dict = eval_metrics[-1] assert isinstance(last_step_stats["""eval_bleu"""] , _SCREAMING_SNAKE_CASE ) assert not math.isnan(float(last_step_stats["""eval_loss"""] ) ), "eval_loss must not be `nan`" @require_torch_non_multi_gpu def __A ( self ): self.run_seqaseq_quick() @require_torch_multi_gpu def __A ( self ): self.run_seqaseq_quick(distributed=_SCREAMING_SNAKE_CASE ) @require_torch_multi_gpu def __A ( self ): self.run_seqaseq_quick(distributed=_SCREAMING_SNAKE_CASE ) @unittest.skip("""Requires an update of the env running those tests""" ) @require_torch_multi_gpu @require_fairscale def __A ( self ): self.run_seqaseq_quick(distributed=_SCREAMING_SNAKE_CASE , extra_args_str="""--sharded_ddp simple""" ) @unittest.skip("""Requires an update of the env running those tests""" ) @require_torch_multi_gpu @require_fairscale def __A ( self ): self.run_seqaseq_quick(distributed=_SCREAMING_SNAKE_CASE , extra_args_str="""--sharded_ddp simple --fp16""" ) @unittest.skip("""Requires an update of the env running those tests""" ) @require_torch_multi_gpu @require_fairscale def __A ( self ): self.run_seqaseq_quick(distributed=_SCREAMING_SNAKE_CASE , extra_args_str="""--sharded_ddp zero_dp_2""" , predict_with_generate=_SCREAMING_SNAKE_CASE ) @unittest.skip("""Requires an update of the env running those tests""" ) @require_torch_multi_gpu @require_fairscale def __A ( self ): self.run_seqaseq_quick( distributed=_SCREAMING_SNAKE_CASE , extra_args_str="""--sharded_ddp zero_dp_2 --fp16""" , predict_with_generate=_SCREAMING_SNAKE_CASE ) @require_apex @require_torch_gpu def __A ( self ): self.run_seqaseq_quick(distributed=_SCREAMING_SNAKE_CASE , extra_args_str="""--fp16 --fp16_backend=apex""" ) # test 2nd time - was getting eval_loss': nan' # to reproduce the problem set distributed=False self.run_seqaseq_quick(distributed=_SCREAMING_SNAKE_CASE , extra_args_str="""--fp16 --fp16_backend=apex""" ) @parameterized.expand(["""base""", """low""", """high""", """mixed"""] ) @require_torch_multi_gpu def __A ( self , A__ ): A__ : str = { # test with the default log_level - should be info and thus log info once """base""": {"""extra_args_str""": """""", """n_matches""": 1}, # test with low log_level and log_level_replica - should be noisy on all processes # now the info string should appear twice on 2 processes """low""": {"""extra_args_str""": """--log_level debug --log_level_replica debug""", """n_matches""": 2}, # test with high log_level and low log_level_replica # now the info string should appear once only on the replica """high""": {"""extra_args_str""": """--log_level error --log_level_replica debug""", """n_matches""": 1}, # test with high log_level and log_level_replica - should be quiet on all processes """mixed""": {"""extra_args_str""": """--log_level error --log_level_replica error""", """n_matches""": 0}, } A__ : int = experiments[experiment_id] A__ : int = {"""distributed""": True, """predict_with_generate""": False, """do_eval""": False, """do_predict""": False} A__ : List[str] = """Running training""" with CaptureStderr() as cl: self.run_seqaseq_quick(**_SCREAMING_SNAKE_CASE , extra_args_str=data["""extra_args_str"""] ) A__ : List[Any] = len(re.findall(_SCREAMING_SNAKE_CASE , cl.err ) ) self.assertEqual(_SCREAMING_SNAKE_CASE , data["""n_matches"""] ) @slow def __A ( self ): A__ : int = self.run_trainer( eval_steps=2 , max_len=128 , model_name=_SCREAMING_SNAKE_CASE , learning_rate=3e-4 , num_train_epochs=10 , distributed=_SCREAMING_SNAKE_CASE , ) # Check metrics A__ : Tuple = TrainerState.load_from_json(os.path.join(_SCREAMING_SNAKE_CASE , """trainer_state.json""" ) ).log_history A__ : Dict = [log for log in logs if """eval_loss""" in log.keys()] A__ : Tuple = eval_metrics[0] A__ : Union[str, Any] = eval_metrics[-1] assert first_step_stats["eval_loss"] > last_step_stats["eval_loss"], "model learned nothing" assert isinstance(last_step_stats["""eval_bleu"""] , _SCREAMING_SNAKE_CASE ) # test if do_predict saves generations and metrics A__ : int = os.listdir(_SCREAMING_SNAKE_CASE ) A__ : List[str] = {os.path.basename(_SCREAMING_SNAKE_CASE ) for p in contents} assert "generated_predictions.txt" in contents assert "predict_results.json" in contents @slow @require_bitsandbytes def __A ( self ): from transformers.training_args import OptimizerNames def train_and_return_metrics(A__ ) -> Tuple[int, float]: A__ : int = """--skip_memory_metrics 0""" A__ : Tuple = self.run_trainer( max_len=128 , model_name=_SCREAMING_SNAKE_CASE , learning_rate=3e-4 , num_train_epochs=1 , optim=_SCREAMING_SNAKE_CASE , distributed=_SCREAMING_SNAKE_CASE , extra_args_str=_SCREAMING_SNAKE_CASE , do_eval=_SCREAMING_SNAKE_CASE , do_predict=_SCREAMING_SNAKE_CASE , n_gpus_to_use=1 , ) # Check metrics A__ : List[Any] = TrainerState.load_from_json(Path(_SCREAMING_SNAKE_CASE , """trainer_state.json""" ) ).log_history A__ : Union[str, Any] = int(logs[0]["""train_mem_gpu_peaked_delta"""] / 2**20 ) A__ : List[Any] = int(logs[0]["""train_mem_gpu_alloc_delta"""] / 2**20 ) A__ : int = logs[0]["""train_loss"""] return gpu_peak_mem_mb, gpu_alloc_mem_mb, loss A__ , A__ , A__ : Tuple = train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value ) A__ , A__ , A__ : Tuple = train_and_return_metrics(OptimizerNames.ADAMW_BNB.value ) A__ : Any = gpu_alloc_mem_orig - gpu_alloc_mem_bnb A__ : Union[str, Any] = gpu_peak_mem_orig + gpu_alloc_mem_orig A__ : Dict = gpu_peak_mem_bnb + gpu_alloc_mem_bnb A__ : int = gpu_total_mem_orig - gpu_total_mem_bnb # sshleifer/student_marian_en_ro_6_1 has 54M parameter, 29M of which is `nn.Embedding` which # doesn't get quantized and remains in fp32. Therefore we only have 25M parameters quantized # in 2 bytes and the diff in optim memory usage is derived as so: # # - normal 25*8=~200MB (8 bytes per param) # - bnb 25*2= ~50MB (2 bytes per param) # # Thus we should expect ~150MB total memory saved. # # Peak memory should be the same - the total should be different by about that same margin # # After leaving a small margin to accommodate for differences between gpus let's check # that we have at least 120MB in savings A__ : Dict = 120 # uncomment the following if this test starts failing - requires py38 for a new print feature # gpu_peak_mem_diff = gpu_peak_mem_orig - gpu_peak_mem_bnb # print(f"{gpu_alloc_mem_orig=}MB {gpu_peak_mem_orig=}MB {gpu_alloc_mem_orig+gpu_peak_mem_orig=}MB") # print(f" {gpu_alloc_mem_bnb=}MB {gpu_peak_mem_bnb=}MB {gpu_alloc_mem_bnb+gpu_peak_mem_bnb=}MB") # print(f"{gpu_alloc_mem_diff=}MB") # print(f"{gpu_peak_mem_diff=}MB") # print(f"{gpu_total_mem_orig=}MB, {gpu_total_mem_bnb=}MB") # print(f"{gpu_total_mem_diff=}MB, {gpu_total_mem_diff=}MB") self.assertGreater( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , """should use ~150MB less alloc gpu memory with BNB, compared to without it for this model but got""" F""" a difference of {gpu_alloc_mem_diff}MB, with gpu_alloc_mem_orig={gpu_alloc_mem_orig}MB and""" F""" gpu_alloc_mem_bnb={gpu_alloc_mem_bnb}MB""" , ) self.assertGreater( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , """should use ~150MB less total gpu memory with BNB, compared to without it for this model but got""" F""" a difference of {gpu_total_mem_diff}MB, with gpu_total_mem_orig={gpu_total_mem_orig}MB and""" F""" gpu_total_mem_bnb={gpu_total_mem_bnb}MB""" , ) self.assertEqual( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , F"""loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}""" ) def __A ( self , A__ , A__ , A__ , A__ = 3e-3 , A__ = "adafactor" , A__ = False , A__ = None , A__ = 0 , A__ = True , A__ = True , A__ = True , A__ = True , A__ = None , ): A__ : int = self.test_file_dir / """../fixtures/tests_samples/wmt_en_ro""" A__ : List[str] = self.get_auto_remove_tmp_dir() A__ : Tuple = F"""\n --model_name_or_path {model_name}\n --train_file {data_dir}/train.json\n --validation_file {data_dir}/val.json\n --test_file {data_dir}/test.json\n --output_dir {output_dir}\n --overwrite_output_dir\n --max_train_samples 8\n --max_source_length {max_len}\n --max_target_length {max_len}\n --do_train\n --num_train_epochs {str(_SCREAMING_SNAKE_CASE )}\n --per_device_train_batch_size 4\n --learning_rate {learning_rate}\n --warmup_steps 8\n --logging_steps 0\n --logging_strategy no\n --save_steps {str(_SCREAMING_SNAKE_CASE )}\n --group_by_length\n --label_smoothing_factor 0.1\n --target_lang ro_RO\n --source_lang en_XX\n """.split() A__ : List[str] = F"""\n --do_eval\n --per_device_eval_batch_size 4\n --max_eval_samples 8\n --val_max_target_length {max_len}\n --evaluation_strategy steps\n --eval_steps {str(_SCREAMING_SNAKE_CASE )}\n """.split() A__ : Optional[Any] = """ --do_predict """.split() A__ : List[str] = [] if do_train: args += args_train if do_eval: args += args_eval if do_predict: args += args_predict if predict_with_generate: args += "--predict_with_generate".split() if do_train: if optim == "adafactor": args += "--adafactor".split() else: args += F"""--optim {optim}""".split() if extra_args_str is not None: args += extra_args_str.split() if distributed: if n_gpus_to_use is None: A__ : Optional[Any] = get_gpu_count() A__ : List[Any] = get_torch_dist_unique_port() A__ : str = F"""\n -m torch.distributed.run\n --nproc_per_node={n_gpus_to_use}\n --master_port={master_port}\n {self.examples_dir_str}/pytorch/translation/run_translation.py\n """.split() A__ : Union[str, Any] = [sys.executable] + distributed_args + args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(_SCREAMING_SNAKE_CASE , env=self.get_env() ) else: A__ : Tuple = ["""run_translation.py"""] + args with patch.object(_SCREAMING_SNAKE_CASE , """argv""" , _SCREAMING_SNAKE_CASE ): main() return output_dir
713
from __future__ import annotations from collections.abc import Callable A_ : List[Any] = list[list[float | int]] def UpperCamelCase (lowercase_: Matrix , lowercase_: Matrix ) -> Matrix: A__ : int = len(lowercase_ ) A__ : Matrix = [[0 for _ in range(size + 1 )] for _ in range(lowercase_ )] A__ : int A__ : int A__ : int A__ : int A__ : int A__ : float for row in range(lowercase_ ): for col in range(lowercase_ ): A__ : List[str] = matrix[row][col] A__ : int = vector[row][0] A__ : Optional[int] = 0 A__ : str = 0 while row < size and col < size: # pivoting A__ : int = max((abs(augmented[rowa][col] ), rowa) for rowa in range(lowercase_ , lowercase_ ) )[ 1 ] if augmented[pivot_row][col] == 0: col += 1 continue else: A__ , A__ : Union[str, Any] = augmented[pivot_row], augmented[row] for rowa in range(row + 1 , lowercase_ ): A__ : List[Any] = augmented[rowa][col] / augmented[row][col] A__ : Dict = 0 for cola in range(col + 1 , size + 1 ): augmented[rowa][cola] -= augmented[row][cola] * ratio row += 1 col += 1 # back substitution for col in range(1 , lowercase_ ): for row in range(lowercase_ ): A__ : List[str] = augmented[row][col] / augmented[col][col] for cola in range(lowercase_ , size + 1 ): augmented[row][cola] -= augmented[col][cola] * ratio # round to get rid of numbers like 2.000000000000004 return [ [round(augmented[row][size] / augmented[row][row] , 10 )] for row in range(lowercase_ ) ] def UpperCamelCase (lowercase_: list[int] ) -> Callable[[int], int]: A__ : int = len(lowercase_ ) A__ : Matrix = [[0 for _ in range(lowercase_ )] for _ in range(lowercase_ )] A__ : Matrix = [[0] for _ in range(lowercase_ )] A__ : Matrix A__ : int A__ : int A__ : int for x_val, y_val in enumerate(lowercase_ ): for col in range(lowercase_ ): A__ : Dict = (x_val + 1) ** (size - col - 1) A__ : Any = y_val A__ : Union[str, Any] = solve(lowercase_ , lowercase_ ) def interpolated_func(lowercase_: int ) -> int: return sum( round(coeffs[x_val][0] ) * (var ** (size - x_val - 1)) for x_val in range(lowercase_ ) ) return interpolated_func def UpperCamelCase (lowercase_: int ) -> int: return ( 1 - variable + variable**2 - variable**3 + variable**4 - variable**5 + variable**6 - variable**7 + variable**8 - variable**9 + variable**10 ) def UpperCamelCase (lowercase_: Callable[[int], int] = question_function , lowercase_: int = 10 ) -> int: A__ : list[int] = [func(lowercase_ ) for x_val in range(1 , order + 1 )] A__ : list[Callable[[int], int]] = [ interpolate(data_points[:max_coeff] ) for max_coeff in range(1 , order + 1 ) ] A__ : int = 0 A__ : Callable[[int], int] A__ : int for poly in polynomials: A__ : List[str] = 1 while func(lowercase_ ) == poly(lowercase_ ): x_val += 1 ret += poly(lowercase_ ) return ret if __name__ == "__main__": print(f'''{solution() = }''')
64
0
import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging A_ : Optional[int] = logging.get_logger(__name__) A_ : Any = '▁' A_ : Dict = { 'vocab_file': 'vocab.json', 'spm_file': 'sentencepiece.bpe.model', } A_ : Optional[int] = { 'vocab_file': { 'facebook/s2t-small-librispeech-asr': ( 'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/vocab.json' ), }, 'spm_file': { 'facebook/s2t-small-librispeech-asr': ( 'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/sentencepiece.bpe.model' ) }, } A_ : str = { 'facebook/s2t-small-librispeech-asr': 1024, } A_ : Any = ['pt', 'fr', 'ru', 'nl', 'ro', 'it', 'es', 'de'] A_ : str = {'mustc': MUSTC_LANGS} class _a (UpperCAmelCase__ ): '''simple docstring''' UpperCAmelCase__: Optional[Any] = VOCAB_FILES_NAMES UpperCAmelCase__: Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__: Any = MAX_MODEL_INPUT_SIZES UpperCAmelCase__: Optional[int] = ['input_ids', 'attention_mask'] UpperCAmelCase__: List[int] = [] def __init__( self , A__ , A__ , A__="<s>" , A__="</s>" , A__="<pad>" , A__="<unk>" , A__=False , A__=False , A__=None , A__=None , A__ = None , **A__ , ): A__ : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A__ , eos_token=A__ , unk_token=A__ , pad_token=A__ , do_upper_case=A__ , do_lower_case=A__ , tgt_lang=A__ , lang_codes=A__ , sp_model_kwargs=self.sp_model_kwargs , **A__ , ) A__ : Optional[Any] = do_upper_case A__ : str = do_lower_case A__ : str = load_json(A__ ) A__ : Tuple = {v: k for k, v in self.encoder.items()} A__ : Optional[Any] = spm_file A__ : Optional[int] = load_spm(A__ , self.sp_model_kwargs ) if lang_codes is not None: A__ : Optional[Any] = lang_codes A__ : str = LANGUAGES[lang_codes] A__ : List[Any] = [F"""<lang:{lang}>""" for lang in self.langs] A__ : Any = {lang: self.sp_model.PieceToId(F"""<lang:{lang}>""" ) for lang in self.langs} A__ : Tuple = self.lang_tokens A__ : Any = tgt_lang if tgt_lang is not None else self.langs[0] self.set_tgt_lang_special_tokens(self._tgt_lang ) else: A__ : List[Any] = {} @property def __A ( self ): return len(self.encoder ) @property def __A ( self ): return self._tgt_lang @tgt_lang.setter def __A ( self , A__ ): A__ : Dict = new_tgt_lang self.set_tgt_lang_special_tokens(A__ ) def __A ( self , A__ ): A__ : int = self.lang_code_to_id[tgt_lang] A__ : Any = [lang_code_id] def __A ( self , A__ ): return self.sp_model.encode(A__ , out_type=A__ ) def __A ( self , A__ ): return self.encoder.get(A__ , self.encoder[self.unk_token] ) def __A ( self , A__ ): return self.decoder.get(A__ , self.unk_token ) def __A ( self , A__ ): A__ : str = [] A__ : int = """""" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: A__ : List[Any] = self.sp_model.decode(A__ ) out_string += (decoded.upper() if self.do_upper_case else decoded) + token + " " A__ : Optional[int] = [] else: current_sub_tokens.append(A__ ) A__ : int = self.sp_model.decode(A__ ) out_string += decoded.upper() if self.do_upper_case else decoded return out_string.strip() def __A ( self , A__ , A__=None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + [self.eos_token_id] def __A ( self , A__ , A__ = None , A__ = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A__ , token_ids_a=A__ , already_has_special_tokens=A__ ) A__ : List[Any] = [1] * len(self.prefix_tokens ) A__ : Union[str, Any] = [1] if token_ids_a is None: return prefix_ones + ([0] * len(A__ )) + suffix_ones return prefix_ones + ([0] * len(A__ )) + ([0] * len(A__ )) + suffix_ones def __A ( self ): A__ : List[Any] = self.encoder.copy() vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): A__ : List[str] = self.__dict__.copy() A__ : Optional[Any] = None return state def __setstate__( self , A__ ): A__ : Any = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): A__ : Any = {} A__ : Union[str, Any] = load_spm(self.spm_file , self.sp_model_kwargs ) def __A ( self , A__ , A__ = None ): A__ : List[str] = Path(A__ ) assert save_dir.is_dir(), F"""{save_directory} should be a directory""" A__ : Any = save_dir / ( (filename_prefix + """-""" if filename_prefix else """""") + self.vocab_files_names["""vocab_file"""] ) A__ : Tuple = save_dir / ( (filename_prefix + """-""" if filename_prefix else """""") + self.vocab_files_names["""spm_file"""] ) save_json(self.encoder , A__ ) if os.path.abspath(self.spm_file ) != os.path.abspath(A__ ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , A__ ) elif not os.path.isfile(self.spm_file ): with open(A__ , """wb""" ) as fi: A__ : Optional[int] = self.sp_model.serialized_model_proto() fi.write(A__ ) return (str(A__ ), str(A__ )) def UpperCamelCase (lowercase_: List[str] , lowercase_: List[str] ) -> str: A__ : Optional[Any] = sentencepiece.SentencePieceProcessor(**lowercase_ ) spm.Load(str(lowercase_ ) ) return spm def UpperCamelCase (lowercase_: Union[str, Any] ) -> Union[str, Any]: with open(lowercase_ , """r""" ) as f: return json.load(lowercase_ ) def UpperCamelCase (lowercase_: Optional[Any] , lowercase_: Dict ) -> List[str]: with open(lowercase_ , """w""" ) as f: json.dump(lowercase_ , lowercase_ , indent=2 )
714
from functools import lru_cache @lru_cache def UpperCamelCase (lowercase_: int ) -> int: 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()
64
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A_ : Tuple = { 'configuration_timesformer': ['TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TimesformerConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : str = [ 'TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TimesformerModel', 'TimesformerForVideoClassification', 'TimesformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_timesformer import TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimesformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timesformer import ( TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimesformerForVideoClassification, TimesformerModel, TimesformerPreTrainedModel, ) else: import sys A_ : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
715
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import datasets import datasets.config from .utils import require_beam class _a (datasets.BeamBasedBuilder ): '''simple docstring''' def __A ( self ): return datasets.DatasetInfo( features=datasets.Features({"""content""": datasets.Value("""string""" )} ) , supervised_keys=A__ , ) def __A ( self , A__ , A__ ): return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""examples""": get_test_dummy_examples()} )] def __A ( self , A__ , A__ ): import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(A__ ) class _a (datasets.BeamBasedBuilder ): '''simple docstring''' def __A ( self ): return datasets.DatasetInfo( features=datasets.Features({"""a""": datasets.Sequence({"""b""": datasets.Value("""string""" )} )} ) , supervised_keys=A__ , ) def __A ( self , A__ , A__ ): return [ datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""examples""": get_test_nested_examples()} ) ] def __A ( self , A__ , A__ ): import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(A__ ) def UpperCamelCase () -> Dict: return [(i, {"content": content}) for i, content in enumerate(["""foo""", """bar""", """foobar"""] )] def UpperCamelCase () -> Tuple: return [(i, {"a": {"b": [content]}}) for i, content in enumerate(["""foo""", """bar""", """foobar"""] )] class _a (__magic_name__ ): '''simple docstring''' @require_beam def __A ( self ): A__ : Dict = len(get_test_dummy_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: A__ : int = DummyBeamDataset(cache_dir=A__ , beam_runner="""DirectRunner""" ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(A__ , builder.name , """default""" , """0.0.0""" , F"""{builder.name}-train.arrow""" ) ) ) self.assertDictEqual(builder.info.features , datasets.Features({"""content""": datasets.Value("""string""" )} ) ) A__ : int = builder.as_dataset() self.assertEqual(dset["""train"""].num_rows , A__ ) self.assertEqual(dset["""train"""].info.splits["""train"""].num_examples , A__ ) self.assertDictEqual(dset["""train"""][0] , get_test_dummy_examples()[0][1] ) self.assertDictEqual( dset["""train"""][expected_num_examples - 1] , get_test_dummy_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(A__ , builder.name , """default""" , """0.0.0""" , """dataset_info.json""" ) ) ) del dset @require_beam def __A ( self ): import apache_beam as beam A__ : int = beam.io.parquetio.WriteToParquet A__ : List[str] = len(get_test_dummy_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: A__ : str = DummyBeamDataset(cache_dir=A__ , beam_runner="""DirectRunner""" ) with patch("""apache_beam.io.parquetio.WriteToParquet""" ) as write_parquet_mock: A__ : Optional[Any] = partial(A__ , num_shards=2 ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join( A__ , builder.name , """default""" , """0.0.0""" , F"""{builder.name}-train-00000-of-00002.arrow""" ) ) ) self.assertTrue( os.path.exists( os.path.join( A__ , builder.name , """default""" , """0.0.0""" , F"""{builder.name}-train-00000-of-00002.arrow""" ) ) ) self.assertDictEqual(builder.info.features , datasets.Features({"""content""": datasets.Value("""string""" )} ) ) A__ : Optional[int] = builder.as_dataset() self.assertEqual(dset["""train"""].num_rows , A__ ) self.assertEqual(dset["""train"""].info.splits["""train"""].num_examples , A__ ) # Order is not preserved when sharding, so we just check that all the elements are there self.assertListEqual(sorted(dset["""train"""]["""content"""] ) , sorted(["""foo""", """bar""", """foobar"""] ) ) self.assertTrue( os.path.exists(os.path.join(A__ , builder.name , """default""" , """0.0.0""" , """dataset_info.json""" ) ) ) del dset @require_beam def __A ( self ): with tempfile.TemporaryDirectory() as tmp_cache_dir: A__ : int = DummyBeamDataset(cache_dir=A__ ) self.assertRaises(datasets.builder.MissingBeamOptions , builder.download_and_prepare ) @require_beam def __A ( self ): A__ : List[Any] = len(get_test_nested_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: A__ : Optional[int] = NestedBeamDataset(cache_dir=A__ , beam_runner="""DirectRunner""" ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(A__ , builder.name , """default""" , """0.0.0""" , F"""{builder.name}-train.arrow""" ) ) ) self.assertDictEqual( builder.info.features , datasets.Features({"""a""": datasets.Sequence({"""b""": datasets.Value("""string""" )} )} ) ) A__ : Optional[int] = builder.as_dataset() self.assertEqual(dset["""train"""].num_rows , A__ ) self.assertEqual(dset["""train"""].info.splits["""train"""].num_examples , A__ ) self.assertDictEqual(dset["""train"""][0] , get_test_nested_examples()[0][1] ) self.assertDictEqual( dset["""train"""][expected_num_examples - 1] , get_test_nested_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(A__ , builder.name , """default""" , """0.0.0""" , """dataset_info.json""" ) ) ) del dset
64
0
from manim import * class _a (__snake_case ): '''simple docstring''' def __A ( self ): A__ : Optional[int] = Rectangle(height=0.5 , width=0.5 ) A__ : str = Rectangle(height=0.2_5 , width=0.2_5 ) A__ : Optional[Any] = Rectangle(height=0.4_6 , width=0.4_6 ).set_stroke(width=0 ) A__ : Optional[Any] = [mem.copy() for i in range(6 )] A__ : List[str] = [mem.copy() for i in range(6 )] A__ : int = VGroup(*A_ ).arrange(A_ , buff=0 ) A__ : Tuple = VGroup(*A_ ).arrange(A_ , buff=0 ) A__ : Union[str, Any] = VGroup(A_ , A_ ).arrange(A_ , buff=0 ) A__ : Optional[int] = Text("""CPU""" , font_size=24 ) A__ : List[Any] = Group(A_ , A_ ).arrange(A_ , buff=0.5 , aligned_edge=A_ ) cpu.move_to([-2.5, -0.5, 0] ) self.add(A_ ) A__ : List[Any] = [mem.copy() for i in range(4 )] A__ : List[Any] = VGroup(*A_ ).arrange(A_ , buff=0 ) A__ : Optional[Any] = Text("""GPU""" , font_size=24 ) A__ : List[str] = Group(A_ , A_ ).arrange(A_ , buff=0.5 , aligned_edge=A_ ) gpu.move_to([-1, -1, 0] ) self.add(A_ ) A__ : Any = [mem.copy() for i in range(6 )] A__ : Any = VGroup(*A_ ).arrange(A_ , buff=0 ) A__ : Optional[Any] = Text("""Model""" , font_size=24 ) A__ : List[Any] = Group(A_ , A_ ).arrange(A_ , buff=0.5 , aligned_edge=A_ ) model.move_to([3, -1.0, 0] ) self.add(A_ ) A__ : Dict = [] A__ : int = [] A__ : Tuple = [] for i, rect in enumerate(A_ ): rect.set_stroke(A_ ) A__ : Optional[Any] = Rectangle(height=0.4_6 / 4 , width=0.4_6 / 3 ).set_stroke(width=0.0 ).set_fill(A_ , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.0_2 , direction=A_ ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(model_cpu_arr[0] , direction=A_ , buff=0.0 ) else: cpu_target.next_to(model_cpu_arr[i - 1] , direction=A_ , buff=0.0 ) self.add(A_ ) model_cpu_arr.append(A_ ) self.add(*A_ , *A_ , *A_ ) A__ : Any = [mem.copy() for i in range(6 )] A__ : List[str] = VGroup(*A_ ).arrange(A_ , buff=0 ) A__ : Dict = Text("""Loaded Checkpoint""" , font_size=24 ) A__ : Union[str, Any] = Group(A_ , A_ ).arrange(A_ , buff=0.5 , aligned_edge=A_ ) checkpoint.move_to([3, 0.5, 0] ) self.add(A_ ) A__ : int = [] A__ : List[Any] = [] for i, rect in enumerate(A_ ): A__ : int = fill.copy().set_fill(A_ , opacity=0.7 ) target.move_to(A_ ) ckpt_arr.append(A_ ) A__ : Optional[Any] = target.copy() if i < 5: cpu_target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.move_to(cpu_right_col_base[i - 5] ) ckpt_cpu_arr.append(A_ ) self.add(*A_ , *A_ ) A__ : Any = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) A__ : Any = MarkupText( F"""<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model""" , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(A_ , A_ ) A__ : List[str] = MarkupText( F"""<span fgcolor='{BLUE}'>●</span> Checkpoint""" , font_size=18 , ) blue_text.next_to(A_ , DOWN * 2.4 , aligned_edge=key_text.get_left() ) self.add(A_ ) A__ : Optional[int] = MarkupText( F"""Based on the passed in configuration, weights are stored in\na variety of np.memmaps on disk or to a particular device.""" , font_size=24 , ) step_a.move_to([2, 2, 0] ) A__ : Union[str, Any] = [meta_mem.copy() for i in range(6 )] A__ : List[str] = [meta_mem.copy() for i in range(6 )] A__ : str = VGroup(*A_ ).arrange(A_ , buff=0 ) A__ : Union[str, Any] = VGroup(*A_ ).arrange(A_ , buff=0 ) A__ : List[str] = VGroup(A_ , A_ ).arrange(A_ , buff=0 ) A__ : str = Text("""Disk""" , font_size=24 ) A__ : int = Group(A_ , A_ ).arrange(A_ , buff=0.5 , aligned_edge=A_ ) disk.move_to([-4.0, -1.2_5, 0] ) self.play(Write(A_ , run_time=3 ) , Write(A_ , run_time=1 ) , Create(A_ , run_time=1 ) ) A__ : Union[str, Any] = [] for i, rect in enumerate(A_ ): A__ : List[Any] = rect.copy() target.generate_target() target.target.move_to(disk_left_col_base[i] ).scale(0.5 ) animations.append(MoveToTarget(A_ , run_time=1.5 ) ) self.play(*A_ ) self.play(FadeOut(A_ ) ) A__ : Any = MarkupText(F"""Then, the checkpoint is removed from memory\nthrough garbage collection.""" , font_size=24 ) step_a.move_to([2, 2, 0] ) self.play(Write(A_ , run_time=3 ) ) self.play( FadeOut(A_ , A_ , *A_ , *A_ ) , ) self.wait()
716
import warnings from ...utils import logging from .image_processing_poolformer import PoolFormerImageProcessor A_ : Union[str, Any] = logging.get_logger(__name__) class _a (__magic_name__ ): '''simple docstring''' def __init__( self , *A__ , **A__ ): warnings.warn( """The class PoolFormerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use PoolFormerImageProcessor instead.""" , A__ , ) super().__init__(*A__ , **A__ )
64
0
import sys from .dependency_versions_table import deps from .utils.versions import require_version, require_version_core # define which module versions we always want to check at run time # (usually the ones defined in `install_requires` in setup.py) # # order specific notes: # - tqdm must be checked before tokenizers A_ : Dict = '''python tqdm regex requests packaging filelock numpy tokenizers'''.split() if sys.version_info < (3, 7): pkgs_to_check_at_runtime.append('dataclasses') if sys.version_info < (3, 8): pkgs_to_check_at_runtime.append('importlib_metadata') for pkg in pkgs_to_check_at_runtime: if pkg in deps: if pkg == "tokenizers": # must be loaded here, or else tqdm check may fail from .utils import is_tokenizers_available if not is_tokenizers_available(): continue # not required, check version only if installed require_version_core(deps[pkg]) else: raise ValueError(f'''can\'t find {pkg} in {deps.keys()}, check dependency_versions_table.py''') def UpperCamelCase (lowercase_: str , lowercase_: List[str]=None ) -> str: require_version(deps[pkg] , lowercase_ )
717
import inspect import logging import os import random import shutil import tempfile import unittest import pytest import torch from torch import nn from torch.utils.data import DataLoader, TensorDataset from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_cuda from accelerate.utils import ProjectConfiguration, set_seed A_ : Any = logging.getLogger(__name__) def UpperCamelCase (lowercase_: Optional[Any]=2 , lowercase_: Union[str, Any]=3 , lowercase_: int=16 , lowercase_: int = 10 , lowercase_: int = 2 ) -> int: def get_dataset(lowercase_: Optional[int] ): A__ : Optional[Any] = torch.randn(batch_size * n_batches , 1 ) return TensorDataset(lowercase_ , a * x + b + 0.1 * torch.randn(batch_size * n_batches , 1 ) ) A__ : Dict = get_dataset(lowercase_ ) A__ : Any = get_dataset(lowercase_ ) A__ : Dict = DataLoader(lowercase_ , shuffle=lowercase_ , batch_size=lowercase_ , num_workers=4 ) A__ : Optional[Any] = DataLoader(lowercase_ , shuffle=lowercase_ , batch_size=lowercase_ , num_workers=4 ) return (train_dataloader, valid_dataloader) def UpperCamelCase (lowercase_: Optional[Any] , lowercase_: List[str] , lowercase_: int , lowercase_: int , lowercase_: List[str] , lowercase_: Dict=None ) -> List[Any]: A__ : List[Any] = [] for epoch in range(lowercase_ ): # Train quickly model.train() for batch in dataloader: A__ , A__ : Any = batch A__ : Any = model(lowercase_ ) A__ : Any = torch.nn.functional.mse_loss(lowercase_ , lowercase_ ) accelerator.backward(lowercase_ ) optimizer.step() optimizer.zero_grad() rands.append(random.random() ) # Introduce some randomness if scheduler is not None: scheduler.step() return rands class _a (nn.Module ): '''simple docstring''' def __init__( self ): super().__init__() A__ : str = nn.Parameter(torch.randn(1 ) ) A__ : Any = nn.Parameter(torch.randn(1 ) ) def __A ( self , A__ ): return x * self.a + self.b class _a (unittest.TestCase ): '''simple docstring''' def __A ( self ): with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) A__ : Optional[Any] = DummyModel() A__ : Optional[Any] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) A__ , A__ : str = dummy_dataloaders() A__ : Dict = ProjectConfiguration(total_limit=1 , project_dir=A__ , automatic_checkpoint_naming=A__ ) # Train baseline A__ : List[str] = Accelerator(project_config=A__ ) A__ , A__ , A__ , A__ : Any = accelerator.prepare( A__ , A__ , A__ , A__ ) # Save initial accelerator.save_state() # Save second state accelerator.save_state() self.assertEqual(len(os.listdir(accelerator.project_dir ) ) , 1 ) def __A ( self ): with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) A__ : str = DummyModel() A__ : Optional[int] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) A__ , A__ : int = dummy_dataloaders() # Train baseline A__ : str = Accelerator() A__ , A__ , A__ , A__ : List[str] = accelerator.prepare( A__ , A__ , A__ , A__ ) # Save initial A__ : List[Any] = os.path.join(A__ , """initial""" ) accelerator.save_state(A__ ) ((A__) , (A__)) : str = model.a.item(), model.b.item() A__ : Dict = optimizer.state_dict() A__ : List[str] = train(3 , A__ , A__ , A__ , A__ ) ((A__) , (A__)) : str = model.a.item(), model.b.item() A__ : Any = optimizer.state_dict() # Train partially set_seed(42 ) A__ : Optional[int] = DummyModel() A__ : Dict = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) A__ , A__ : Dict = dummy_dataloaders() A__ : List[str] = Accelerator() A__ , A__ , A__ , A__ : Optional[Any] = accelerator.prepare( A__ , A__ , A__ , A__ ) accelerator.load_state(A__ ) ((A__) , (A__)) : Tuple = model.a.item(), model.b.item() A__ : Union[str, Any] = optimizer.state_dict() self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) A__ : List[str] = train(2 , A__ , A__ , A__ , A__ ) # Save everything A__ : Optional[int] = os.path.join(A__ , """checkpoint""" ) accelerator.save_state(A__ ) # Load everything back in and make sure all states work accelerator.load_state(A__ ) test_rands += train(1 , A__ , A__ , A__ , A__ ) ((A__) , (A__)) : Union[str, Any] = model.a.item(), model.b.item() A__ : Optional[int] = optimizer.state_dict() self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) def __A ( self ): with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) A__ : int = DummyModel() A__ : Optional[int] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) A__ , A__ : List[str] = dummy_dataloaders() A__ : str = ProjectConfiguration(automatic_checkpoint_naming=A__ ) # Train baseline A__ : Any = Accelerator(project_dir=A__ , project_config=A__ ) A__ , A__ , A__ , A__ : str = accelerator.prepare( A__ , A__ , A__ , A__ ) # Save initial accelerator.save_state() ((A__) , (A__)) : Tuple = model.a.item(), model.b.item() A__ : int = optimizer.state_dict() A__ : int = train(3 , A__ , A__ , A__ , A__ ) ((A__) , (A__)) : Optional[Any] = model.a.item(), model.b.item() A__ : Any = optimizer.state_dict() # Train partially set_seed(42 ) A__ : Dict = DummyModel() A__ : List[Any] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) A__ , A__ : Union[str, Any] = dummy_dataloaders() A__ : List[Any] = ProjectConfiguration(iteration=1 , automatic_checkpoint_naming=A__ ) A__ : Dict = Accelerator(project_dir=A__ , project_config=A__ ) A__ , A__ , A__ , A__ : Union[str, Any] = accelerator.prepare( A__ , A__ , A__ , A__ ) accelerator.load_state(os.path.join(A__ , """checkpoints""" , """checkpoint_0""" ) ) ((A__) , (A__)) : Optional[int] = model.a.item(), model.b.item() A__ : Tuple = optimizer.state_dict() self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) A__ : str = train(2 , A__ , A__ , A__ , A__ ) # Save everything accelerator.save_state() # Load everything back in and make sure all states work accelerator.load_state(os.path.join(A__ , """checkpoints""" , """checkpoint_1""" ) ) test_rands += train(1 , A__ , A__ , A__ , A__ ) ((A__) , (A__)) : Optional[int] = model.a.item(), model.b.item() A__ : List[Any] = optimizer.state_dict() self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) def __A ( self ): A__ : Union[str, Any] = torch.tensor([1, 2, 3] ) A__ : int = torch.tensor([2, 3, 4] ) A__ : List[Any] = DummyModel() A__ : List[Any] = torch.optim.Adam(net.parameters() ) A__ : Tuple = Accelerator() with self.assertRaises(A__ ) as ve: accelerator.register_for_checkpointing(A__ , A__ , A__ , A__ ) A__ : Any = str(ve.exception ) self.assertTrue("""Item at index 0""" in message ) self.assertTrue("""Item at index 1""" in message ) self.assertFalse("""Item at index 2""" in message ) self.assertFalse("""Item at index 3""" in message ) def __A ( self ): with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) A__ : Any = DummyModel() A__ : Union[str, Any] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) A__ : Dict = torch.optim.lr_scheduler.StepLR(A__ , step_size=1 , gamma=0.9_9 ) A__ , A__ : List[Any] = dummy_dataloaders() A__ : Tuple = ProjectConfiguration(automatic_checkpoint_naming=A__ ) # Train baseline A__ : Optional[Any] = Accelerator(project_dir=A__ , project_config=A__ ) A__ , A__ , A__ , A__ , A__ : Union[str, Any] = accelerator.prepare( A__ , A__ , A__ , A__ , A__ ) # Save initial accelerator.save_state() A__ : Tuple = scheduler.state_dict() train(3 , A__ , A__ , A__ , A__ , A__ ) self.assertNotEqual(A__ , scheduler.state_dict() ) # Load everything back in and make sure all states work accelerator.load_state(os.path.join(A__ , """checkpoints""" , """checkpoint_0""" ) ) self.assertEqual(A__ , scheduler.state_dict() ) def __A ( self ): with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) A__ : Optional[Any] = DummyModel() A__ : int = ProjectConfiguration(automatic_checkpoint_naming=A__ , total_limit=2 ) # Train baseline A__ : List[str] = Accelerator(project_dir=A__ , project_config=A__ ) A__ : Union[str, Any] = accelerator.prepare(A__ ) # Save 3 states: for _ in range(11 ): accelerator.save_state() self.assertTrue(not os.path.exists(os.path.join(A__ , """checkpoints""" , """checkpoint_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(A__ , """checkpoints""" , """checkpoint_9""" ) ) ) self.assertTrue(os.path.exists(os.path.join(A__ , """checkpoints""" , """checkpoint_10""" ) ) ) @require_cuda def __A ( self ): A__ : Dict = ["""torchrun""", F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__ )] execute_subprocess_async(A__ , env=os.environ.copy() ) if __name__ == "__main__": A_ : List[str] = '/tmp/accelerate/state_checkpointing' A_ : Optional[Any] = DummyModel() A_ : Union[str, Any] = torch.optim.Adam(params=model.parameters(), lr=1E-3) A_ : str = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99) A_ , A_ : List[Any] = dummy_dataloaders() A_ : int = ProjectConfiguration(automatic_checkpoint_naming=True) # Train baseline A_ : List[str] = Accelerator(project_dir=savedir, project_config=project_config, mixed_precision='no') if accelerator.process_index == 0: if os.path.exists(savedir): shutil.rmtree(savedir) os.makedirs(savedir) A_ , A_ , A_ , A_ , A_ : List[Any] = accelerator.prepare( model, optimizer, train_dataloader, valid_dataloader, scheduler ) A_ , A_ : Dict = accelerator.prepare(model, optimizer) train(3, model, train_dataloader, optimizer, accelerator, scheduler) # Check that the intial optimizer is loaded on the GPU for group in optimizer.param_groups: A_ : str = group['params'][0].device break assert param_device.type == accelerator.device.type A_ : Optional[Any] = model.cpu() accelerator.wait_for_everyone() accelerator.save_state() accelerator.wait_for_everyone() # Check CPU state accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='cpu') for group in optimizer.param_groups: A_ : str = group['params'][0].device break assert ( param_device.type == torch.device('cpu').type ), f"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}" # Check device state model.to(accelerator.device) accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='on_device') for group in optimizer.param_groups: A_ : Tuple = group['params'][0].device break assert ( param_device.type == accelerator.device.type ), f"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}" # Check error with pytest.raises(TypeError, match='Unsupported optimizer map location passed'): accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='invalid') accelerator.wait_for_everyone() if accelerator.process_index == 0: shutil.rmtree(savedir) accelerator.wait_for_everyone()
64
0
import fire from transformers import AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer def UpperCamelCase (lowercase_: int , lowercase_: Dict , **lowercase_: Dict ) -> Union[str, Any]: A__ : int = AutoConfig.from_pretrained(__lowerCAmelCase , **__lowerCAmelCase ) A__ : str = AutoModelForSeqaSeqLM.from_config(__lowerCAmelCase ) model.save_pretrained(__lowerCAmelCase ) AutoTokenizer.from_pretrained(__lowerCAmelCase ).save_pretrained(__lowerCAmelCase ) return model if __name__ == "__main__": fire.Fire(save_randomly_initialized_version)
718
def UpperCamelCase (lowercase_: str , lowercase_: str ) -> bool: A__ : Union[str, Any] = len(lowercase_ ) A__ : List[Any] = len(lowercase_ ) A__ : List[Any] = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] A__ : str = True for i in range(lowercase_ ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: A__ : int = True if a[i].islower(): A__ : Dict = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
64
0
from typing import List, Optional, Union import torch from transformers import ( XLMRobertaTokenizer, ) from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) from .text_encoder import MultilingualCLIP A_ : Tuple = logging.get_logger(__name__) # pylint: disable=invalid-name A_ : str = '\n Examples:\n ```py\n >>> from diffusers import KandinskyPipeline, KandinskyPriorPipeline\n >>> import torch\n\n >>> pipe_prior = KandinskyPriorPipeline.from_pretrained("kandinsky-community/Kandinsky-2-1-prior")\n >>> pipe_prior.to("cuda")\n\n >>> prompt = "red cat, 4k photo"\n >>> out = pipe_prior(prompt)\n >>> image_emb = out.image_embeds\n >>> negative_image_emb = out.negative_image_embeds\n\n >>> pipe = KandinskyPipeline.from_pretrained("kandinsky-community/kandinsky-2-1")\n >>> pipe.to("cuda")\n\n >>> image = pipe(\n ... prompt,\n ... image_embeds=image_emb,\n ... negative_image_embeds=negative_image_emb,\n ... height=768,\n ... width=768,\n ... num_inference_steps=100,\n ... ).images\n\n >>> image[0].save("cat.png")\n ```\n' def UpperCamelCase (lowercase_: Optional[Any] , lowercase_: Any , lowercase_: Tuple=8 ) -> Optional[Any]: A__ : int = h // scale_factor**2 if h % scale_factor**2 != 0: new_h += 1 A__ : List[Any] = w // scale_factor**2 if w % scale_factor**2 != 0: new_w += 1 return new_h * scale_factor, new_w * scale_factor class _a(__a ): '''simple docstring''' def __init__( self , A__ , A__ , A__ , A__ , A__ , ): super().__init__() self.register_modules( text_encoder=lowerCAmelCase_ , tokenizer=lowerCAmelCase_ , unet=lowerCAmelCase_ , scheduler=lowerCAmelCase_ , movq=lowerCAmelCase_ , ) A__ : int = 2 ** (len(self.movq.config.block_out_channels ) - 1) def __A ( self , A__ , A__ , A__ , A__ , A__ , A__ ): if latents is None: A__ : Union[str, Any] = randn_tensor(lowerCAmelCase_ , generator=lowerCAmelCase_ , device=lowerCAmelCase_ , dtype=lowerCAmelCase_ ) else: if latents.shape != shape: raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {shape}""" ) A__ : int = latents.to(lowerCAmelCase_ ) A__ : Union[str, Any] = latents * scheduler.init_noise_sigma return latents def __A ( self , A__ , A__ , A__ , A__ , A__=None , ): A__ : int = len(lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else 1 # get prompt text embeddings A__ : Optional[Any] = self.tokenizer( lowerCAmelCase_ , padding="""max_length""" , truncation=lowerCAmelCase_ , max_length=77 , return_attention_mask=lowerCAmelCase_ , add_special_tokens=lowerCAmelCase_ , return_tensors="""pt""" , ) A__ : Optional[int] = text_inputs.input_ids A__ : str = self.tokenizer(lowerCAmelCase_ , padding="""longest""" , return_tensors="""pt""" ).input_ids if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(lowerCAmelCase_ , lowerCAmelCase_ ): A__ : int = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1] ) 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}""" ) A__ : List[str] = text_input_ids.to(lowerCAmelCase_ ) A__ : Dict = text_inputs.attention_mask.to(lowerCAmelCase_ ) A__ , A__ : int = self.text_encoder( input_ids=lowerCAmelCase_ , attention_mask=lowerCAmelCase_ ) A__ : int = prompt_embeds.repeat_interleave(lowerCAmelCase_ , dim=0 ) A__ : int = text_encoder_hidden_states.repeat_interleave(lowerCAmelCase_ , dim=0 ) A__ : int = text_mask.repeat_interleave(lowerCAmelCase_ , dim=0 ) if do_classifier_free_guidance: A__ : int = 42 if negative_prompt is None: A__ : Union[str, Any] = [""""""] * batch_size elif type(lowerCAmelCase_ ) is not type(lowerCAmelCase_ ): raise TypeError( F"""`negative_prompt` should be the same type to `prompt`, but got {type(lowerCAmelCase_ )} !=""" F""" {type(lowerCAmelCase_ )}.""" ) elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): A__ : Optional[Any] = [negative_prompt] elif batch_size != len(lowerCAmelCase_ ): raise ValueError( F"""`negative_prompt`: {negative_prompt} has batch size {len(lowerCAmelCase_ )}, but `prompt`:""" F""" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches""" """ the batch size of `prompt`.""" ) else: A__ : List[Any] = negative_prompt A__ : Optional[Any] = self.tokenizer( lowerCAmelCase_ , padding="""max_length""" , max_length=77 , truncation=lowerCAmelCase_ , return_attention_mask=lowerCAmelCase_ , add_special_tokens=lowerCAmelCase_ , return_tensors="""pt""" , ) A__ : Optional[Any] = uncond_input.input_ids.to(lowerCAmelCase_ ) A__ : Any = uncond_input.attention_mask.to(lowerCAmelCase_ ) A__ , A__ : Dict = self.text_encoder( input_ids=lowerCAmelCase_ , attention_mask=lowerCAmelCase_ ) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method A__ : Optional[Any] = negative_prompt_embeds.shape[1] A__ : Any = negative_prompt_embeds.repeat(1 , lowerCAmelCase_ ) A__ : Tuple = negative_prompt_embeds.view(batch_size * num_images_per_prompt , lowerCAmelCase_ ) A__ : List[str] = uncond_text_encoder_hidden_states.shape[1] A__ : str = uncond_text_encoder_hidden_states.repeat(1 , lowerCAmelCase_ , 1 ) A__ : Tuple = uncond_text_encoder_hidden_states.view( batch_size * num_images_per_prompt , lowerCAmelCase_ , -1 ) A__ : Tuple = uncond_text_mask.repeat_interleave(lowerCAmelCase_ , dim=0 ) # done duplicates # 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 A__ : List[Any] = torch.cat([negative_prompt_embeds, prompt_embeds] ) A__ : List[str] = torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states] ) A__ : Tuple = torch.cat([uncond_text_mask, text_mask] ) return prompt_embeds, text_encoder_hidden_states, text_mask def __A ( self , A__=0 ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) A__ : Optional[int] = torch.device(F"""cuda:{gpu_id}""" ) A__ : List[str] = [ self.unet, self.text_encoder, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(lowerCAmelCase_ , lowerCAmelCase_ ) def __A ( self , A__=0 ): if is_accelerate_available() and is_accelerate_version(""">=""" , """0.17.0.dev0""" ): from accelerate import cpu_offload_with_hook else: raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.""" ) A__ : Union[str, Any] = torch.device(F"""cuda:{gpu_id}""" ) if self.device.type != "cpu": self.to("""cpu""" , silence_dtype_warnings=lowerCAmelCase_ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) A__ : str = None for cpu_offloaded_model in [self.text_encoder, self.unet, self.movq]: A__ , A__ : Union[str, Any] = cpu_offload_with_hook(lowerCAmelCase_ , lowerCAmelCase_ , prev_module_hook=lowerCAmelCase_ ) if self.safety_checker is not None: A__ , A__ : Dict = cpu_offload_with_hook(self.safety_checker , lowerCAmelCase_ , prev_module_hook=lowerCAmelCase_ ) # We'll offload the last model manually. A__ : Any = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __A ( self ): if not hasattr(self.unet , """_hf_hook""" ): return self.device for module in self.unet.modules(): if ( hasattr(lowerCAmelCase_ , """_hf_hook""" ) and hasattr(module._hf_hook , """execution_device""" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(lowerCAmelCase_ ) def __call__( self , A__ , A__ , A__ , A__ = None , A__ = 512 , A__ = 512 , A__ = 100 , A__ = 4.0 , A__ = 1 , A__ = None , A__ = None , A__ = "pil" , A__ = True , ): if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): A__ : List[str] = 1 elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): A__ : List[Any] = len(lowerCAmelCase_ ) else: raise ValueError(F"""`prompt` has to be of type `str` or `list` but is {type(lowerCAmelCase_ )}""" ) A__ : Union[str, Any] = self._execution_device A__ : Tuple = batch_size * num_images_per_prompt A__ : int = guidance_scale > 1.0 A__ , A__ , A__ : Union[str, Any] = self._encode_prompt( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): A__ : int = torch.cat(lowerCAmelCase_ , dim=0 ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): A__ : Dict = torch.cat(lowerCAmelCase_ , dim=0 ) if do_classifier_free_guidance: A__ : List[Any] = image_embeds.repeat_interleave(lowerCAmelCase_ , dim=0 ) A__ : Optional[int] = negative_image_embeds.repeat_interleave(lowerCAmelCase_ , dim=0 ) A__ : Tuple = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to( dtype=prompt_embeds.dtype , device=lowerCAmelCase_ ) self.scheduler.set_timesteps(lowerCAmelCase_ , device=lowerCAmelCase_ ) A__ : List[Any] = self.scheduler.timesteps A__ : str = self.unet.config.in_channels A__ , A__ : List[str] = get_new_h_w(lowerCAmelCase_ , lowerCAmelCase_ , self.movq_scale_factor ) # create initial latent A__ : Dict = self.prepare_latents( (batch_size, num_channels_latents, height, width) , text_encoder_hidden_states.dtype , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , self.scheduler , ) for i, t in enumerate(self.progress_bar(lowerCAmelCase_ ) ): # expand the latents if we are doing classifier free guidance A__ : Dict = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents A__ : Any = {"""text_embeds""": prompt_embeds, """image_embeds""": image_embeds} A__ : Dict = self.unet( sample=lowerCAmelCase_ , timestep=lowerCAmelCase_ , encoder_hidden_states=lowerCAmelCase_ , added_cond_kwargs=lowerCAmelCase_ , return_dict=lowerCAmelCase_ , )[0] if do_classifier_free_guidance: A__ , A__ : Dict = noise_pred.split(latents.shape[1] , dim=1 ) A__ , A__ : Dict = noise_pred.chunk(2 ) A__ , A__ : Any = variance_pred.chunk(2 ) A__ : Union[str, Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) A__ : int = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , """variance_type""" ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): A__ , A__ : int = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 A__ : int = self.scheduler.step( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , generator=lowerCAmelCase_ , ).prev_sample # post-processing A__ : Optional[int] = self.movq.decode(lowerCAmelCase_ , force_not_quantize=lowerCAmelCase_ )["""sample"""] if output_type not in ["pt", "np", "pil"]: raise ValueError(F"""Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}""" ) if output_type in ["np", "pil"]: A__ : List[str] = image * 0.5 + 0.5 A__ : List[str] = image.clamp(0 , 1 ) A__ : Union[str, Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": A__ : Tuple = self.numpy_to_pil(lowerCAmelCase_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=lowerCAmelCase_ )
719
import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin A_ : Dict = random.Random() if is_torch_available(): import torch def UpperCamelCase (lowercase_: Tuple , lowercase_: Tuple=1.0 , lowercase_: Dict=None , lowercase_: int=None ) -> str: if rng is None: A__ : Optional[Any] = global_rng A__ : List[str] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class _a (unittest.TestCase ): '''simple docstring''' def __init__( self , A__ , A__=7 , A__=400 , A__=2000 , A__=1 , A__=0.0 , A__=1_6000 , A__=True , A__=True , ): A__ : Any = parent A__ : Optional[int] = batch_size A__ : Union[str, Any] = min_seq_length A__ : Dict = max_seq_length A__ : Tuple = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) A__ : str = feature_size A__ : Optional[int] = padding_value A__ : List[str] = sampling_rate A__ : List[str] = return_attention_mask A__ : int = do_normalize def __A ( self ): return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def __A ( self , A__=False , A__=False ): def _flatten(A__ ): return list(itertools.chain(*A__ ) ) if equal_length: A__ : Dict = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size A__ : Union[str, Any] = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: A__ : Optional[int] = [np.asarray(A__ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class _a (__magic_name__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: int = ASTFeatureExtractor def __A ( self ): A__ : Optional[Any] = ASTFeatureExtractionTester(self ) def __A ( self ): # Tests that all call wrap to encode_plus and batch_encode_plus A__ : Optional[int] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 A__ : List[Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] A__ : Optional[Any] = [np.asarray(A__ ) for speech_input in speech_inputs] # Test not batched input A__ : Tuple = feat_extract(speech_inputs[0] , return_tensors="""np""" ).input_values A__ : Tuple = feat_extract(np_speech_inputs[0] , return_tensors="""np""" ).input_values self.assertTrue(np.allclose(A__ , A__ , atol=1e-3 ) ) # Test batched A__ : Tuple = feat_extract(A__ , padding=A__ , return_tensors="""np""" ).input_values A__ : Tuple = feat_extract(A__ , padding=A__ , return_tensors="""np""" ).input_values for enc_seq_a, enc_seq_a in zip(A__ , A__ ): self.assertTrue(np.allclose(A__ , A__ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. A__ : int = [floats_list((1, x) )[0] for x in (800, 800, 800)] A__ : List[str] = np.asarray(A__ ) A__ : Union[str, Any] = feat_extract(A__ , return_tensors="""np""" ).input_values A__ : Optional[Any] = feat_extract(A__ , return_tensors="""np""" ).input_values for enc_seq_a, enc_seq_a in zip(A__ , A__ ): self.assertTrue(np.allclose(A__ , A__ , atol=1e-3 ) ) @require_torch def __A ( self ): import torch A__ : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) A__ : Tuple = np.random.rand(100 ).astype(np.floataa ) A__ : Tuple = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: A__ : List[str] = feature_extractor.pad([{"""input_values""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) A__ : Any = feature_extractor.pad([{"""input_values""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def __A ( self , A__ ): from datasets import load_dataset A__ : str = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech A__ : str = ds.sort("""id""" ).select(range(A__ ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] @require_torch def __A ( self ): # fmt: off A__ : Optional[Any] = torch.tensor( [-0.9_8_9_4, -1.2_7_7_6, -0.9_0_6_6, -1.2_7_7_6, -0.9_3_4_9, -1.2_6_0_9, -1.0_3_8_6, -1.2_7_7_6, -1.1_5_6_1, -1.2_7_7_6, -1.2_0_5_2, -1.2_7_2_3, -1.2_1_9_0, -1.2_1_3_2, -1.2_7_7_6, -1.1_1_3_3, -1.1_9_5_3, -1.1_3_4_3, -1.1_5_8_4, -1.2_2_0_3, -1.1_7_7_0, -1.2_4_7_4, -1.2_3_8_1, -1.1_9_3_6, -0.9_2_7_0, -0.8_3_1_7, -0.8_0_4_9, -0.7_7_0_6, -0.7_5_6_5, -0.7_8_6_9] ) # fmt: on A__ : Any = self._load_datasamples(1 ) A__ : Tuple = ASTFeatureExtractor() A__ : Dict = feature_extractor(A__ , return_tensors="""pt""" ).input_values self.assertEquals(input_values.shape , (1, 1024, 128) ) self.assertTrue(torch.allclose(input_values[0, 0, :30] , A__ , atol=1e-4 ) )
64
0
from bisect import bisect from itertools import accumulate def UpperCamelCase (lowercase_: str , lowercase_: List[str] , lowercase_: List[str] , lowercase_: Union[str, Any] ) -> Optional[int]: A__ : List[Any] = sorted(zip(UpperCamelCase__ , UpperCamelCase__ ) , key=lambda lowercase_ : x[0] / x[1] , reverse=UpperCamelCase__ ) A__ : List[Any] = [i[0] for i in r], [i[1] for i in r] A__ : Optional[int] = list(accumulate(UpperCamelCase__ ) ) A__ : int = bisect(UpperCamelCase__ , UpperCamelCase__ ) return ( 0 if k == 0 else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k] ) ) if __name__ == "__main__": import doctest doctest.testmod()
720
from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class _a (__magic_name__ , __magic_name__ , __magic_name__ ): '''simple docstring''' UpperCAmelCase__: str = [r'''h\.\d+\.attn\.bias''', r'''h\.\d+\.attn\.masked_bias'''] @register_to_config def __init__( self , A__ , A__ , A__ = None , A__ = 5_0257 , A__ = 1024 , A__ = 768 , A__ = 12 , A__ = 12 , A__ = None , A__ = "gelu_new" , A__ = 0.1 , A__ = 0.1 , A__ = 0.1 , A__ = 1e-5 , A__ = 0.0_2 , A__ = True , A__ = True , A__ = False , A__ = False , ): super().__init__() A__ : Union[str, Any] = prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( F"""`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and""" F""" `n_embd`: {n_embd} are not equal.""" ) A__ : str = prefix_inner_dim A__ : Optional[Any] = prefix_hidden_dim A__ : Tuple = ( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) A__ : int = ( nn.Linear(self.prefix_hidden_dim , A__ ) if self.prefix_hidden_dim is not None else nn.Identity() ) A__ : Tuple = GPTaConfig( vocab_size=A__ , n_positions=A__ , n_embd=A__ , n_layer=A__ , n_head=A__ , n_inner=A__ , activation_function=A__ , resid_pdrop=A__ , embd_pdrop=A__ , attn_pdrop=A__ , layer_norm_epsilon=A__ , initializer_range=A__ , scale_attn_weights=A__ , use_cache=A__ , scale_attn_by_inverse_layer_idx=A__ , reorder_and_upcast_attn=A__ , ) A__ : int = GPTaLMHeadModel(A__ ) def __A ( self , A__ , A__ , A__ = None , A__ = None , ): A__ : List[str] = self.transformer.transformer.wte(A__ ) A__ : int = self.encode_prefix(A__ ) A__ : int = self.decode_prefix(A__ ) A__ : Optional[Any] = torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: A__ : Any = self.get_dummy_token(input_ids.shape[0] , input_ids.device ) A__ : List[Any] = torch.cat((dummy_token, input_ids) , dim=1 ) A__ : List[str] = self.transformer(inputs_embeds=A__ , labels=A__ , attention_mask=A__ ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def __A ( self , A__ , A__ ): return torch.zeros(A__ , self.prefix_length , dtype=torch.intaa , device=A__ ) def __A ( self , A__ ): return self.encode_prefix(A__ ) @torch.no_grad() def __A ( self , A__ , A__ , A__ ): A__ : List[Any] = torch.split(A__ , 1 , dim=0 ) A__ : Optional[int] = [] A__ : str = [] for feature in features: A__ : Dict = self.decode_prefix(feature.to(A__ ) ) # back to the clip feature # Only support beam search for now A__ , A__ : Union[str, Any] = self.generate_beam( input_embeds=A__ , device=A__ , eos_token_id=A__ ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) A__ : int = torch.stack(A__ ) A__ : List[Any] = torch.stack(A__ ) return generated_tokens, generated_seq_lengths @torch.no_grad() def __A ( self , A__=None , A__=None , A__=None , A__ = 5 , A__ = 67 , A__ = 1.0 , A__ = None , ): A__ : Any = eos_token_id A__ : Any = None A__ : Optional[int] = None A__ : Optional[Any] = torch.ones(A__ , device=A__ , dtype=torch.int ) A__ : Any = torch.zeros(A__ , device=A__ , dtype=torch.bool ) if input_embeds is not None: A__ : Dict = input_embeds else: A__ : str = self.transformer.transformer.wte(A__ ) for i in range(A__ ): A__ : Dict = self.transformer(inputs_embeds=A__ ) A__ : str = outputs.logits A__ : Union[str, Any] = logits[:, -1, :] / (temperature if temperature > 0 else 1.0) A__ : Any = logits.softmax(-1 ).log() if scores is None: A__ , A__ : Optional[int] = logits.topk(A__ , -1 ) A__ : List[Any] = generated.expand(A__ , *generated.shape[1:] ) A__ , A__ : List[Any] = next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: A__ : Optional[Any] = next_tokens else: A__ : List[Any] = tokens.expand(A__ , *tokens.shape[1:] ) A__ : int = torch.cat((tokens, next_tokens) , dim=1 ) else: A__ : Optional[int] = -float(np.inf ) A__ : List[Any] = 0 A__ : str = scores[:, None] + logits seq_lengths[~is_stopped] += 1 A__ : Dict = scores_sum / seq_lengths[:, None] A__ , A__ : List[Any] = scores_sum_average.view(-1 ).topk(A__ , -1 ) A__ : Tuple = next_tokens // scores_sum.shape[1] A__ : Optional[Any] = seq_lengths[next_tokens_source] A__ : List[str] = next_tokens % scores_sum.shape[1] A__ : Optional[int] = next_tokens.unsqueeze(1 ) A__ : int = tokens[next_tokens_source] A__ : List[Any] = torch.cat((tokens, next_tokens) , dim=1 ) A__ : str = generated[next_tokens_source] A__ : Optional[Any] = scores_sum_average * seq_lengths A__ : Union[str, Any] = is_stopped[next_tokens_source] A__ : str = self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) A__ : Optional[int] = torch.cat((generated, next_token_embed) , dim=1 ) A__ : List[str] = is_stopped + next_tokens.eq(A__ ).squeeze() if is_stopped.all(): break A__ : Dict = scores / seq_lengths A__ : Dict = scores.argsort(descending=A__ ) # tokens tensors are already padded to max_seq_length A__ : Union[str, Any] = [tokens[i] for i in order] A__ : Any = torch.stack(A__ , dim=0 ) A__ : Dict = torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
64
0
from math import asin, atan, cos, radians, sin, sqrt, tan A_ = 637_8137.0 A_ = 635_6752.31_4245 A_ = 637_8137 def UpperCamelCase (lowercase_: float , lowercase_: float , lowercase_: float , lowercase_: float ) -> Any: A__ : str = (AXIS_A - AXIS_B) / AXIS_A A__ : int = atan((1 - flattening) * tan(radians(_UpperCamelCase ) ) ) A__ : Any = atan((1 - flattening) * tan(radians(_UpperCamelCase ) ) ) A__ : List[str] = radians(_UpperCamelCase ) A__ : Union[str, Any] = radians(_UpperCamelCase ) # Equation A__ : Optional[Any] = sin((phi_a - phi_a) / 2 ) A__ : str = sin((lambda_a - lambda_a) / 2 ) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda A__ : List[str] = sqrt(sin_sq_phi + (cos(_UpperCamelCase ) * cos(_UpperCamelCase ) * sin_sq_lambda) ) return 2 * RADIUS * asin(_UpperCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
721
import io import itertools import json from dataclasses import dataclass from typing import Optional import pyarrow as pa import pyarrow.json as paj import datasets from datasets.table import table_cast from datasets.utils.file_utils import readline A_ : Tuple = datasets.utils.logging.get_logger(__name__) @dataclass class _a (datasets.BuilderConfig ): '''simple docstring''' UpperCAmelCase__: Optional[datasets.Features] = None UpperCAmelCase__: str = "utf-8" UpperCAmelCase__: Optional[str] = None UpperCAmelCase__: Optional[str] = None UpperCAmelCase__: bool = True # deprecated UpperCAmelCase__: Optional[int] = None # deprecated UpperCAmelCase__: int = 10 << 20 # 10MB UpperCAmelCase__: Optional[bool] = None class _a (datasets.ArrowBasedBuilder ): '''simple docstring''' UpperCAmelCase__: List[str] = JsonConfig def __A ( self ): if self.config.block_size is not None: logger.warning("""The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead""" ) A__ : Union[str, Any] = self.config.block_size if self.config.use_threads is not True: logger.warning( """The JSON loader parameter `use_threads` is deprecated and doesn't have any effect anymore.""" ) if self.config.newlines_in_values is not None: raise ValueError("""The JSON loader parameter `newlines_in_values` is no longer supported""" ) return datasets.DatasetInfo(features=self.config.features ) def __A ( self , A__ ): if not self.config.data_files: raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}""" ) A__ : int = dl_manager.download_and_extract(self.config.data_files ) if isinstance(A__ , (str, list, tuple) ): A__ : Optional[Any] = data_files if isinstance(A__ , A__ ): A__ : List[str] = [files] A__ : int = [dl_manager.iter_files(A__ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""files""": files} )] A__ : List[str] = [] for split_name, files in data_files.items(): if isinstance(A__ , A__ ): A__ : Optional[int] = [files] A__ : Optional[int] = [dl_manager.iter_files(A__ ) for file in files] splits.append(datasets.SplitGenerator(name=A__ , gen_kwargs={"""files""": files} ) ) return splits def __A ( self , A__ ): if self.config.features is not None: # adding missing columns for column_name in set(self.config.features ) - set(pa_table.column_names ): A__ : Optional[Any] = self.config.features.arrow_schema.field(A__ ).type A__ : str = pa_table.append_column(A__ , pa.array([None] * len(A__ ) , type=A__ ) ) # more expensive cast to support nested structures with keys in a different order # allows str <-> int/float or str to Audio for example A__ : Optional[int] = table_cast(A__ , self.config.features.arrow_schema ) return pa_table def __A ( self , A__ ): for file_idx, file in enumerate(itertools.chain.from_iterable(A__ ) ): # If the file is one json object and if we need to look at the list of items in one specific field if self.config.field is not None: with open(A__ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: A__ : Optional[Any] = json.load(A__ ) # We keep only the field we are interested in A__ : Optional[int] = dataset[self.config.field] # We accept two format: a list of dicts or a dict of lists if isinstance(A__ , (list, tuple) ): A__ : Union[str, Any] = set().union(*[row.keys() for row in dataset] ) A__ : Any = {col: [row.get(A__ ) for row in dataset] for col in keys} else: A__ : Any = dataset A__ : Any = pa.Table.from_pydict(A__ ) yield file_idx, self._cast_table(A__ ) # If the file has one json object per line else: with open(A__ , """rb""" ) as f: A__ : List[str] = 0 # Use block_size equal to the chunk size divided by 32 to leverage multithreading # Set a default minimum value of 16kB if the chunk size is really small A__ : List[str] = max(self.config.chunksize // 32 , 16 << 10 ) A__ : Any = ( self.config.encoding_errors if self.config.encoding_errors is not None else """strict""" ) while True: A__ : Dict = f.read(self.config.chunksize ) if not batch: break # Finish current line try: batch += f.readline() except (AttributeError, io.UnsupportedOperation): batch += readline(A__ ) # PyArrow only accepts utf-8 encoded bytes if self.config.encoding != "utf-8": A__ : List[Any] = batch.decode(self.config.encoding , errors=A__ ).encode("""utf-8""" ) try: while True: try: A__ : str = paj.read_json( io.BytesIO(A__ ) , read_options=paj.ReadOptions(block_size=A__ ) ) break except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e: if ( isinstance(A__ , pa.ArrowInvalid ) and "straddling" not in str(A__ ) or block_size > len(A__ ) ): raise else: # Increase the block size in case it was too small. # The block size will be reset for the next file. logger.debug( F"""Batch of {len(A__ )} bytes couldn't be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.""" ) block_size *= 2 except pa.ArrowInvalid as e: try: with open( A__ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: A__ : Optional[Any] = json.load(A__ ) except json.JSONDecodeError: logger.error(F"""Failed to read file '{file}' with error {type(A__ )}: {e}""" ) raise e # If possible, parse the file as a list of json objects and exit the loop if isinstance(A__ , A__ ): # list is the only sequence type supported in JSON try: A__ : str = set().union(*[row.keys() for row in dataset] ) A__ : List[str] = {col: [row.get(A__ ) for row in dataset] for col in keys} A__ : int = pa.Table.from_pydict(A__ ) except (pa.ArrowInvalid, AttributeError) as e: logger.error(F"""Failed to read file '{file}' with error {type(A__ )}: {e}""" ) raise ValueError(F"""Not able to read records in the JSON file at {file}.""" ) from None yield file_idx, self._cast_table(A__ ) break else: logger.error(F"""Failed to read file '{file}' with error {type(A__ )}: {e}""" ) raise ValueError( F"""Not able to read records in the JSON file at {file}. """ F"""You should probably indicate the field of the JSON file containing your records. """ F"""This JSON file contain the following fields: {str(list(dataset.keys() ) )}. """ F"""Select the correct one and provide it as `field='XXX'` to the dataset loading method. """ ) from None # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(A__ ) batch_idx += 1
64
0
from __future__ import annotations import inspect import unittest from transformers import ViTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFViTForImageClassification, TFViTModel if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class _a : '''simple docstring''' def __init__( self , A__ , A__=13 , A__=30 , A__=2 , A__=3 , A__=True , A__=True , A__=32 , A__=2 , A__=4 , A__=37 , A__="gelu" , A__=0.1 , A__=0.1 , A__=10 , A__=0.0_2 , A__=3 , A__=None , ): A__ : Any = parent A__ : Optional[int] = batch_size A__ : int = image_size A__ : Tuple = patch_size A__ : Dict = num_channels A__ : List[str] = is_training A__ : str = use_labels A__ : int = hidden_size A__ : List[Any] = num_hidden_layers A__ : List[str] = num_attention_heads A__ : List[Any] = intermediate_size A__ : List[Any] = hidden_act A__ : Tuple = hidden_dropout_prob A__ : Union[str, Any] = attention_probs_dropout_prob A__ : Union[str, Any] = type_sequence_label_size A__ : List[Any] = initializer_range A__ : List[Any] = scope # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) A__ : str = (image_size // patch_size) ** 2 A__ : int = num_patches + 1 def __A ( self ): A__ : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A__ : int = None if self.use_labels: A__ : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ : Dict = self.get_config() return config, pixel_values, labels def __A ( self ): return ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=A__ , initializer_range=self.initializer_range , ) def __A ( self , A__ , A__ , A__ ): A__ : Optional[int] = TFViTModel(config=A__ ) A__ : Dict = model(A__ , training=A__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # Test with an image with different size than the one specified in config. A__ : Dict = self.image_size // 2 A__ : List[str] = pixel_values[:, :, :image_size, :image_size] A__ : List[str] = model(A__ , interpolate_pos_encoding=A__ , training=A__ ) A__ : List[str] = (image_size // self.patch_size) ** 2 + 1 self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, seq_length, self.hidden_size) ) def __A ( self , A__ , A__ , A__ ): A__ : Dict = self.type_sequence_label_size A__ : Optional[int] = TFViTForImageClassification(A__ ) A__ : Tuple = model(A__ , labels=A__ , training=A__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # Test with an image with different size than the one specified in config. A__ : Optional[Any] = self.image_size // 2 A__ : str = pixel_values[:, :, :image_size, :image_size] A__ : Optional[int] = model(A__ , interpolate_pos_encoding=A__ , training=A__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images A__ : Tuple = 1 A__ : Union[str, Any] = TFViTForImageClassification(A__ ) A__ : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A__ : str = model(A__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __A ( self ): A__ : List[str] = self.prepare_config_and_inputs() A__ , A__ , A__ : Tuple = config_and_inputs A__ : int = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class _a (__a , __a , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: Tuple = (TFViTModel, TFViTForImageClassification) if is_tf_available() else () UpperCAmelCase__: Any = ( {'''feature-extraction''': TFViTModel, '''image-classification''': TFViTForImageClassification} if is_tf_available() else {} ) UpperCAmelCase__: Union[str, Any] = False UpperCAmelCase__: Union[str, Any] = False UpperCAmelCase__: Any = False def __A ( self ): A__ : Optional[int] = TFViTModelTester(self ) A__ : Union[str, Any] = ConfigTester(self , config_class=A__ , has_text_modality=A__ , hidden_size=37 ) def __A ( self ): self.config_tester.run_common_tests() @unittest.skip(reason="""ViT does not use inputs_embeds""" ) def __A ( self ): pass @unittest.skip(reason="""ViT does not use inputs_embeds""" ) def __A ( self ): pass def __A ( self ): A__ , A__ : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A__ : Dict = model_class(A__ ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) A__ : int = model.get_output_embeddings() self.assertTrue(x is None or isinstance(A__ , tf.keras.layers.Layer ) ) def __A ( self ): A__ , A__ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A__ : str = model_class(A__ ) A__ : List[Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A__ : int = [*signature.parameters.keys()] A__ : List[str] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , A__ ) def __A ( self ): A__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A__ ) def __A ( self ): A__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A__ ) @slow def __A ( self ): A__ : Optional[Any] = TFViTModel.from_pretrained("""google/vit-base-patch16-224""" ) self.assertIsNotNone(A__ ) def UpperCamelCase () -> Any: A__ : Optional[int] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class _a (unittest.TestCase ): '''simple docstring''' @cached_property def __A ( self ): return ViTImageProcessor.from_pretrained("""google/vit-base-patch16-224""" ) if is_vision_available() else None @slow def __A ( self ): A__ : Any = TFViTForImageClassification.from_pretrained("""google/vit-base-patch16-224""" ) A__ : str = self.default_image_processor A__ : Dict = prepare_img() A__ : int = image_processor(images=A__ , return_tensors="""tf""" ) # forward pass A__ : Optional[int] = model(**A__ ) # verify the logits A__ : Optional[int] = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , A__ ) A__ : str = tf.constant([-0.2_7_4_4, 0.8_2_1_5, -0.0_8_3_6] ) tf.debugging.assert_near(outputs.logits[0, :3] , A__ , atol=1e-4 )
700
import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore A_ : Dict = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" A_ : Optional[Any] = [file for file in filepaths if file != file.lower()] if upper_files: print(f'''{len(upper_files)} files contain uppercase characters:''') print('\n'.join(upper_files) + '\n') A_ : Tuple = [file for file in filepaths if ' ' in file] if space_files: print(f'''{len(space_files)} files contain space characters:''') print('\n'.join(space_files) + '\n') A_ : Any = [file for file in filepaths if '-' in file] if hyphen_files: print(f'''{len(hyphen_files)} files contain hyphen characters:''') print('\n'.join(hyphen_files) + '\n') A_ : List[str] = [file for file in filepaths if os.sep not in file] if nodir_files: print(f'''{len(nodir_files)} files are not in a directory:''') print('\n'.join(nodir_files) + '\n') A_ : Any = len(upper_files + space_files + hyphen_files + nodir_files) if bad_files: import sys sys.exit(bad_files)
64
0
import os import unittest from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, BertTokenizer, 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 _a (__magic_name__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: Tuple = BertTokenizer UpperCAmelCase__: Tuple = BertTokenizerFast UpperCAmelCase__: Dict = True UpperCAmelCase__: List[Any] = True UpperCAmelCase__: List[Any] = filter_non_english def __A ( self ): super().setUp() A__ : Dict = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] A__ : Optional[int] = 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] ) ) def __A ( self , A__ ): A__ : Dict = """UNwant\u00E9d,running""" A__ : Union[str, Any] = """unwanted, running""" return input_text, output_text def __A ( self ): A__ : int = self.tokenizer_class(self.vocab_file ) A__ : List[str] = 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 __A ( self ): if not self.test_rust_tokenizer: return A__ : Tuple = self.get_tokenizer() A__ : List[str] = self.get_rust_tokenizer() A__ : List[str] = """UNwant\u00E9d,running""" A__ : List[str] = tokenizer.tokenize(A__ ) A__ : List[str] = rust_tokenizer.tokenize(A__ ) self.assertListEqual(A__ , A__ ) A__ : Tuple = tokenizer.encode(A__ , add_special_tokens=A__ ) A__ : Dict = rust_tokenizer.encode(A__ , add_special_tokens=A__ ) self.assertListEqual(A__ , A__ ) A__ : int = self.get_rust_tokenizer() A__ : Union[str, Any] = tokenizer.encode(A__ ) A__ : int = rust_tokenizer.encode(A__ ) self.assertListEqual(A__ , A__ ) # With lower casing A__ : Dict = self.get_tokenizer(do_lower_case=A__ ) A__ : Dict = self.get_rust_tokenizer(do_lower_case=A__ ) A__ : Union[str, Any] = """UNwant\u00E9d,running""" A__ : List[Any] = tokenizer.tokenize(A__ ) A__ : Union[str, Any] = rust_tokenizer.tokenize(A__ ) self.assertListEqual(A__ , A__ ) A__ : Optional[Any] = tokenizer.encode(A__ , add_special_tokens=A__ ) A__ : Optional[Any] = rust_tokenizer.encode(A__ , add_special_tokens=A__ ) self.assertListEqual(A__ , A__ ) A__ : int = self.get_rust_tokenizer() A__ : Union[str, Any] = tokenizer.encode(A__ ) A__ : List[Any] = rust_tokenizer.encode(A__ ) self.assertListEqual(A__ , A__ ) def __A ( self ): A__ : Optional[int] = BasicTokenizer() self.assertListEqual(tokenizer.tokenize("""ah\u535A\u63A8zz""" ) , ["""ah""", """\u535A""", """\u63A8""", """zz"""] ) def __A ( self ): A__ : Dict = 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 __A ( self ): A__ : Any = 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 __A ( self ): A__ : str = 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 __A ( self ): A__ : str = 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 __A ( self ): A__ : int = BasicTokenizer(do_lower_case=A__ ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def __A ( self ): A__ : Any = BasicTokenizer(do_lower_case=A__ , strip_accents=A__ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HäLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def __A ( self ): A__ : List[str] = BasicTokenizer(do_lower_case=A__ , strip_accents=A__ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HaLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def __A ( self ): A__ : Any = BasicTokenizer(do_lower_case=A__ , never_split=["""[UNK]"""] ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? [UNK]""" ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?""", """[UNK]"""] ) def __A ( self ): A__ : str = BasicTokenizer() A__ : Dict = """a\n\'ll !!to?\'d of, can\'t.""" A__ : Any = ["""a""", """\'""", """ll""", """!""", """!""", """to""", """?""", """\'""", """d""", """of""", """,""", """can""", """\'""", """t""", """."""] self.assertListEqual(tokenizer.tokenize(A__ ) , A__ ) def __A ( self ): A__ : Optional[Any] = ["""[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing"""] A__ : Optional[Any] = {} for i, token in enumerate(A__ ): A__ : Any = i A__ : int = 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 __A ( self ): 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 __A ( self ): 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 __A ( self ): 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 __A ( self ): A__ : List[Any] = self.get_tokenizer() A__ : List[str] = 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 __A ( self ): A__ : Optional[Any] = self.tokenizer_class.from_pretrained("""bert-base-uncased""" ) A__ : Union[str, Any] = tokenizer.encode("""sequence builders""" , add_special_tokens=A__ ) A__ : Any = tokenizer.encode("""multi-sequence build""" , add_special_tokens=A__ ) A__ : int = tokenizer.build_inputs_with_special_tokens(A__ ) A__ : List[Any] = tokenizer.build_inputs_with_special_tokens(A__ , A__ ) assert encoded_sentence == [101] + text + [102] assert encoded_pair == [101] + text + [102] + text_a + [102] def __A ( self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): A__ : Any = self.rust_tokenizer_class.from_pretrained(A__ , **A__ ) A__ : int = F"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence.""" A__ : Tuple = tokenizer_r.encode_plus( A__ , return_attention_mask=A__ , return_token_type_ids=A__ , return_offsets_mapping=A__ , add_special_tokens=A__ , ) A__ : Any = tokenizer_r.do_lower_case if hasattr(A__ , """do_lower_case""" ) else False A__ : Optional[int] = ( [ ((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 __A ( self ): A__ : List[Any] = ["""的""", """人""", """有"""] A__ : Optional[Any] = """""".join(A__ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): A__ : Dict = True A__ : str = self.tokenizer_class.from_pretrained(A__ , **A__ ) A__ : List[str] = self.rust_tokenizer_class.from_pretrained(A__ , **A__ ) A__ : List[str] = tokenizer_p.encode(A__ , add_special_tokens=A__ ) A__ : Optional[Any] = tokenizer_r.encode(A__ , add_special_tokens=A__ ) A__ : Optional[Any] = tokenizer_r.convert_ids_to_tokens(A__ ) A__ : Tuple = 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__ : Union[str, Any] = False A__ : Any = self.rust_tokenizer_class.from_pretrained(A__ , **A__ ) A__ : Union[str, Any] = self.tokenizer_class.from_pretrained(A__ , **A__ ) A__ : List[Any] = tokenizer_r.encode(A__ , add_special_tokens=A__ ) A__ : Optional[int] = tokenizer_p.encode(A__ , add_special_tokens=A__ ) A__ : Union[str, Any] = tokenizer_r.convert_ids_to_tokens(A__ ) A__ : Optional[Any] = tokenizer_p.convert_ids_to_tokens(A__ ) # it is expected that only the first Chinese character is not preceded by "##". A__ : str = [ F"""##{token}""" if idx != 0 else token for idx, token in enumerate(A__ ) ] self.assertListEqual(A__ , A__ ) self.assertListEqual(A__ , A__ )
701
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def UpperCamelCase (*lowercase_: Optional[int] , lowercase_: Optional[Union[Dict, Any]] = None , lowercase_: Dict=True , lowercase_: Tuple=2 ) -> Dict: from .. import __version__ A__ : Dict = take_from A__ : str = () if not isinstance(args[0] , lowercase_ ): A__ : int = (args,) for attribute, version_name, message in args: if version.parse(version.parse(lowercase_ ).base_version ) >= version.parse(lowercase_ ): raise ValueError( f"""The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers'""" f""" version {__version__} is >= {version_name}""" ) A__ : Any = None if isinstance(lowercase_ , lowercase_ ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(lowercase_ ),) A__ : List[str] = f"""The `{attribute}` argument is deprecated and will be removed in version {version_name}.""" elif hasattr(lowercase_ , lowercase_ ): values += (getattr(lowercase_ , lowercase_ ),) A__ : Optional[Any] = f"""The `{attribute}` attribute is deprecated and will be removed in version {version_name}.""" elif deprecated_kwargs is None: A__ : int = f"""`{attribute}` is deprecated and will be removed in version {version_name}.""" if warning is not None: A__ : int = warning + """ """ if standard_warn else """""" warnings.warn(warning + message , lowercase_ , stacklevel=lowercase_ ) if isinstance(lowercase_ , lowercase_ ) and len(lowercase_ ) > 0: A__ : Union[str, Any] = inspect.getouterframes(inspect.currentframe() )[1] A__ : Optional[Any] = call_frame.filename A__ : Optional[int] = call_frame.lineno A__ : Any = call_frame.function A__ , A__ : List[str] = next(iter(deprecated_kwargs.items() ) ) raise TypeError(f"""{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`""" ) if len(lowercase_ ) == 0: return elif len(lowercase_ ) == 1: return values[0] return values
64
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) A_ : Optional[Any] = { 'configuration_trocr': ['TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TrOCRConfig'], 'processing_trocr': ['TrOCRProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Any = [ 'TROCR_PRETRAINED_MODEL_ARCHIVE_LIST', 'TrOCRForCausalLM', 'TrOCRPreTrainedModel', ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys A_ : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
702
import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import ( rename_keys, ) from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME from transformers.utils.hub import convert_file_size_to_int def UpperCamelCase (lowercase_: List[str] , lowercase_: str ) -> Optional[Any]: if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer A__ : Union[str, Any] = flax_key_tuple[:-1] + ("""weight""",) A__ : Optional[int] = torch.permute(lowercase_ , (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(lowercase_ ): # linear layer A__ : Optional[Any] = flax_key_tuple[:-1] + ("""weight""",) A__ : int = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: A__ : Optional[int] = flax_key_tuple[:-1] + ("""weight""",) return flax_key_tuple, flax_tensor def UpperCamelCase (lowercase_: Tuple , lowercase_: Optional[int] , lowercase_: str ) -> Union[str, Any]: if "metadata" in layer: A__ : Tuple = layer.split("""metadata""" ) A__ : Optional[Any] = """""".join(split_layer[0] )[:-1] A__ : Optional[Any] = [tuple(("""metadata""" + split_layer[1]).split("""/""" ) )] elif "kvstore" in layer: A__ : str = layer.split("""kvstore""" ) A__ : int = """""".join(split_layer[0] )[:-1] A__ : Optional[int] = [tuple(("""kvstore""" + split_layer[1]).split("""/""" ) )] else: A__ : Any = layer.split("""/""" ) A__ : int = """/""".join(split_layer[:-1] ) A__ : str = (split_layer[-1],) if "kvstore/path" in layer: A__ : Dict = f"""{switch_checkpoint_path}/{checkpoint_info[layer]}""" elif "kvstore/driver" in layer: A__ : Optional[int] = """file""" else: A__ : str = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def UpperCamelCase (lowercase_: str , lowercase_: List[Any] ) -> int: A__ : int = rename_keys(lowercase_ ) A__ : Any = {} for k, v in current_block.items(): A__ : Dict = v A__ : str = new_current_block torch.save(lowercase_ , lowercase_ ) def UpperCamelCase (lowercase_: Dict , lowercase_: Optional[Any] , lowercase_: Optional[Any] , lowercase_: Optional[int] , lowercase_: str = WEIGHTS_NAME ) -> Tuple: A__ : Optional[int] = convert_file_size_to_int(lowercase_ ) A__ : List[Any] = [] A__ : int = {} A__ : List[str] = 0 A__ : Any = 0 os.makedirs(lowercase_ , exist_ok=lowercase_ ) with gfile.GFile(switch_checkpoint_path + """/checkpoint""" , """rb""" ) as fp: A__ : Optional[Any] = serialization.msgpack_restore(fp.read() )["""optimizer"""]["""target"""] A__ : Dict = flatten_dict(lowercase_ , sep="""/""" ) A__ : Any = {} for layer in checkpoint_info.keys(): A__ , A__ , A__ : Union[str, Any] = get_key_and_tensorstore_dict( lowercase_ , lowercase_ , lowercase_ ) if curr_real_layer_name in all_layers: A__ : Optional[int] = content else: A__ : List[Any] = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file A__ : Optional[Any] = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() A__ : List[Any] = torch.tensor(lowercase_ ) A__ : List[Any] = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts A__ , A__ : Any = rename_base_flax_keys(tuple(key.split("""/""" ) ) , lowercase_ ) A__ : Any = """/""".join(lowercase_ ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: A__ : List[Any] = os.path.join( lowercase_ , weights_name.replace(""".bin""" , f"""-{len(lowercase_ )+1:05d}-of-???.bin""" ) ) rename_and_save_block(lowercase_ , lowercase_ ) sharded_state_dicts.append(current_block.keys() ) del current_block A__ : Any = {} A__ : str = 0 A__ : List[str] = raw_weights.to(getattr(lowercase_ , lowercase_ ) ) current_block_size += weight_size total_size += weight_size # Add the last block A__ : Union[str, Any] = os.path.join(lowercase_ , weights_name.replace(""".bin""" , f"""-{len(lowercase_ )+1:05d}-of-???.bin""" ) ) rename_and_save_block(lowercase_ , lowercase_ ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(lowercase_ ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index A__ : str = {} A__ : Any = {} for idx, shard in enumerate(lowercase_ ): A__ : Any = weights_name.replace( """.bin""" , f"""-{idx+1:05d}-of-{len(lowercase_ ):05d}.bin""" ) # len(sharded_state_dicts):05d} A__ : Dict = os.path.join(lowercase_ , weights_name.replace(""".bin""" , f"""-{idx+1:05d}-of-???.bin""" ) ) os.rename(lowercase_ , os.path.join(lowercase_ , lowercase_ ) ) A__ : str = shard for key in shard: A__ : Any = shard_file # Add the metadata A__ : Tuple = {"""total_size""": total_size} A__ : Union[str, Any] = {"""metadata""": metadata, """weight_map""": weight_map} with open(os.path.join(lowercase_ , lowercase_ ) , """w""" , encoding="""utf-8""" ) as f: A__ : Dict = json.dumps(lowercase_ , indent=2 , sort_keys=lowercase_ ) + """\n""" f.write(lowercase_ ) return metadata, index if __name__ == "__main__": A_ : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--switch_t5x_checkpoint_path', default='/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600', type=str, required=False, help='Path to a directory containing a folder per layer. Follows the original Google format.', ) parser.add_argument('--max_shard_size', default='10GB', required=False, help='Max shard size') parser.add_argument('--dtype', default='bfloat16', type=str, required=False, help='dtype of the saved model') parser.add_argument( '--pytorch_dump_folder_path', default='/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted', type=str, required=False, help='Path to the output pytorch model.', ) A_ : Dict = parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def UpperCamelCase () -> int: from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer A__ : str = SwitchTransformersConfig.from_pretrained("""google/switch-base-8""" ) config.save_pretrained("""/home/arthur_huggingface_co/transformers/switch_converted""" ) A__ : str = SwitchTransformersForConditionalGeneration.from_pretrained( """/home/arthur_huggingface_co/transformers/switch_converted""" , device_map="""auto""" ) A__ : Tuple = TaTokenizer.from_pretrained("""t5-small""" ) A__ : Dict = """A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.""" A__ : Union[str, Any] = tokenizer(lowercase_ , return_tensors="""pt""" ).input_ids A__ : Tuple = model.generate(lowercase_ , decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
64
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A_ : Dict = {'configuration_timm_backbone': ['TimmBackboneConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Union[str, Any] = ['TimmBackbone'] if TYPE_CHECKING: from .configuration_timm_backbone import TimmBackboneConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timm_backbone import TimmBackbone else: import sys A_ : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
703
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available A_ : Optional[Any] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : str = ['BartphoTokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bartpho import BartphoTokenizer else: import sys A_ : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
64
0
from random import randint from tempfile import TemporaryFile import numpy as np def UpperCamelCase (lowercase_: List[Any] , lowercase_: Dict , lowercase_: Optional[int] ) -> List[str]: A__ : Union[str, Any] = 0 if start < end: A__ : Union[str, Any] = randint(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A__ : List[Any] = a[end] A__ : Dict = a[pivot] A__ : Any = temp A__ : Dict = _in_place_partition(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) count += _in_place_quick_sort(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , p - 1 ) count += _in_place_quick_sort(SCREAMING_SNAKE_CASE__ , p + 1 , SCREAMING_SNAKE_CASE__ ) return count def UpperCamelCase (lowercase_: int , lowercase_: List[Any] , lowercase_: Dict ) -> Optional[Any]: A__ : Tuple = 0 A__ : List[Any] = randint(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A__ : Dict = a[end] A__ : List[Any] = a[pivot] A__ : Optional[Any] = temp A__ : List[str] = start - 1 for index in range(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value A__ : Any = new_pivot_index + 1 A__ : Tuple = a[new_pivot_index] A__ : Optional[int] = a[index] A__ : Tuple = temp A__ : Union[str, Any] = a[new_pivot_index + 1] A__ : Union[str, Any] = a[end] A__ : Union[str, Any] = temp return new_pivot_index + 1, count A_ : Optional[int] = TemporaryFile() A_ : List[Any] = 100 # 1000 elements are to be sorted A_ , A_ : List[str] = 0, 1 # mean and standard deviation A_ : Tuple = np.random.normal(mu, sigma, p) np.save(outfile, X) print('The array is') print(X) outfile.seek(0) # using the same array A_ : Any = np.load(outfile) A_ : List[Any] = len(M) - 1 A_ : Tuple = _in_place_quick_sort(M, 0, r) print( 'No of Comparisons for 100 elements selected from a standard normal distribution' 'is :' ) print(z)
704
import argparse import hashlib import os import urllib import warnings import torch from torch import nn from tqdm import tqdm from transformers import WhisperConfig, WhisperForConditionalGeneration A_ : Dict = { 'tiny.en': 'https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt', 'tiny': 'https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt', 'base.en': 'https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt', 'base': 'https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt', 'small.en': 'https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt', 'small': 'https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt', 'medium.en': 'https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt', 'medium': 'https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt', 'large': 'https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt', 'large-v2': 'https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt', } def UpperCamelCase (lowercase_: Optional[Any] ) -> Optional[int]: A__ : List[Any] = ["""layers""", """blocks"""] for k in ignore_keys: state_dict.pop(lowercase_ , lowercase_ ) A_ : Any = { 'blocks': 'layers', 'mlp.0': 'fc1', 'mlp.2': 'fc2', 'mlp_ln': 'final_layer_norm', '.attn.query': '.self_attn.q_proj', '.attn.key': '.self_attn.k_proj', '.attn.value': '.self_attn.v_proj', '.attn_ln': '.self_attn_layer_norm', '.attn.out': '.self_attn.out_proj', '.cross_attn.query': '.encoder_attn.q_proj', '.cross_attn.key': '.encoder_attn.k_proj', '.cross_attn.value': '.encoder_attn.v_proj', '.cross_attn_ln': '.encoder_attn_layer_norm', '.cross_attn.out': '.encoder_attn.out_proj', 'decoder.ln.': 'decoder.layer_norm.', 'encoder.ln.': 'encoder.layer_norm.', 'token_embedding': 'embed_tokens', 'encoder.positional_embedding': 'encoder.embed_positions.weight', 'decoder.positional_embedding': 'decoder.embed_positions.weight', 'ln_post': 'layer_norm', } def UpperCamelCase (lowercase_: str ) -> Any: A__ : Dict = list(s_dict.keys() ) for key in keys: A__ : List[str] = key for k, v in WHISPER_MAPPING.items(): if k in key: A__ : List[Any] = new_key.replace(lowercase_ , lowercase_ ) print(f"""{key} -> {new_key}""" ) A__ : Tuple = s_dict.pop(lowercase_ ) return s_dict def UpperCamelCase (lowercase_: Tuple ) -> Optional[int]: A__ , A__ : Any = emb.weight.shape A__ : str = nn.Linear(lowercase_ , lowercase_ , bias=lowercase_ ) A__ : Union[str, Any] = emb.weight.data return lin_layer def UpperCamelCase (lowercase_: str , lowercase_: str ) -> bytes: os.makedirs(lowercase_ , exist_ok=lowercase_ ) A__ : Tuple = os.path.basename(lowercase_ ) A__ : int = url.split("""/""" )[-2] A__ : Dict = os.path.join(lowercase_ , lowercase_ ) if os.path.exists(lowercase_ ) and not os.path.isfile(lowercase_ ): raise RuntimeError(f"""{download_target} exists and is not a regular file""" ) if os.path.isfile(lowercase_ ): A__ : Optional[Any] = open(lowercase_ , """rb""" ).read() if hashlib.shaaaa(lowercase_ ).hexdigest() == expected_shaaaa: return model_bytes else: warnings.warn(f"""{download_target} exists, but the SHA256 checksum does not match; re-downloading the file""" ) with urllib.request.urlopen(lowercase_ ) as source, open(lowercase_ , """wb""" ) as output: with tqdm( total=int(source.info().get("""Content-Length""" ) ) , ncols=80 , unit="""iB""" , unit_scale=lowercase_ , unit_divisor=1024 ) as loop: while True: A__ : Any = source.read(8192 ) if not buffer: break output.write(lowercase_ ) loop.update(len(lowercase_ ) ) A__ : Dict = open(lowercase_ , """rb""" ).read() if hashlib.shaaaa(lowercase_ ).hexdigest() != expected_shaaaa: raise RuntimeError( """Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model.""" ) return model_bytes def UpperCamelCase (lowercase_: List[Any] , lowercase_: Tuple ) -> Optional[Any]: if ".pt" not in checkpoint_path: A__ : Tuple = _download(_MODELS[checkpoint_path] ) else: A__ : Optional[int] = torch.load(lowercase_ , map_location="""cpu""" ) A__ : str = original_checkpoint["""dims"""] A__ : List[Any] = original_checkpoint["""model_state_dict"""] A__ : Optional[Any] = state_dict["""decoder.token_embedding.weight"""] remove_ignore_keys_(lowercase_ ) rename_keys(lowercase_ ) A__ : List[str] = True A__ : Optional[Any] = state_dict["""decoder.layers.0.fc1.weight"""].shape[0] A__ : List[Any] = WhisperConfig( vocab_size=dimensions["""n_vocab"""] , encoder_ffn_dim=lowercase_ , decoder_ffn_dim=lowercase_ , num_mel_bins=dimensions["""n_mels"""] , d_model=dimensions["""n_audio_state"""] , max_target_positions=dimensions["""n_text_ctx"""] , encoder_layers=dimensions["""n_audio_layer"""] , encoder_attention_heads=dimensions["""n_audio_head"""] , decoder_layers=dimensions["""n_text_layer"""] , decoder_attention_heads=dimensions["""n_text_state"""] , max_source_positions=dimensions["""n_audio_ctx"""] , ) A__ : Optional[Any] = WhisperForConditionalGeneration(lowercase_ ) A__ , A__ : List[Any] = model.model.load_state_dict(lowercase_ , strict=lowercase_ ) if len(lowercase_ ) > 0 and not set(lowercase_ ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( """Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,""" f""" but all the following weights are missing {missing}""" ) if tie_embeds: A__ : Any = make_linear_from_emb(model.model.decoder.embed_tokens ) else: A__ : str = proj_out_weights model.save_pretrained(lowercase_ ) if __name__ == "__main__": A_ : Any = argparse.ArgumentParser() # # Required parameters parser.add_argument('--checkpoint_path', type=str, help='Patht to the downloaded checkpoints') parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') A_ : Tuple = parser.parse_args() convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)
64
0
from __future__ import annotations class _a : '''simple docstring''' def __init__( self , A__ ): A__ : Tuple = order # a_{0} ... a_{k} A__ : Dict = [1.0] + [0.0] * order # b_{0} ... b_{k} A__ : Optional[int] = [1.0] + [0.0] * order # x[n-1] ... x[n-k] A__ : Union[str, Any] = [0.0] * self.order # y[n-1] ... y[n-k] A__ : Any = [0.0] * self.order def __A ( self , A__ , A__ ): if len(__snake_case ) < self.order: A__ : int = [1.0, *a_coeffs] if len(__snake_case ) != self.order + 1: A__ : str = ( F"""Expected a_coeffs to have {self.order + 1} elements """ F"""for {self.order}-order filter, got {len(__snake_case )}""" ) raise ValueError(__snake_case ) if len(__snake_case ) != self.order + 1: A__ : str = ( F"""Expected b_coeffs to have {self.order + 1} elements """ F"""for {self.order}-order filter, got {len(__snake_case )}""" ) raise ValueError(__snake_case ) A__ : Optional[int] = a_coeffs A__ : Tuple = b_coeffs def __A ( self , A__ ): A__ : int = 0.0 # Start at index 1 and do index 0 at the end. for i in range(1 , self.order + 1 ): result += ( self.b_coeffs[i] * self.input_history[i - 1] - self.a_coeffs[i] * self.output_history[i - 1] ) A__ : Union[str, Any] = (result + self.b_coeffs[0] * sample) / self.a_coeffs[0] A__ : Optional[Any] = self.input_history[:-1] A__ : Union[str, Any] = self.output_history[:-1] A__ : int = sample A__ : int = result return result
705
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DPMSolverMultistepScheduler, TextToVideoSDPipeline, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class _a (__magic_name__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: Any = TextToVideoSDPipeline UpperCAmelCase__: Any = TEXT_TO_IMAGE_PARAMS UpperCAmelCase__: Optional[Any] = TEXT_TO_IMAGE_BATCH_PARAMS # No `output_type`. UpperCAmelCase__: Optional[int] = frozenset( [ '''num_inference_steps''', '''generator''', '''latents''', '''return_dict''', '''callback''', '''callback_steps''', ] ) def __A ( self ): torch.manual_seed(0 ) A__ : Optional[int] = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """DownBlock3D""") , up_block_types=("""UpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""") , cross_attention_dim=32 , attention_head_dim=4 , ) A__ : Optional[int] = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule="""scaled_linear""" , clip_sample=A__ , set_alpha_to_one=A__ , ) torch.manual_seed(0 ) A__ : Union[str, Any] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) A__ : Union[str, Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act="""gelu""" , projection_dim=512 , ) A__ : Union[str, Any] = CLIPTextModel(A__ ) A__ : Tuple = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) A__ : Dict = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, } return components def __A ( self , A__ , A__=0 ): if str(A__ ).startswith("""mps""" ): A__ : Tuple = torch.manual_seed(A__ ) else: A__ : List[str] = torch.Generator(device=A__ ).manual_seed(A__ ) A__ : List[str] = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """pt""", } return inputs def __A ( self ): A__ : List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator A__ : Union[str, Any] = self.get_dummy_components() A__ : Union[str, Any] = TextToVideoSDPipeline(**A__ ) A__ : int = sd_pipe.to(A__ ) sd_pipe.set_progress_bar_config(disable=A__ ) A__ : int = self.get_dummy_inputs(A__ ) A__ : int = """np""" A__ : Any = sd_pipe(**A__ ).frames A__ : Dict = frames[0][-3:, -3:, -1] assert frames[0].shape == (64, 64, 3) A__ : Optional[Any] = np.array([1_5_8.0, 1_6_0.0, 1_5_3.0, 1_2_5.0, 1_0_0.0, 1_2_1.0, 1_1_1.0, 9_3.0, 1_1_3.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __A ( self ): self._test_attention_slicing_forward_pass(test_mean_pixel_difference=A__ , expected_max_diff=3e-3 ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def __A ( self ): self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=A__ , expected_max_diff=1e-2 ) @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def __A ( self ): pass @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def __A ( self ): pass @unittest.skip(reason="""`num_images_per_prompt` argument is not supported for this pipeline.""" ) def __A ( self ): pass def __A ( self ): return super().test_progress_bar() @slow @skip_mps class _a (unittest.TestCase ): '''simple docstring''' def __A ( self ): A__ : Union[str, Any] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy""" ) A__ : Tuple = TextToVideoSDPipeline.from_pretrained("""damo-vilab/text-to-video-ms-1.7b""" ) A__ : Any = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) A__ : int = pipe.to("""cuda""" ) A__ : Optional[Any] = """Spiderman is surfing""" A__ : List[str] = torch.Generator(device="""cpu""" ).manual_seed(0 ) A__ : Optional[Any] = pipe(A__ , generator=A__ , num_inference_steps=25 , output_type="""pt""" ).frames A__ : Dict = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5e-2 def __A ( self ): A__ : List[Any] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy""" ) A__ : Optional[int] = TextToVideoSDPipeline.from_pretrained("""damo-vilab/text-to-video-ms-1.7b""" ) A__ : List[str] = pipe.to("""cuda""" ) A__ : Dict = """Spiderman is surfing""" A__ : Union[str, Any] = torch.Generator(device="""cpu""" ).manual_seed(0 ) A__ : Optional[int] = pipe(A__ , generator=A__ , num_inference_steps=2 , output_type="""pt""" ).frames A__ : Optional[int] = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5e-2
64
0
from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo A_ : List[str] = """\ @misc{wu2016googles, title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation}, author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes and Jeffrey Dean}, year={2016}, eprint={1609.08144}, archivePrefix={arXiv}, primaryClass={cs.CL} } """ A_ : Optional[Any] = """\ The BLEU score has some undesirable properties when used for single sentences, as it was designed to be a corpus measure. We therefore use a slightly different score for our RL experiments which we call the 'GLEU score'. For the GLEU score, we record all sub-sequences of 1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then compute a recall, which is the ratio of the number of matching n-grams to the number of total n-grams in the target (ground truth) sequence, and a precision, which is the ratio of the number of matching n-grams to the number of total n-grams in the generated output sequence. Then GLEU score is simply the minimum of recall and precision. This GLEU score's range is always between 0 (no matches) and 1 (all match) and it is symmetrical when switching output and target. According to our experiments, GLEU score correlates quite well with the BLEU metric on a corpus level but does not have its drawbacks for our per sentence reward objective. """ A_ : Any = """\ Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references. Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values. Args: predictions (list of str): list of translations to score. Each translation should be tokenized into a list of tokens. references (list of list of str): list of lists of references for each translation. Each reference should be tokenized into a list of tokens. min_len (int): The minimum order of n-gram this function should extract. Defaults to 1. max_len (int): The maximum order of n-gram this function should extract. Defaults to 4. Returns: 'google_bleu': google_bleu score Examples: Example 1: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.44 Example 2: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.61 Example 3: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2) >>> print(round(results[\"google_bleu\"], 2)) 0.53 Example 4: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6) >>> print(round(results[\"google_bleu\"], 2)) 0.4 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _a (datasets.Metric ): '''simple docstring''' def __A ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Sequence(datasets.Value("""string""" , id="""token""" ) , id="""sequence""" ), """references""": datasets.Sequence( datasets.Sequence(datasets.Value("""string""" , id="""token""" ) , id="""sequence""" ) , id="""references""" ), } ) , ) def __A ( self , A__ , A__ , A__ = 1 , A__ = 4 , ): return { "google_bleu": gleu_score.corpus_gleu( list_of_references=A__ , hypotheses=A__ , min_len=A__ , max_len=A__ ) }
706
def UpperCamelCase (lowercase_: int ) -> int: if not isinstance(lowercase_ , lowercase_ ): raise TypeError("""Input value must be an 'int' type""" ) A__ : int = 0 while number: position += 1 number >>= 1 return position if __name__ == "__main__": import doctest doctest.testmod()
64
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) A_ : str = { 'configuration_albert': ['ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'AlbertConfig', 'AlbertOnnxConfig'], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : List[Any] = ['AlbertTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : int = ['AlbertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Union[str, Any] = [ 'ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'AlbertForMaskedLM', 'AlbertForMultipleChoice', 'AlbertForPreTraining', 'AlbertForQuestionAnswering', 'AlbertForSequenceClassification', 'AlbertForTokenClassification', 'AlbertModel', 'AlbertPreTrainedModel', 'load_tf_weights_in_albert', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Union[str, Any] = [ 'TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFAlbertForMaskedLM', 'TFAlbertForMultipleChoice', 'TFAlbertForPreTraining', 'TFAlbertForQuestionAnswering', 'TFAlbertForSequenceClassification', 'TFAlbertForTokenClassification', 'TFAlbertMainLayer', 'TFAlbertModel', 'TFAlbertPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Dict = [ 'FlaxAlbertForMaskedLM', 'FlaxAlbertForMultipleChoice', 'FlaxAlbertForPreTraining', 'FlaxAlbertForQuestionAnswering', 'FlaxAlbertForSequenceClassification', 'FlaxAlbertForTokenClassification', 'FlaxAlbertModel', 'FlaxAlbertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_albert import ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, AlbertOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_albert import AlbertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_albert_fast import AlbertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_albert import ( ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForPreTraining, AlbertForQuestionAnswering, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertModel, AlbertPreTrainedModel, load_tf_weights_in_albert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_albert import ( TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFAlbertForMaskedLM, TFAlbertForMultipleChoice, TFAlbertForPreTraining, TFAlbertForQuestionAnswering, TFAlbertForSequenceClassification, TFAlbertForTokenClassification, TFAlbertMainLayer, TFAlbertModel, TFAlbertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_albert import ( FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForPreTraining, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertModel, FlaxAlbertPreTrainedModel, ) else: import sys A_ : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
707
from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def UpperCamelCase (lowercase_: np.ndarray , lowercase_: np.ndarray , lowercase_: np.ndarray , lowercase_: int , lowercase_: int ) -> np.ndarray: A__ : Any = cva.getAffineTransform(lowercase_ , lowercase_ ) return cva.warpAffine(lowercase_ , lowercase_ , (rows, cols) ) if __name__ == "__main__": # read original image A_ : List[Any] = cva.imread( str(Path(__file__).resolve().parent.parent / 'image_data' / 'lena.jpg') ) # turn image in gray scale value A_ : List[Any] = cva.cvtColor(image, cva.COLOR_BGR2GRAY) # get image shape A_ , A_ : Optional[Any] = gray_img.shape # set different points to rotate image A_ : str = np.array([[50, 50], [200, 50], [50, 200]], np.floataa) A_ : Dict = np.array([[10, 100], [200, 50], [100, 250]], np.floataa) A_ : Optional[int] = np.array([[50, 50], [150, 50], [120, 200]], np.floataa) A_ : Optional[int] = np.array([[10, 100], [80, 50], [180, 250]], np.floataa) # add all rotated images in a list A_ : Dict = [ 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_ : Union[str, Any] = plt.figure(1) A_ : Union[str, Any] = ['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()
64
0
import os import re import shutil import sys import tempfile import unittest import black A_ = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, 'utils')) import check_copies # noqa: E402 # This is the reference code that will be used in the tests. # If BertLMPredictionHead is changed in modeling_bert.py, this code needs to be manually updated. A_ = ' def __init__(self, config):\n super().__init__()\n self.transform = BertPredictionHeadTransform(config)\n\n # The output weights are the same as the input embeddings, but there is\n # an output-only bias for each token.\n self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)\n\n self.bias = nn.Parameter(torch.zeros(config.vocab_size))\n\n # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`\n self.decoder.bias = self.bias\n\n def forward(self, hidden_states):\n hidden_states = self.transform(hidden_states)\n hidden_states = self.decoder(hidden_states)\n return hidden_states\n' class _a (unittest.TestCase ): '''simple docstring''' def __A ( self ): A__ : List[Any] = tempfile.mkdtemp() os.makedirs(os.path.join(self.transformer_dir , """models/bert/""" ) ) A__ : int = self.transformer_dir shutil.copy( os.path.join(_snake_case , """src/transformers/models/bert/modeling_bert.py""" ) , os.path.join(self.transformer_dir , """models/bert/modeling_bert.py""" ) , ) def __A ( self ): A__ : Optional[Any] = """src/transformers""" shutil.rmtree(self.transformer_dir ) def __A ( self , A__ , A__ , A__ , A__=None ): A__ : str = comment + F"""\nclass {class_name}(nn.Module):\n""" + class_code if overwrite_result is not None: A__ : str = comment + F"""\nclass {class_name}(nn.Module):\n""" + overwrite_result A__ : Optional[int] = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 ) A__ : Any = black.format_str(_snake_case , mode=_snake_case ) A__ : Union[str, Any] = os.path.join(self.transformer_dir , """new_code.py""" ) with open(_snake_case , """w""" , newline="""\n""" ) as f: f.write(_snake_case ) if overwrite_result is None: self.assertTrue(len(check_copies.is_copy_consistent(_snake_case ) ) == 0 ) else: check_copies.is_copy_consistent(f.name , overwrite=_snake_case ) with open(_snake_case , """r""" ) as f: self.assertTrue(f.read() , _snake_case ) def __A ( self ): A__ : Tuple = check_copies.find_code_in_transformers("""models.bert.modeling_bert.BertLMPredictionHead""" ) self.assertEqual(_snake_case , _snake_case ) def __A ( self ): self.check_copy_consistency( """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead""" , """BertLMPredictionHead""" , REFERENCE_CODE + """\n""" , ) # With no empty line at the end self.check_copy_consistency( """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead""" , """BertLMPredictionHead""" , _snake_case , ) # Copy consistency with rename self.check_copy_consistency( """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel""" , """TestModelLMPredictionHead""" , re.sub("""Bert""" , """TestModel""" , _snake_case ) , ) # Copy consistency with a really long name A__ : Dict = """TestModelWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason""" self.check_copy_consistency( F"""# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->{long_class_name}""" , F"""{long_class_name}LMPredictionHead""" , re.sub("""Bert""" , _snake_case , _snake_case ) , ) # Copy consistency with overwrite self.check_copy_consistency( """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel""" , """TestModelLMPredictionHead""" , _snake_case , overwrite_result=re.sub("""Bert""" , """TestModel""" , _snake_case ) , ) def __A ( self ): A__ : Optional[int] = check_copies.LOCALIZED_READMES["""README_zh-hans.md"""] A__ : Tuple = ( """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the""" """ Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for""" """ Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong""" """ Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.\n1.""" """ **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (from HuggingFace),""" """ released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and""" """ lighter](https://arxiv.org/abs/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same""" """ method has been applied to compress GPT2 into""" """ [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into""" """ [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),""" """ Multilingual BERT into""" """ [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German""" """ version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)**""" """ (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders""" """ as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang""" """ Luong, Quoc V. Le, Christopher D. Manning.""" ) A__ : int = ( """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the""" """ Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of""" """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian""" """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n""" ) A__ : Union[str, Any] = ( """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the""" """ Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of""" """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian""" """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n1.""" """ **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (来自 HuggingFace) 伴随论文""" """ [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and""" """ lighter](https://arxiv.org/abs/1910.01108) 由 Victor Sanh, Lysandre Debut and Thomas Wolf 发布。 The same""" """ method has been applied to compress GPT2 into""" """ [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into""" """ [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),""" """ Multilingual BERT into""" """ [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German""" """ version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)** (来自""" """ Google Research/Stanford University) 伴随论文 [ELECTRA: Pre-training text encoders as discriminators rather""" """ than generators](https://arxiv.org/abs/2003.10555) 由 Kevin Clark, Minh-Thang Luong, Quoc V. Le,""" """ Christopher D. Manning 发布。\n""" ) A__ , A__ : List[str] = check_copies.convert_to_localized_md( _snake_case , _snake_case , localized_readme["""format_model_list"""] ) self.assertFalse(_snake_case ) self.assertEqual(_snake_case , _snake_case ) A__ , A__ : str = check_copies.convert_to_localized_md( _snake_case , _snake_case , localized_readme["""format_model_list"""] ) # Check whether the number of models is equal to README.md after conversion. self.assertTrue(_snake_case ) A__ : Optional[int] = ( """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the""" """ Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for""" """ Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong""" """ Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.""" ) A__ : List[str] = ( """1. **[ALBERT](https://huggingface.co/transformers/main/model_doc/albert.html)** (来自 Google Research and""" """ the Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of""" """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian""" """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n""" ) A__ : Union[str, Any] = ( """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the""" """ Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of""" """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian""" """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n""" ) A__ , A__ : Dict = check_copies.convert_to_localized_md( _snake_case , _snake_case , localized_readme["""format_model_list"""] ) # Check if the model link is synchronized. self.assertEqual(_snake_case , _snake_case )
708
import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class _a (unittest.TestCase ): '''simple docstring''' def __A ( self , A__ ): for model_result in results.values(): for batch_size, sequence_length in zip(model_result["""bs"""] , model_result["""ss"""] ): A__ : str = model_result["""result"""][batch_size][sequence_length] self.assertIsNotNone(A__ ) def __A ( self ): A__ : Dict = """sshleifer/tiny-gpt2""" A__ : Tuple = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : int = PyTorchBenchmark(A__ ) A__ : List[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ): A__ : Dict = """sgugger/tiny-distilbert-classification""" A__ : Dict = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , only_pretrain_model=A__ , ) A__ : str = PyTorchBenchmark(A__ ) A__ : List[str] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ): A__ : Any = """sshleifer/tiny-gpt2""" A__ : List[Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , torchscript=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : Tuple = PyTorchBenchmark(A__ ) A__ : str = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == """cpu""" , """Cant do half precision""" ) def __A ( self ): A__ : Optional[Any] = """sshleifer/tiny-gpt2""" A__ : Optional[Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , fpaa=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : str = PyTorchBenchmark(A__ ) A__ : Any = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ): A__ : Optional[Any] = """sshleifer/tiny-gpt2""" A__ : Tuple = AutoConfig.from_pretrained(A__ ) # set architectures equal to `None` A__ : List[Any] = None A__ : str = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : List[str] = PyTorchBenchmark(A__ , configs=[config] ) A__ : Any = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ): A__ : Optional[int] = """sshleifer/tiny-gpt2""" A__ : Optional[int] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : Any = PyTorchBenchmark(A__ ) A__ : Dict = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == """cpu""" , """Can't do half precision""" ) def __A ( self ): A__ : Optional[int] = """sshleifer/tiny-gpt2""" A__ : List[str] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , fpaa=A__ , multi_process=A__ , ) A__ : Dict = PyTorchBenchmark(A__ ) A__ : Optional[int] = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __A ( self ): A__ : int = """sshleifer/tiny-gpt2""" A__ : Optional[int] = AutoConfig.from_pretrained(A__ ) A__ : str = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : int = PyTorchBenchmark(A__ , configs=[config] ) A__ : Tuple = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ): A__ : List[str] = """sshleifer/tinier_bart""" A__ : List[str] = AutoConfig.from_pretrained(A__ ) A__ : List[str] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : Union[str, Any] = PyTorchBenchmark(A__ , configs=[config] ) A__ : str = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ): A__ : Optional[int] = """sshleifer/tiny-gpt2""" A__ : Union[str, Any] = AutoConfig.from_pretrained(A__ ) A__ : Tuple = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : int = PyTorchBenchmark(A__ , configs=[config] ) A__ : Tuple = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __A ( self ): A__ : Dict = """sshleifer/tinier_bart""" A__ : int = AutoConfig.from_pretrained(A__ ) A__ : Union[str, Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : List[Any] = PyTorchBenchmark(A__ , configs=[config] ) A__ : Optional[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __A ( self ): A__ : int = """sshleifer/tiny-gpt2""" with tempfile.TemporaryDirectory() as tmp_dir: A__ : Dict = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , save_to_csv=A__ , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(A__ , """inf_time.csv""" ) , train_memory_csv_file=os.path.join(A__ , """train_mem.csv""" ) , inference_memory_csv_file=os.path.join(A__ , """inf_mem.csv""" ) , train_time_csv_file=os.path.join(A__ , """train_time.csv""" ) , env_info_csv_file=os.path.join(A__ , """env.csv""" ) , multi_process=A__ , ) A__ : Optional[Any] = PyTorchBenchmark(A__ ) benchmark.run() self.assertTrue(Path(os.path.join(A__ , """inf_time.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(A__ , """train_time.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(A__ , """inf_mem.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(A__ , """train_mem.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(A__ , """env.csv""" ) ).exists() ) def __A ( self ): A__ : Optional[int] = """sshleifer/tiny-gpt2""" def _check_summary_is_not_empty(A__ ): self.assertTrue(hasattr(A__ , """sequential""" ) ) self.assertTrue(hasattr(A__ , """cumulative""" ) ) self.assertTrue(hasattr(A__ , """current""" ) ) self.assertTrue(hasattr(A__ , """total""" ) ) with tempfile.TemporaryDirectory() as tmp_dir: A__ : Dict = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(A__ , """log.txt""" ) , log_print=A__ , trace_memory_line_by_line=A__ , multi_process=A__ , ) A__ : Dict = PyTorchBenchmark(A__ ) A__ : str = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(A__ , """log.txt""" ) ).exists() )
64
0
from functools import lru_cache def UpperCamelCase (lowercase_: Dict ) -> Tuple: A__ : Union[str, Any] = 2 A__ : Union[str, Any] = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(lowercase_ ) if n > 1: factors.add(lowercase_ ) return factors @lru_cache def UpperCamelCase (lowercase_: Tuple ) -> List[Any]: return len(unique_prime_factors(lowercase_ ) ) def UpperCamelCase (lowercase_: Union[str, Any] ) -> Optional[Any]: return len(set(lowercase_ ) ) in (0, 1) def UpperCamelCase (lowercase_: int ) -> int: A__ : Dict = 2 while True: # Increment each value of a generated range A__ : List[Any] = [base + i for i in range(lowercase_ )] # Run elements through out unique_prime_factors function # Append our target number to the end. A__ : int = [upf_len(lowercase_ ) for x in group] checker.append(lowercase_ ) # If all numbers in the list are equal, return the group variable. if equality(lowercase_ ): return group # Increment our base variable by 1 base += 1 def UpperCamelCase (lowercase_: Optional[Any] = 4 ) -> Optional[Any]: A__ : Dict = run(lowercase_ ) return results[0] if len(lowercase_ ) else None if __name__ == "__main__": print(solution())
709
# tests directory-specific settings - this file is run automatically # by pytest before any tests are run import doctest import sys import warnings from os.path import abspath, dirname, join import _pytest from transformers.testing_utils import HfDoctestModule, HfDocTestParser # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. A_ : Optional[int] = abspath(join(dirname(__file__), 'src')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='ignore', category=FutureWarning) def UpperCamelCase (lowercase_: List[str] ) -> Any: config.addinivalue_line( """markers""" , """is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested""" ) config.addinivalue_line( """markers""" , """is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested""" ) config.addinivalue_line("""markers""" , """is_pipeline_test: mark test to run only when pipelines are tested""" ) config.addinivalue_line("""markers""" , """is_staging_test: mark test to run only in the staging environment""" ) config.addinivalue_line("""markers""" , """accelerate_tests: mark test that require accelerate""" ) config.addinivalue_line("""markers""" , """tool_tests: mark the tool tests that are run on their specific schedule""" ) def UpperCamelCase (lowercase_: Optional[int] ) -> Optional[Any]: from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(lowercase_ ) def UpperCamelCase (lowercase_: List[str] ) -> Optional[Any]: from transformers.testing_utils import pytest_terminal_summary_main A__ : List[Any] = terminalreporter.config.getoption("""--make-reports""" ) if make_reports: pytest_terminal_summary_main(lowercase_ , id=lowercase_ ) def UpperCamelCase (lowercase_: Union[str, Any] , lowercase_: int ) -> List[str]: # If no tests are collected, pytest exists with code 5, which makes the CI fail. if exitstatus == 5: A__ : Tuple = 0 # Doctest custom flag to ignore output. A_ : Tuple = doctest.register_optionflag('IGNORE_RESULT') A_ : Dict = doctest.OutputChecker class _a (__magic_name__ ): '''simple docstring''' def __A ( self , A__ , A__ , A__ ): if IGNORE_RESULT & optionflags: return True return OutputChecker.check_output(self , A__ , A__ , A__ ) A_ : str = CustomOutputChecker A_ : Dict = HfDoctestModule A_ : Optional[int] = HfDocTestParser
64
0
def UpperCamelCase (lowercase_: Optional[int] = 200 ) -> str: A__ : Optional[Any] = [1, 2, 5, 10, 20, 50, 100, 200] A__ : List[str] = [0] * (pence + 1) A__ : int = 1 # base case: 1 way to make 0 pence for coin in coins: for i in range(snake_case_ , pence + 1 , 1 ): number_of_ways[i] += number_of_ways[i - coin] return number_of_ways[pence] if __name__ == "__main__": assert solution(200) == 7_3682
710
from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, 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, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class _a : '''simple docstring''' UpperCAmelCase__: List[Any] = PegasusConfig UpperCAmelCase__: Optional[int] = {} UpperCAmelCase__: List[str] = '''gelu''' def __init__( self , A__ , A__=13 , A__=7 , A__=True , A__=False , A__=99 , A__=32 , A__=2 , A__=4 , A__=37 , A__=0.1 , A__=0.1 , A__=40 , A__=2 , A__=1 , A__=0 , ): A__ : Dict = parent A__ : Dict = batch_size A__ : Any = seq_length A__ : Optional[Any] = is_training A__ : int = use_labels A__ : Any = vocab_size A__ : Union[str, Any] = hidden_size A__ : Tuple = num_hidden_layers A__ : Tuple = num_attention_heads A__ : List[Any] = intermediate_size A__ : Union[str, Any] = hidden_dropout_prob A__ : Optional[Any] = attention_probs_dropout_prob A__ : List[Any] = max_position_embeddings A__ : Any = eos_token_id A__ : List[Any] = pad_token_id A__ : List[Any] = bos_token_id def __A ( self ): A__ : str = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) A__ : Dict = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) A__ : List[Any] = tf.concat([input_ids, eos_tensor] , axis=1 ) A__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ : Tuple = 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 , ) A__ : str = prepare_pegasus_inputs_dict(A__ , A__ , A__ ) return config, inputs_dict def __A ( self , A__ , A__ ): A__ : int = TFPegasusModel(config=A__ ).get_decoder() A__ : List[Any] = inputs_dict["""input_ids"""] A__ : Any = input_ids[:1, :] A__ : Optional[Any] = inputs_dict["""attention_mask"""][:1, :] A__ : Optional[int] = inputs_dict["""head_mask"""] A__ : Any = 1 # first forward pass A__ : Tuple = model(A__ , attention_mask=A__ , head_mask=A__ , use_cache=A__ ) A__ , A__ : Dict = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids A__ : Tuple = ids_tensor((self.batch_size, 3) , config.vocab_size ) A__ : Optional[Any] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and A__ : List[Any] = tf.concat([input_ids, next_tokens] , axis=-1 ) A__ : Tuple = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) A__ : Optional[Any] = model(A__ , attention_mask=A__ )[0] A__ : Any = model(A__ , attention_mask=A__ , past_key_values=A__ )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice A__ : int = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) A__ : Any = output_from_no_past[:, -3:, random_slice_idx] A__ : Tuple = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(A__ , A__ , rtol=1e-3 ) def UpperCamelCase (lowercase_: Union[str, Any] , lowercase_: Dict , lowercase_: List[Any] , lowercase_: Dict=None , lowercase_: int=None , lowercase_: List[Any]=None , lowercase_: List[Any]=None , lowercase_: str=None , ) -> int: if attention_mask is None: A__ : List[str] = tf.cast(tf.math.not_equal(lowercase_ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: A__ : Dict = 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: A__ : Any = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: A__ : Tuple = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: A__ : List[str] = 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 (__magic_name__ , __magic_name__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: List[Any] = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () UpperCAmelCase__: Tuple = (TFPegasusForConditionalGeneration,) if is_tf_available() else () UpperCAmelCase__: Tuple = ( { '''conversational''': TFPegasusForConditionalGeneration, '''feature-extraction''': TFPegasusModel, '''summarization''': TFPegasusForConditionalGeneration, '''text2text-generation''': TFPegasusForConditionalGeneration, '''translation''': TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) UpperCAmelCase__: int = True UpperCAmelCase__: Union[str, Any] = False UpperCAmelCase__: List[str] = False def __A ( self ): A__ : Optional[Any] = TFPegasusModelTester(self ) A__ : Tuple = ConfigTester(self , config_class=A__ ) def __A ( self ): self.config_tester.run_common_tests() def __A ( self ): A__ : int = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*A__ ) @require_sentencepiece @require_tokenizers @require_tf class _a (unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: Optional[int] = [ ''' 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!" ''', ] UpperCAmelCase__: Any = [ '''California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to''' ''' reduce the risk of wildfires.''', '''N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.''', ] # differs slightly from pytorch, likely due to numerical differences in linear layers UpperCAmelCase__: List[str] = '''google/pegasus-xsum''' @cached_property def __A ( self ): return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def __A ( self ): A__ : int = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def __A ( self , **A__ ): A__ : str = self.translate_src_text(**A__ ) assert self.expected_text == generated_words def __A ( self , **A__ ): A__ : List[str] = self.tokenizer(self.src_text , **A__ , padding=A__ , return_tensors="""tf""" ) A__ : Optional[int] = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=A__ , ) A__ : Dict = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=A__ ) return generated_words @slow def __A ( self ): self._assert_generated_batch_equal_expected()
64
0
import os from typing import Dict, List, Tuple, TypeVar, Union A_ : List[str] = TypeVar('T') A_ : int = Union[List[T], Tuple[T, ...]] A_ : Any = Union[T, List[T], Dict[str, T]] A_ : int = Union[str, bytes, os.PathLike]
711
class _a : '''simple docstring''' def __init__( self ): A__ : str = """""" A__ : Any = """""" A__ : List[Any] = [] def __A ( self , A__ , A__ ): if m == -1: return n + 1 elif n == -1: return m + 1 elif self.dp[m][n] > -1: return self.dp[m][n] else: if self.worda[m] == self.worda[n]: A__ : Optional[Any] = self.__min_dist_top_down_dp(m - 1 , n - 1 ) else: A__ : Union[str, Any] = self.__min_dist_top_down_dp(A__ , n - 1 ) A__ : Union[str, Any] = self.__min_dist_top_down_dp(m - 1 , A__ ) A__ : Union[str, Any] = self.__min_dist_top_down_dp(m - 1 , n - 1 ) A__ : List[Any] = 1 + min(A__ , A__ , A__ ) return self.dp[m][n] def __A ( self , A__ , A__ ): A__ : Tuple = worda A__ : Dict = worda A__ : Optional[Any] = [[-1 for _ in range(len(A__ ) )] for _ in range(len(A__ ) )] return self.__min_dist_top_down_dp(len(A__ ) - 1 , len(A__ ) - 1 ) def __A ( self , A__ , A__ ): A__ : Optional[Any] = worda A__ : Dict = worda A__ : Union[str, Any] = len(A__ ) A__ : List[str] = len(A__ ) A__ : int = [[0 for _ in range(n + 1 )] for _ in range(m + 1 )] for i in range(m + 1 ): for j in range(n + 1 ): if i == 0: # first string is empty A__ : Tuple = j elif j == 0: # second string is empty A__ : Dict = i elif worda[i - 1] == worda[j - 1]: # last characters are equal A__ : str = self.dp[i - 1][j - 1] else: A__ : Union[str, Any] = self.dp[i][j - 1] A__ : str = self.dp[i - 1][j] A__ : Union[str, Any] = self.dp[i - 1][j - 1] A__ : Tuple = 1 + min(A__ , A__ , A__ ) return self.dp[m][n] if __name__ == "__main__": A_ : Union[str, Any] = EditDistance() print('****************** Testing Edit Distance DP Algorithm ******************') print() A_ : int = input('Enter the first string: ').strip() A_ : List[str] = input('Enter the second string: ').strip() print() print(f'''The minimum edit distance is: {solver.min_dist_top_down(Sa, Sa)}''') print(f'''The minimum edit distance is: {solver.min_dist_bottom_up(Sa, Sa)}''') print() print('*************** End of Testing Edit Distance DP Algorithm ***************')
64
0
def UpperCamelCase (lowercase_: str , lowercase_: str ) -> Union[str, Any]: def get_matched_characters(lowercase_: str , lowercase_: str ) -> str: A__ : Any = [] A__ : Union[str, Any] = min(len(_stra ) , len(_stra ) ) // 2 for i, l in enumerate(_stra ): A__ : Optional[Any] = int(max(0 , i - limit ) ) A__ : Optional[Any] = int(min(i + limit + 1 , len(_stra ) ) ) if l in _stra[left:right]: matched.append(lowerCamelCase_ ) A__ : List[Any] = f"""{_stra[0:_stra.index(lowerCamelCase_ )]} {_stra[_stra.index(lowerCamelCase_ ) + 1:]}""" return "".join(lowerCamelCase_ ) # matching characters A__ : Optional[int] = get_matched_characters(lowerCamelCase_ , lowerCamelCase_ ) A__ : int = get_matched_characters(lowerCamelCase_ , lowerCamelCase_ ) A__ : str = len(lowerCamelCase_ ) # transposition A__ : Tuple = ( len([(ca, ca) for ca, ca in zip(lowerCamelCase_ , lowerCamelCase_ ) if ca != ca] ) // 2 ) if not match_count: A__ : str = 0.0 else: A__ : Dict = ( 1 / 3 * ( match_count / len(lowerCamelCase_ ) + match_count / len(lowerCamelCase_ ) + (match_count - transpositions) / match_count ) ) # common prefix up to 4 characters A__ : Union[str, Any] = 0 for ca, ca in zip(stra[:4] , stra[:4] ): if ca == ca: prefix_len += 1 else: break return jaro + 0.1 * prefix_len * (1 - jaro) if __name__ == "__main__": import doctest doctest.testmod() print(jaro_winkler('hello', 'world'))
712
def UpperCamelCase (lowercase_: int , lowercase_: int ) -> int: while second != 0: A__ : int = first & second first ^= second A__ : int = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() A_ : Optional[Any] = int(input('Enter the first number: ').strip()) A_ : List[str] = int(input('Enter the second number: ').strip()) print(f'''{add(first, second) = }''')
64
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A_ : List[str] = { "configuration_xlm_roberta_xl": [ "XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP", "XLMRobertaXLConfig", "XLMRobertaXLOnnxConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : int = [ "XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST", "XLMRobertaXLForCausalLM", "XLMRobertaXLForMaskedLM", "XLMRobertaXLForMultipleChoice", "XLMRobertaXLForQuestionAnswering", "XLMRobertaXLForSequenceClassification", "XLMRobertaXLForTokenClassification", "XLMRobertaXLModel", "XLMRobertaXLPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMRobertaXLConfig, XLMRobertaXLOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST, XLMRobertaXLForCausalLM, XLMRobertaXLForMaskedLM, XLMRobertaXLForMultipleChoice, XLMRobertaXLForQuestionAnswering, XLMRobertaXLForSequenceClassification, XLMRobertaXLForTokenClassification, XLMRobertaXLModel, XLMRobertaXLPreTrainedModel, ) else: import sys A_ : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure)
713
from __future__ import annotations from collections.abc import Callable A_ : List[Any] = list[list[float | int]] def UpperCamelCase (lowercase_: Matrix , lowercase_: Matrix ) -> Matrix: A__ : int = len(lowercase_ ) A__ : Matrix = [[0 for _ in range(size + 1 )] for _ in range(lowercase_ )] A__ : int A__ : int A__ : int A__ : int A__ : int A__ : float for row in range(lowercase_ ): for col in range(lowercase_ ): A__ : List[str] = matrix[row][col] A__ : int = vector[row][0] A__ : Optional[int] = 0 A__ : str = 0 while row < size and col < size: # pivoting A__ : int = max((abs(augmented[rowa][col] ), rowa) for rowa in range(lowercase_ , lowercase_ ) )[ 1 ] if augmented[pivot_row][col] == 0: col += 1 continue else: A__ , A__ : Union[str, Any] = augmented[pivot_row], augmented[row] for rowa in range(row + 1 , lowercase_ ): A__ : List[Any] = augmented[rowa][col] / augmented[row][col] A__ : Dict = 0 for cola in range(col + 1 , size + 1 ): augmented[rowa][cola] -= augmented[row][cola] * ratio row += 1 col += 1 # back substitution for col in range(1 , lowercase_ ): for row in range(lowercase_ ): A__ : List[str] = augmented[row][col] / augmented[col][col] for cola in range(lowercase_ , size + 1 ): augmented[row][cola] -= augmented[col][cola] * ratio # round to get rid of numbers like 2.000000000000004 return [ [round(augmented[row][size] / augmented[row][row] , 10 )] for row in range(lowercase_ ) ] def UpperCamelCase (lowercase_: list[int] ) -> Callable[[int], int]: A__ : int = len(lowercase_ ) A__ : Matrix = [[0 for _ in range(lowercase_ )] for _ in range(lowercase_ )] A__ : Matrix = [[0] for _ in range(lowercase_ )] A__ : Matrix A__ : int A__ : int A__ : int for x_val, y_val in enumerate(lowercase_ ): for col in range(lowercase_ ): A__ : Dict = (x_val + 1) ** (size - col - 1) A__ : Any = y_val A__ : Union[str, Any] = solve(lowercase_ , lowercase_ ) def interpolated_func(lowercase_: int ) -> int: return sum( round(coeffs[x_val][0] ) * (var ** (size - x_val - 1)) for x_val in range(lowercase_ ) ) return interpolated_func def UpperCamelCase (lowercase_: int ) -> int: return ( 1 - variable + variable**2 - variable**3 + variable**4 - variable**5 + variable**6 - variable**7 + variable**8 - variable**9 + variable**10 ) def UpperCamelCase (lowercase_: Callable[[int], int] = question_function , lowercase_: int = 10 ) -> int: A__ : list[int] = [func(lowercase_ ) for x_val in range(1 , order + 1 )] A__ : list[Callable[[int], int]] = [ interpolate(data_points[:max_coeff] ) for max_coeff in range(1 , order + 1 ) ] A__ : int = 0 A__ : Callable[[int], int] A__ : int for poly in polynomials: A__ : List[str] = 1 while func(lowercase_ ) == poly(lowercase_ ): x_val += 1 ret += poly(lowercase_ ) return ret if __name__ == "__main__": print(f'''{solution() = }''')
64
0
import warnings from functools import wraps from typing import Callable def UpperCamelCase (lowercase_: int ) -> int: @wraps(a__ ) def _inner_fn(*lowercase_: Optional[int] , **lowercase_: Tuple ): warnings.warn( (f"""\'{fn.__name__}\' is experimental and might be subject to breaking changes in the future.""") , a__ , ) return fn(*a__ , **a__ ) return _inner_fn
714
from functools import lru_cache @lru_cache def UpperCamelCase (lowercase_: int ) -> int: 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()
64
0
import pytest from datasets.splits import SplitDict, SplitInfo from datasets.utils.py_utils import asdict @pytest.mark.parametrize( """split_dict""" , [ SplitDict(), SplitDict({"""train""": SplitInfo(name="""train""" , num_bytes=1337 , num_examples=42 , dataset_name="""my_dataset""" )} ), SplitDict({"""train""": SplitInfo(name="""train""" , num_bytes=1337 , num_examples=42 )} ), SplitDict({"""train""": SplitInfo()} ), ] , ) def UpperCamelCase (lowercase_: SplitDict ) -> Tuple: A__ : Tuple = split_dict._to_yaml_list() assert len(UpperCamelCase__ ) == len(UpperCamelCase__ ) A__ : Optional[Any] = SplitDict._from_yaml_list(UpperCamelCase__ ) for split_name, split_info in split_dict.items(): # dataset_name field is deprecated, and is therefore not part of the YAML dump A__ : Dict = None # the split name of split_dict takes over the name of the split info object A__ : Dict = split_name assert split_dict == reloaded @pytest.mark.parametrize( """split_info""" , [SplitInfo(), SplitInfo(dataset_name=UpperCamelCase__ ), SplitInfo(dataset_name="""my_dataset""" )] ) def UpperCamelCase (lowercase_: Optional[int] ) -> Tuple: # For backward compatibility, we need asdict(split_dict) to return split info dictrionaries with the "dataset_name" # field even if it's deprecated. This way old versionso of `datasets` can still reload dataset_infos.json files A__ : Union[str, Any] = asdict(SplitDict({"""train""": split_info} ) ) assert "dataset_name" in split_dict_asdict["train"] assert split_dict_asdict["train"]["dataset_name"] == split_info.dataset_name
715
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import datasets import datasets.config from .utils import require_beam class _a (datasets.BeamBasedBuilder ): '''simple docstring''' def __A ( self ): return datasets.DatasetInfo( features=datasets.Features({"""content""": datasets.Value("""string""" )} ) , supervised_keys=A__ , ) def __A ( self , A__ , A__ ): return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""examples""": get_test_dummy_examples()} )] def __A ( self , A__ , A__ ): import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(A__ ) class _a (datasets.BeamBasedBuilder ): '''simple docstring''' def __A ( self ): return datasets.DatasetInfo( features=datasets.Features({"""a""": datasets.Sequence({"""b""": datasets.Value("""string""" )} )} ) , supervised_keys=A__ , ) def __A ( self , A__ , A__ ): return [ datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""examples""": get_test_nested_examples()} ) ] def __A ( self , A__ , A__ ): import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(A__ ) def UpperCamelCase () -> Dict: return [(i, {"content": content}) for i, content in enumerate(["""foo""", """bar""", """foobar"""] )] def UpperCamelCase () -> Tuple: return [(i, {"a": {"b": [content]}}) for i, content in enumerate(["""foo""", """bar""", """foobar"""] )] class _a (__magic_name__ ): '''simple docstring''' @require_beam def __A ( self ): A__ : Dict = len(get_test_dummy_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: A__ : int = DummyBeamDataset(cache_dir=A__ , beam_runner="""DirectRunner""" ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(A__ , builder.name , """default""" , """0.0.0""" , F"""{builder.name}-train.arrow""" ) ) ) self.assertDictEqual(builder.info.features , datasets.Features({"""content""": datasets.Value("""string""" )} ) ) A__ : int = builder.as_dataset() self.assertEqual(dset["""train"""].num_rows , A__ ) self.assertEqual(dset["""train"""].info.splits["""train"""].num_examples , A__ ) self.assertDictEqual(dset["""train"""][0] , get_test_dummy_examples()[0][1] ) self.assertDictEqual( dset["""train"""][expected_num_examples - 1] , get_test_dummy_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(A__ , builder.name , """default""" , """0.0.0""" , """dataset_info.json""" ) ) ) del dset @require_beam def __A ( self ): import apache_beam as beam A__ : int = beam.io.parquetio.WriteToParquet A__ : List[str] = len(get_test_dummy_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: A__ : str = DummyBeamDataset(cache_dir=A__ , beam_runner="""DirectRunner""" ) with patch("""apache_beam.io.parquetio.WriteToParquet""" ) as write_parquet_mock: A__ : Optional[Any] = partial(A__ , num_shards=2 ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join( A__ , builder.name , """default""" , """0.0.0""" , F"""{builder.name}-train-00000-of-00002.arrow""" ) ) ) self.assertTrue( os.path.exists( os.path.join( A__ , builder.name , """default""" , """0.0.0""" , F"""{builder.name}-train-00000-of-00002.arrow""" ) ) ) self.assertDictEqual(builder.info.features , datasets.Features({"""content""": datasets.Value("""string""" )} ) ) A__ : Optional[int] = builder.as_dataset() self.assertEqual(dset["""train"""].num_rows , A__ ) self.assertEqual(dset["""train"""].info.splits["""train"""].num_examples , A__ ) # Order is not preserved when sharding, so we just check that all the elements are there self.assertListEqual(sorted(dset["""train"""]["""content"""] ) , sorted(["""foo""", """bar""", """foobar"""] ) ) self.assertTrue( os.path.exists(os.path.join(A__ , builder.name , """default""" , """0.0.0""" , """dataset_info.json""" ) ) ) del dset @require_beam def __A ( self ): with tempfile.TemporaryDirectory() as tmp_cache_dir: A__ : int = DummyBeamDataset(cache_dir=A__ ) self.assertRaises(datasets.builder.MissingBeamOptions , builder.download_and_prepare ) @require_beam def __A ( self ): A__ : List[Any] = len(get_test_nested_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: A__ : Optional[int] = NestedBeamDataset(cache_dir=A__ , beam_runner="""DirectRunner""" ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(A__ , builder.name , """default""" , """0.0.0""" , F"""{builder.name}-train.arrow""" ) ) ) self.assertDictEqual( builder.info.features , datasets.Features({"""a""": datasets.Sequence({"""b""": datasets.Value("""string""" )} )} ) ) A__ : Optional[int] = builder.as_dataset() self.assertEqual(dset["""train"""].num_rows , A__ ) self.assertEqual(dset["""train"""].info.splits["""train"""].num_examples , A__ ) self.assertDictEqual(dset["""train"""][0] , get_test_nested_examples()[0][1] ) self.assertDictEqual( dset["""train"""][expected_num_examples - 1] , get_test_nested_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(A__ , builder.name , """default""" , """0.0.0""" , """dataset_info.json""" ) ) ) del dset
64
0
from typing import Dict import numpy as np from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException if is_tf_available(): import tensorflow as tf from ..tf_utils import stable_softmax if is_torch_available(): import torch A_ : int = logging.get_logger(__name__) @add_end_docstrings( __UpperCAmelCase , r''' top_k (`int`, defaults to 5): The number of predictions to return. targets (`str` or `List[str]`, *optional*): When passed, the model will limit the scores to the passed targets instead of looking up in the whole vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting token will be used (with a warning, and that might be slower). ''' , ) class _a (__UpperCAmelCase ): '''simple docstring''' def __A ( self , A__ ): if self.framework == "tf": A__ : Dict = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy() elif self.framework == "pt": A__ : List[Any] = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=__SCREAMING_SNAKE_CASE ) else: raise ValueError("""Unsupported framework""" ) return masked_index def __A ( self , A__ ): A__ : Union[str, Any] = self.get_masked_index(__SCREAMING_SNAKE_CASE ) A__ : Optional[int] = np.prod(masked_index.shape ) if numel < 1: raise PipelineException( """fill-mask""" , self.model.base_model_prefix , F"""No mask_token ({self.tokenizer.mask_token}) found on the input""" , ) def __A ( self , A__ ): if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): for model_input in model_inputs: self._ensure_exactly_one_mask_token(model_input["""input_ids"""][0] ) else: for input_ids in model_inputs["input_ids"]: self._ensure_exactly_one_mask_token(__SCREAMING_SNAKE_CASE ) def __A ( self , A__ , A__=None , **A__ ): if return_tensors is None: A__ : List[Any] = self.framework A__ : Union[str, Any] = self.tokenizer(__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE ) self.ensure_exactly_one_mask_token(__SCREAMING_SNAKE_CASE ) return model_inputs def __A ( self , A__ ): A__ : Any = self.model(**__SCREAMING_SNAKE_CASE ) A__ : List[Any] = model_inputs["""input_ids"""] return model_outputs def __A ( self , A__ , A__=5 , A__=None ): if target_ids is not None and target_ids.shape[0] < top_k: A__ : str = target_ids.shape[0] A__ : int = model_outputs["""input_ids"""][0] A__ : List[Any] = model_outputs["""logits"""] if self.framework == "tf": A__ : List[Any] = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()[:, 0] A__ : List[Any] = outputs.numpy() A__ : List[Any] = outputs[0, masked_index, :] A__ : Optional[Any] = stable_softmax(__SCREAMING_SNAKE_CASE , axis=-1 ) if target_ids is not None: A__ : str = tf.gather_nd(tf.squeeze(__SCREAMING_SNAKE_CASE , 0 ) , target_ids.reshape(-1 , 1 ) ) A__ : List[Any] = tf.expand_dims(__SCREAMING_SNAKE_CASE , 0 ) A__ : Optional[int] = tf.math.top_k(__SCREAMING_SNAKE_CASE , k=__SCREAMING_SNAKE_CASE ) A__ , A__ : Dict = topk.values.numpy(), topk.indices.numpy() else: A__ : Optional[int] = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=__SCREAMING_SNAKE_CASE ).squeeze(-1 ) # Fill mask pipeline supports only one ${mask_token} per sample A__ : Optional[int] = outputs[0, masked_index, :] A__ : Dict = logits.softmax(dim=-1 ) if target_ids is not None: A__ : int = probs[..., target_ids] A__ , A__ : Dict = probs.topk(__SCREAMING_SNAKE_CASE ) A__ : Any = [] A__ : List[Any] = values.shape[0] == 1 for i, (_values, _predictions) in enumerate(zip(values.tolist() , predictions.tolist() ) ): A__ : Union[str, Any] = [] for v, p in zip(_values , _predictions ): # Copy is important since we're going to modify this array in place A__ : Any = input_ids.numpy().copy() if target_ids is not None: A__ : str = target_ids[p].tolist() A__ : Tuple = p # Filter padding out: A__ : Dict = tokens[np.where(tokens != self.tokenizer.pad_token_id )] # Originally we skip special tokens to give readable output. # For multi masks though, the other [MASK] would be removed otherwise # making the output look odd, so we add them back A__ : Union[str, Any] = self.tokenizer.decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE ) A__ : int = {"""score""": v, """token""": p, """token_str""": self.tokenizer.decode([p] ), """sequence""": sequence} row.append(__SCREAMING_SNAKE_CASE ) result.append(__SCREAMING_SNAKE_CASE ) if single_mask: return result[0] return result def __A ( self , A__ , A__=None ): if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): A__ : Dict = [targets] try: A__ : Tuple = self.tokenizer.get_vocab() except Exception: A__ : Dict = {} A__ : List[str] = [] for target in targets: A__ : Optional[int] = vocab.get(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if id_ is None: A__ : Union[str, Any] = self.tokenizer( __SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , return_attention_mask=__SCREAMING_SNAKE_CASE , return_token_type_ids=__SCREAMING_SNAKE_CASE , max_length=1 , truncation=__SCREAMING_SNAKE_CASE , )["""input_ids"""] if len(__SCREAMING_SNAKE_CASE ) == 0: logger.warning( F"""The specified target token `{target}` does not exist in the model vocabulary. """ """We cannot replace it with anything meaningful, ignoring it""" ) continue A__ : int = input_ids[0] # XXX: If users encounter this pass # it becomes pretty slow, so let's make sure # The warning enables them to fix the input to # get faster performance. logger.warning( F"""The specified target token `{target}` does not exist in the model vocabulary. """ F"""Replacing with `{self.tokenizer.convert_ids_to_tokens(id_ )}`.""" ) target_ids.append(id_ ) A__ : List[str] = list(set(__SCREAMING_SNAKE_CASE ) ) if len(__SCREAMING_SNAKE_CASE ) == 0: raise ValueError("""At least one target must be provided when passed.""" ) A__ : Tuple = np.array(__SCREAMING_SNAKE_CASE ) return target_ids def __A ( self , A__=None , A__=None ): A__ : Tuple = {} if targets is not None: A__ : Optional[int] = self.get_target_ids(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) A__ : Optional[int] = target_ids if top_k is not None: A__ : Dict = top_k if self.tokenizer.mask_token_id is None: raise PipelineException( """fill-mask""" , self.model.base_model_prefix , """The tokenizer does not define a `mask_token`.""" ) return {}, {}, postprocess_params def __call__( self , A__ , *A__ , **A__ ): A__ : Tuple = super().__call__(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) and len(__SCREAMING_SNAKE_CASE ) == 1: return outputs[0] return outputs
716
import warnings from ...utils import logging from .image_processing_poolformer import PoolFormerImageProcessor A_ : Union[str, Any] = logging.get_logger(__name__) class _a (__magic_name__ ): '''simple docstring''' def __init__( self , *A__ , **A__ ): warnings.warn( """The class PoolFormerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use PoolFormerImageProcessor instead.""" , A__ , ) super().__init__(*A__ , **A__ )
64
0
import fire from utils import calculate_rouge, save_json def UpperCamelCase (lowercase_: List[Any] , lowercase_: List[str] , lowercase_: Union[str, Any]=None , **lowercase_: List[Any] ) -> List[Any]: A__ : List[Any] = [x.strip() for x in open(lowercase_ ).readlines()] A__ : Optional[Any] = [x.strip() for x in open(lowercase_ ).readlines()][: len(lowercase_ )] A__ : List[Any] = calculate_rouge(lowercase_ , lowercase_ , **lowercase_ ) if save_path is not None: save_json(lowercase_ , lowercase_ , indent=lowercase_ ) return metrics # these print nicely if __name__ == "__main__": fire.Fire(calculate_rouge_path)
717
import inspect import logging import os import random import shutil import tempfile import unittest import pytest import torch from torch import nn from torch.utils.data import DataLoader, TensorDataset from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_cuda from accelerate.utils import ProjectConfiguration, set_seed A_ : Any = logging.getLogger(__name__) def UpperCamelCase (lowercase_: Optional[Any]=2 , lowercase_: Union[str, Any]=3 , lowercase_: int=16 , lowercase_: int = 10 , lowercase_: int = 2 ) -> int: def get_dataset(lowercase_: Optional[int] ): A__ : Optional[Any] = torch.randn(batch_size * n_batches , 1 ) return TensorDataset(lowercase_ , a * x + b + 0.1 * torch.randn(batch_size * n_batches , 1 ) ) A__ : Dict = get_dataset(lowercase_ ) A__ : Any = get_dataset(lowercase_ ) A__ : Dict = DataLoader(lowercase_ , shuffle=lowercase_ , batch_size=lowercase_ , num_workers=4 ) A__ : Optional[Any] = DataLoader(lowercase_ , shuffle=lowercase_ , batch_size=lowercase_ , num_workers=4 ) return (train_dataloader, valid_dataloader) def UpperCamelCase (lowercase_: Optional[Any] , lowercase_: List[str] , lowercase_: int , lowercase_: int , lowercase_: List[str] , lowercase_: Dict=None ) -> List[Any]: A__ : List[Any] = [] for epoch in range(lowercase_ ): # Train quickly model.train() for batch in dataloader: A__ , A__ : Any = batch A__ : Any = model(lowercase_ ) A__ : Any = torch.nn.functional.mse_loss(lowercase_ , lowercase_ ) accelerator.backward(lowercase_ ) optimizer.step() optimizer.zero_grad() rands.append(random.random() ) # Introduce some randomness if scheduler is not None: scheduler.step() return rands class _a (nn.Module ): '''simple docstring''' def __init__( self ): super().__init__() A__ : str = nn.Parameter(torch.randn(1 ) ) A__ : Any = nn.Parameter(torch.randn(1 ) ) def __A ( self , A__ ): return x * self.a + self.b class _a (unittest.TestCase ): '''simple docstring''' def __A ( self ): with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) A__ : Optional[Any] = DummyModel() A__ : Optional[Any] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) A__ , A__ : str = dummy_dataloaders() A__ : Dict = ProjectConfiguration(total_limit=1 , project_dir=A__ , automatic_checkpoint_naming=A__ ) # Train baseline A__ : List[str] = Accelerator(project_config=A__ ) A__ , A__ , A__ , A__ : Any = accelerator.prepare( A__ , A__ , A__ , A__ ) # Save initial accelerator.save_state() # Save second state accelerator.save_state() self.assertEqual(len(os.listdir(accelerator.project_dir ) ) , 1 ) def __A ( self ): with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) A__ : str = DummyModel() A__ : Optional[int] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) A__ , A__ : int = dummy_dataloaders() # Train baseline A__ : str = Accelerator() A__ , A__ , A__ , A__ : List[str] = accelerator.prepare( A__ , A__ , A__ , A__ ) # Save initial A__ : List[Any] = os.path.join(A__ , """initial""" ) accelerator.save_state(A__ ) ((A__) , (A__)) : str = model.a.item(), model.b.item() A__ : Dict = optimizer.state_dict() A__ : List[str] = train(3 , A__ , A__ , A__ , A__ ) ((A__) , (A__)) : str = model.a.item(), model.b.item() A__ : Any = optimizer.state_dict() # Train partially set_seed(42 ) A__ : Optional[int] = DummyModel() A__ : Dict = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) A__ , A__ : Dict = dummy_dataloaders() A__ : List[str] = Accelerator() A__ , A__ , A__ , A__ : Optional[Any] = accelerator.prepare( A__ , A__ , A__ , A__ ) accelerator.load_state(A__ ) ((A__) , (A__)) : Tuple = model.a.item(), model.b.item() A__ : Union[str, Any] = optimizer.state_dict() self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) A__ : List[str] = train(2 , A__ , A__ , A__ , A__ ) # Save everything A__ : Optional[int] = os.path.join(A__ , """checkpoint""" ) accelerator.save_state(A__ ) # Load everything back in and make sure all states work accelerator.load_state(A__ ) test_rands += train(1 , A__ , A__ , A__ , A__ ) ((A__) , (A__)) : Union[str, Any] = model.a.item(), model.b.item() A__ : Optional[int] = optimizer.state_dict() self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) def __A ( self ): with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) A__ : int = DummyModel() A__ : Optional[int] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) A__ , A__ : List[str] = dummy_dataloaders() A__ : str = ProjectConfiguration(automatic_checkpoint_naming=A__ ) # Train baseline A__ : Any = Accelerator(project_dir=A__ , project_config=A__ ) A__ , A__ , A__ , A__ : str = accelerator.prepare( A__ , A__ , A__ , A__ ) # Save initial accelerator.save_state() ((A__) , (A__)) : Tuple = model.a.item(), model.b.item() A__ : int = optimizer.state_dict() A__ : int = train(3 , A__ , A__ , A__ , A__ ) ((A__) , (A__)) : Optional[Any] = model.a.item(), model.b.item() A__ : Any = optimizer.state_dict() # Train partially set_seed(42 ) A__ : Dict = DummyModel() A__ : List[Any] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) A__ , A__ : Union[str, Any] = dummy_dataloaders() A__ : List[Any] = ProjectConfiguration(iteration=1 , automatic_checkpoint_naming=A__ ) A__ : Dict = Accelerator(project_dir=A__ , project_config=A__ ) A__ , A__ , A__ , A__ : Union[str, Any] = accelerator.prepare( A__ , A__ , A__ , A__ ) accelerator.load_state(os.path.join(A__ , """checkpoints""" , """checkpoint_0""" ) ) ((A__) , (A__)) : Optional[int] = model.a.item(), model.b.item() A__ : Tuple = optimizer.state_dict() self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) A__ : str = train(2 , A__ , A__ , A__ , A__ ) # Save everything accelerator.save_state() # Load everything back in and make sure all states work accelerator.load_state(os.path.join(A__ , """checkpoints""" , """checkpoint_1""" ) ) test_rands += train(1 , A__ , A__ , A__ , A__ ) ((A__) , (A__)) : Optional[int] = model.a.item(), model.b.item() A__ : List[Any] = optimizer.state_dict() self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) def __A ( self ): A__ : Union[str, Any] = torch.tensor([1, 2, 3] ) A__ : int = torch.tensor([2, 3, 4] ) A__ : List[Any] = DummyModel() A__ : List[Any] = torch.optim.Adam(net.parameters() ) A__ : Tuple = Accelerator() with self.assertRaises(A__ ) as ve: accelerator.register_for_checkpointing(A__ , A__ , A__ , A__ ) A__ : Any = str(ve.exception ) self.assertTrue("""Item at index 0""" in message ) self.assertTrue("""Item at index 1""" in message ) self.assertFalse("""Item at index 2""" in message ) self.assertFalse("""Item at index 3""" in message ) def __A ( self ): with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) A__ : Any = DummyModel() A__ : Union[str, Any] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) A__ : Dict = torch.optim.lr_scheduler.StepLR(A__ , step_size=1 , gamma=0.9_9 ) A__ , A__ : List[Any] = dummy_dataloaders() A__ : Tuple = ProjectConfiguration(automatic_checkpoint_naming=A__ ) # Train baseline A__ : Optional[Any] = Accelerator(project_dir=A__ , project_config=A__ ) A__ , A__ , A__ , A__ , A__ : Union[str, Any] = accelerator.prepare( A__ , A__ , A__ , A__ , A__ ) # Save initial accelerator.save_state() A__ : Tuple = scheduler.state_dict() train(3 , A__ , A__ , A__ , A__ , A__ ) self.assertNotEqual(A__ , scheduler.state_dict() ) # Load everything back in and make sure all states work accelerator.load_state(os.path.join(A__ , """checkpoints""" , """checkpoint_0""" ) ) self.assertEqual(A__ , scheduler.state_dict() ) def __A ( self ): with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) A__ : Optional[Any] = DummyModel() A__ : int = ProjectConfiguration(automatic_checkpoint_naming=A__ , total_limit=2 ) # Train baseline A__ : List[str] = Accelerator(project_dir=A__ , project_config=A__ ) A__ : Union[str, Any] = accelerator.prepare(A__ ) # Save 3 states: for _ in range(11 ): accelerator.save_state() self.assertTrue(not os.path.exists(os.path.join(A__ , """checkpoints""" , """checkpoint_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(A__ , """checkpoints""" , """checkpoint_9""" ) ) ) self.assertTrue(os.path.exists(os.path.join(A__ , """checkpoints""" , """checkpoint_10""" ) ) ) @require_cuda def __A ( self ): A__ : Dict = ["""torchrun""", F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__ )] execute_subprocess_async(A__ , env=os.environ.copy() ) if __name__ == "__main__": A_ : List[str] = '/tmp/accelerate/state_checkpointing' A_ : Optional[Any] = DummyModel() A_ : Union[str, Any] = torch.optim.Adam(params=model.parameters(), lr=1E-3) A_ : str = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99) A_ , A_ : List[Any] = dummy_dataloaders() A_ : int = ProjectConfiguration(automatic_checkpoint_naming=True) # Train baseline A_ : List[str] = Accelerator(project_dir=savedir, project_config=project_config, mixed_precision='no') if accelerator.process_index == 0: if os.path.exists(savedir): shutil.rmtree(savedir) os.makedirs(savedir) A_ , A_ , A_ , A_ , A_ : List[Any] = accelerator.prepare( model, optimizer, train_dataloader, valid_dataloader, scheduler ) A_ , A_ : Dict = accelerator.prepare(model, optimizer) train(3, model, train_dataloader, optimizer, accelerator, scheduler) # Check that the intial optimizer is loaded on the GPU for group in optimizer.param_groups: A_ : str = group['params'][0].device break assert param_device.type == accelerator.device.type A_ : Optional[Any] = model.cpu() accelerator.wait_for_everyone() accelerator.save_state() accelerator.wait_for_everyone() # Check CPU state accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='cpu') for group in optimizer.param_groups: A_ : str = group['params'][0].device break assert ( param_device.type == torch.device('cpu').type ), f"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}" # Check device state model.to(accelerator.device) accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='on_device') for group in optimizer.param_groups: A_ : Tuple = group['params'][0].device break assert ( param_device.type == accelerator.device.type ), f"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}" # Check error with pytest.raises(TypeError, match='Unsupported optimizer map location passed'): accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='invalid') accelerator.wait_for_everyone() if accelerator.process_index == 0: shutil.rmtree(savedir) accelerator.wait_for_everyone()
64
0
import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def UpperCamelCase (lowercase_: str ) -> List[str]: if is_torch_version("""<""" , """2.0.0""" ) or not hasattr(_lowercase , """_dynamo""" ): return False return isinstance(_lowercase , torch._dynamo.eval_frame.OptimizedModule ) def UpperCamelCase (lowercase_: Optional[Any] , lowercase_: List[Any] = True ) -> Dict: A__ : List[Any] = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) A__ : Union[str, Any] = is_compiled_module(_lowercase ) if is_compiled: A__ : Any = model A__ : Dict = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(_lowercase , _lowercase ): A__ : Dict = model.module if not keep_fpaa_wrapper: A__ : Union[str, Any] = getattr(_lowercase , """forward""" ) A__ : Dict = model.__dict__.pop("""_original_forward""" , _lowercase ) if original_forward is not None: while hasattr(_lowercase , """__wrapped__""" ): A__ : str = forward.__wrapped__ if forward == original_forward: break A__ : Any = forward if getattr(_lowercase , """_converted_to_transformer_engine""" , _lowercase ): convert_model(_lowercase , to_transformer_engine=_lowercase ) if is_compiled: A__ : Union[str, Any] = model A__ : Union[str, Any] = compiled_model return model def UpperCamelCase () -> Any: PartialState().wait_for_everyone() def UpperCamelCase (lowercase_: List[Any] , lowercase_: int ) -> int: if PartialState().distributed_type == DistributedType.TPU: xm.save(_lowercase , _lowercase ) elif PartialState().local_process_index == 0: torch.save(_lowercase , _lowercase ) @contextmanager def UpperCamelCase (**lowercase_: str ) -> Dict: for key, value in kwargs.items(): A__ : str = str(_lowercase ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def UpperCamelCase (lowercase_: int ) -> Dict: if not hasattr(_lowercase , """__qualname__""" ) and not hasattr(_lowercase , """__name__""" ): A__ : Union[str, Any] = getattr(_lowercase , """__class__""" , _lowercase ) if hasattr(_lowercase , """__qualname__""" ): return obj.__qualname__ if hasattr(_lowercase , """__name__""" ): return obj.__name__ return str(_lowercase ) def UpperCamelCase (lowercase_: Union[str, Any] , lowercase_: Any ) -> Union[str, Any]: for key, value in source.items(): if isinstance(_lowercase , _lowercase ): A__ : List[str] = destination.setdefault(_lowercase , {} ) merge_dicts(_lowercase , _lowercase ) else: A__ : List[Any] = value return destination def UpperCamelCase (lowercase_: List[Any] = None ) -> Dict: if port is None: A__ : Union[str, Any] = 29500 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(("""localhost""", port) ) == 0
718
def UpperCamelCase (lowercase_: str , lowercase_: str ) -> bool: A__ : Union[str, Any] = len(lowercase_ ) A__ : List[Any] = len(lowercase_ ) A__ : List[Any] = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] A__ : str = True for i in range(lowercase_ ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: A__ : int = True if a[i].islower(): A__ : Dict = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
64
0
from ..utils import ( OptionalDependencyNotAvailable, is_flax_available, is_scipy_available, is_torch_available, is_torchsde_available, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_pt_objects import * # noqa F403 else: from .scheduling_consistency_models import CMStochasticIterativeScheduler from .scheduling_ddim import DDIMScheduler from .scheduling_ddim_inverse import DDIMInverseScheduler from .scheduling_ddim_parallel import DDIMParallelScheduler from .scheduling_ddpm import DDPMScheduler from .scheduling_ddpm_parallel import DDPMParallelScheduler from .scheduling_deis_multistep import DEISMultistepScheduler from .scheduling_dpmsolver_multistep import DPMSolverMultistepScheduler from .scheduling_dpmsolver_multistep_inverse import DPMSolverMultistepInverseScheduler from .scheduling_dpmsolver_singlestep import DPMSolverSinglestepScheduler from .scheduling_euler_ancestral_discrete import EulerAncestralDiscreteScheduler from .scheduling_euler_discrete import EulerDiscreteScheduler from .scheduling_heun_discrete import HeunDiscreteScheduler from .scheduling_ipndm import IPNDMScheduler from .scheduling_k_dpm_2_ancestral_discrete import KDPMaAncestralDiscreteScheduler from .scheduling_k_dpm_2_discrete import KDPMaDiscreteScheduler from .scheduling_karras_ve import KarrasVeScheduler from .scheduling_pndm import PNDMScheduler from .scheduling_repaint import RePaintScheduler from .scheduling_sde_ve import ScoreSdeVeScheduler from .scheduling_sde_vp import ScoreSdeVpScheduler from .scheduling_unclip import UnCLIPScheduler from .scheduling_unipc_multistep import UniPCMultistepScheduler from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin from .scheduling_vq_diffusion import VQDiffusionScheduler try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_flax_objects import * # noqa F403 else: from .scheduling_ddim_flax import FlaxDDIMScheduler from .scheduling_ddpm_flax import FlaxDDPMScheduler from .scheduling_dpmsolver_multistep_flax import FlaxDPMSolverMultistepScheduler from .scheduling_karras_ve_flax import FlaxKarrasVeScheduler from .scheduling_lms_discrete_flax import FlaxLMSDiscreteScheduler from .scheduling_pndm_flax import FlaxPNDMScheduler from .scheduling_sde_ve_flax import FlaxScoreSdeVeScheduler from .scheduling_utils_flax import ( FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, broadcast_to_shape_from_left, ) try: if not (is_torch_available() and is_scipy_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_scipy_objects import * # noqa F403 else: from .scheduling_lms_discrete import LMSDiscreteScheduler try: if not (is_torch_available() and is_torchsde_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_torchsde_objects import * # noqa F403 else: from .scheduling_dpmsolver_sde import DPMSolverSDEScheduler
719
import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin A_ : Dict = random.Random() if is_torch_available(): import torch def UpperCamelCase (lowercase_: Tuple , lowercase_: Tuple=1.0 , lowercase_: Dict=None , lowercase_: int=None ) -> str: if rng is None: A__ : Optional[Any] = global_rng A__ : List[str] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class _a (unittest.TestCase ): '''simple docstring''' def __init__( self , A__ , A__=7 , A__=400 , A__=2000 , A__=1 , A__=0.0 , A__=1_6000 , A__=True , A__=True , ): A__ : Any = parent A__ : Optional[int] = batch_size A__ : Union[str, Any] = min_seq_length A__ : Dict = max_seq_length A__ : Tuple = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) A__ : str = feature_size A__ : Optional[int] = padding_value A__ : List[str] = sampling_rate A__ : List[str] = return_attention_mask A__ : int = do_normalize def __A ( self ): return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def __A ( self , A__=False , A__=False ): def _flatten(A__ ): return list(itertools.chain(*A__ ) ) if equal_length: A__ : Dict = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size A__ : Union[str, Any] = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: A__ : Optional[int] = [np.asarray(A__ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class _a (__magic_name__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: int = ASTFeatureExtractor def __A ( self ): A__ : Optional[Any] = ASTFeatureExtractionTester(self ) def __A ( self ): # Tests that all call wrap to encode_plus and batch_encode_plus A__ : Optional[int] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 A__ : List[Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] A__ : Optional[Any] = [np.asarray(A__ ) for speech_input in speech_inputs] # Test not batched input A__ : Tuple = feat_extract(speech_inputs[0] , return_tensors="""np""" ).input_values A__ : Tuple = feat_extract(np_speech_inputs[0] , return_tensors="""np""" ).input_values self.assertTrue(np.allclose(A__ , A__ , atol=1e-3 ) ) # Test batched A__ : Tuple = feat_extract(A__ , padding=A__ , return_tensors="""np""" ).input_values A__ : Tuple = feat_extract(A__ , padding=A__ , return_tensors="""np""" ).input_values for enc_seq_a, enc_seq_a in zip(A__ , A__ ): self.assertTrue(np.allclose(A__ , A__ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. A__ : int = [floats_list((1, x) )[0] for x in (800, 800, 800)] A__ : List[str] = np.asarray(A__ ) A__ : Union[str, Any] = feat_extract(A__ , return_tensors="""np""" ).input_values A__ : Optional[Any] = feat_extract(A__ , return_tensors="""np""" ).input_values for enc_seq_a, enc_seq_a in zip(A__ , A__ ): self.assertTrue(np.allclose(A__ , A__ , atol=1e-3 ) ) @require_torch def __A ( self ): import torch A__ : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) A__ : Tuple = np.random.rand(100 ).astype(np.floataa ) A__ : Tuple = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: A__ : List[str] = feature_extractor.pad([{"""input_values""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) A__ : Any = feature_extractor.pad([{"""input_values""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def __A ( self , A__ ): from datasets import load_dataset A__ : str = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech A__ : str = ds.sort("""id""" ).select(range(A__ ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] @require_torch def __A ( self ): # fmt: off A__ : Optional[Any] = torch.tensor( [-0.9_8_9_4, -1.2_7_7_6, -0.9_0_6_6, -1.2_7_7_6, -0.9_3_4_9, -1.2_6_0_9, -1.0_3_8_6, -1.2_7_7_6, -1.1_5_6_1, -1.2_7_7_6, -1.2_0_5_2, -1.2_7_2_3, -1.2_1_9_0, -1.2_1_3_2, -1.2_7_7_6, -1.1_1_3_3, -1.1_9_5_3, -1.1_3_4_3, -1.1_5_8_4, -1.2_2_0_3, -1.1_7_7_0, -1.2_4_7_4, -1.2_3_8_1, -1.1_9_3_6, -0.9_2_7_0, -0.8_3_1_7, -0.8_0_4_9, -0.7_7_0_6, -0.7_5_6_5, -0.7_8_6_9] ) # fmt: on A__ : Any = self._load_datasamples(1 ) A__ : Tuple = ASTFeatureExtractor() A__ : Dict = feature_extractor(A__ , return_tensors="""pt""" ).input_values self.assertEquals(input_values.shape , (1, 1024, 128) ) self.assertTrue(torch.allclose(input_values[0, 0, :30] , A__ , atol=1e-4 ) )
64
0
import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_available from .test_pipelines_common import ANY if is_torch_available(): import torch @is_pipeline_test class _a (unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: Union[str, Any] = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING UpperCAmelCase__: Dict = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def __A ( self , A__ , A__ , A__ ): A__ : int = TextaTextGenerationPipeline(model=_a , tokenizer=_a ) return generator, ["Something to write", "Something else"] def __A ( self , A__ , A__ ): A__ : Union[str, Any] = generator("""Something there""" ) self.assertEqual(_a , [{"""generated_text""": ANY(_a )}] ) # These are encoder decoder, they don't just append to incoming string self.assertFalse(outputs[0]["""generated_text"""].startswith("""Something there""" ) ) A__ : Optional[Any] = generator(["""This is great !""", """Something else"""] , num_return_sequences=2 , do_sample=_a ) self.assertEqual( _a , [ [{"""generated_text""": ANY(_a )}, {"""generated_text""": ANY(_a )}], [{"""generated_text""": ANY(_a )}, {"""generated_text""": ANY(_a )}], ] , ) A__ : Tuple = generator( ["""This is great !""", """Something else"""] , num_return_sequences=2 , batch_size=2 , do_sample=_a ) self.assertEqual( _a , [ [{"""generated_text""": ANY(_a )}, {"""generated_text""": ANY(_a )}], [{"""generated_text""": ANY(_a )}, {"""generated_text""": ANY(_a )}], ] , ) with self.assertRaises(_a ): generator(4 ) @require_torch def __A ( self ): A__ : Tuple = pipeline("""text2text-generation""" , model="""patrickvonplaten/t5-tiny-random""" , framework="""pt""" ) # do_sample=False necessary for reproducibility A__ : List[Any] = generator("""Something there""" , do_sample=_a ) self.assertEqual(_a , [{"""generated_text""": """"""}] ) A__ : str = 3 A__ : Optional[int] = generator( """Something there""" , num_return_sequences=_a , num_beams=_a , ) A__ : List[str] = [ {"""generated_text""": """Beide Beide Beide Beide Beide Beide Beide Beide Beide"""}, {"""generated_text""": """Beide Beide Beide Beide Beide Beide Beide Beide"""}, {"""generated_text""": """"""}, ] self.assertEqual(_a , _a ) A__ : Optional[Any] = generator("""This is a test""" , do_sample=_a , num_return_sequences=2 , return_tensors=_a ) self.assertEqual( _a , [ {"""generated_token_ids""": ANY(torch.Tensor )}, {"""generated_token_ids""": ANY(torch.Tensor )}, ] , ) A__ : int = generator.model.config.eos_token_id A__ : List[Any] = """<pad>""" A__ : str = generator( ["""This is a test""", """This is a second test"""] , do_sample=_a , num_return_sequences=2 , batch_size=2 , return_tensors=_a , ) self.assertEqual( _a , [ [ {"""generated_token_ids""": ANY(torch.Tensor )}, {"""generated_token_ids""": ANY(torch.Tensor )}, ], [ {"""generated_token_ids""": ANY(torch.Tensor )}, {"""generated_token_ids""": ANY(torch.Tensor )}, ], ] , ) @require_tf def __A ( self ): A__ : Optional[Any] = pipeline("""text2text-generation""" , model="""patrickvonplaten/t5-tiny-random""" , framework="""tf""" ) # do_sample=False necessary for reproducibility A__ : Optional[Any] = generator("""Something there""" , do_sample=_a ) self.assertEqual(_a , [{"""generated_text""": """"""}] )
720
from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class _a (__magic_name__ , __magic_name__ , __magic_name__ ): '''simple docstring''' UpperCAmelCase__: str = [r'''h\.\d+\.attn\.bias''', r'''h\.\d+\.attn\.masked_bias'''] @register_to_config def __init__( self , A__ , A__ , A__ = None , A__ = 5_0257 , A__ = 1024 , A__ = 768 , A__ = 12 , A__ = 12 , A__ = None , A__ = "gelu_new" , A__ = 0.1 , A__ = 0.1 , A__ = 0.1 , A__ = 1e-5 , A__ = 0.0_2 , A__ = True , A__ = True , A__ = False , A__ = False , ): super().__init__() A__ : Union[str, Any] = prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( F"""`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and""" F""" `n_embd`: {n_embd} are not equal.""" ) A__ : str = prefix_inner_dim A__ : Optional[Any] = prefix_hidden_dim A__ : Tuple = ( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) A__ : int = ( nn.Linear(self.prefix_hidden_dim , A__ ) if self.prefix_hidden_dim is not None else nn.Identity() ) A__ : Tuple = GPTaConfig( vocab_size=A__ , n_positions=A__ , n_embd=A__ , n_layer=A__ , n_head=A__ , n_inner=A__ , activation_function=A__ , resid_pdrop=A__ , embd_pdrop=A__ , attn_pdrop=A__ , layer_norm_epsilon=A__ , initializer_range=A__ , scale_attn_weights=A__ , use_cache=A__ , scale_attn_by_inverse_layer_idx=A__ , reorder_and_upcast_attn=A__ , ) A__ : int = GPTaLMHeadModel(A__ ) def __A ( self , A__ , A__ , A__ = None , A__ = None , ): A__ : List[str] = self.transformer.transformer.wte(A__ ) A__ : int = self.encode_prefix(A__ ) A__ : int = self.decode_prefix(A__ ) A__ : Optional[Any] = torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: A__ : Any = self.get_dummy_token(input_ids.shape[0] , input_ids.device ) A__ : List[Any] = torch.cat((dummy_token, input_ids) , dim=1 ) A__ : List[str] = self.transformer(inputs_embeds=A__ , labels=A__ , attention_mask=A__ ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def __A ( self , A__ , A__ ): return torch.zeros(A__ , self.prefix_length , dtype=torch.intaa , device=A__ ) def __A ( self , A__ ): return self.encode_prefix(A__ ) @torch.no_grad() def __A ( self , A__ , A__ , A__ ): A__ : List[Any] = torch.split(A__ , 1 , dim=0 ) A__ : Optional[int] = [] A__ : str = [] for feature in features: A__ : Dict = self.decode_prefix(feature.to(A__ ) ) # back to the clip feature # Only support beam search for now A__ , A__ : Union[str, Any] = self.generate_beam( input_embeds=A__ , device=A__ , eos_token_id=A__ ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) A__ : int = torch.stack(A__ ) A__ : List[Any] = torch.stack(A__ ) return generated_tokens, generated_seq_lengths @torch.no_grad() def __A ( self , A__=None , A__=None , A__=None , A__ = 5 , A__ = 67 , A__ = 1.0 , A__ = None , ): A__ : Any = eos_token_id A__ : Any = None A__ : Optional[int] = None A__ : Optional[Any] = torch.ones(A__ , device=A__ , dtype=torch.int ) A__ : Any = torch.zeros(A__ , device=A__ , dtype=torch.bool ) if input_embeds is not None: A__ : Dict = input_embeds else: A__ : str = self.transformer.transformer.wte(A__ ) for i in range(A__ ): A__ : Dict = self.transformer(inputs_embeds=A__ ) A__ : str = outputs.logits A__ : Union[str, Any] = logits[:, -1, :] / (temperature if temperature > 0 else 1.0) A__ : Any = logits.softmax(-1 ).log() if scores is None: A__ , A__ : Optional[int] = logits.topk(A__ , -1 ) A__ : List[Any] = generated.expand(A__ , *generated.shape[1:] ) A__ , A__ : List[Any] = next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: A__ : Optional[Any] = next_tokens else: A__ : List[Any] = tokens.expand(A__ , *tokens.shape[1:] ) A__ : int = torch.cat((tokens, next_tokens) , dim=1 ) else: A__ : Optional[int] = -float(np.inf ) A__ : List[Any] = 0 A__ : str = scores[:, None] + logits seq_lengths[~is_stopped] += 1 A__ : Dict = scores_sum / seq_lengths[:, None] A__ , A__ : List[Any] = scores_sum_average.view(-1 ).topk(A__ , -1 ) A__ : Tuple = next_tokens // scores_sum.shape[1] A__ : Optional[Any] = seq_lengths[next_tokens_source] A__ : List[str] = next_tokens % scores_sum.shape[1] A__ : Optional[int] = next_tokens.unsqueeze(1 ) A__ : int = tokens[next_tokens_source] A__ : List[Any] = torch.cat((tokens, next_tokens) , dim=1 ) A__ : str = generated[next_tokens_source] A__ : Optional[Any] = scores_sum_average * seq_lengths A__ : Union[str, Any] = is_stopped[next_tokens_source] A__ : str = self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) A__ : Optional[int] = torch.cat((generated, next_token_embed) , dim=1 ) A__ : List[str] = is_stopped + next_tokens.eq(A__ ).squeeze() if is_stopped.all(): break A__ : Dict = scores / seq_lengths A__ : Dict = scores.argsort(descending=A__ ) # tokens tensors are already padded to max_seq_length A__ : Union[str, Any] = [tokens[i] for i in order] A__ : Any = torch.stack(A__ , dim=0 ) A__ : Dict = torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
64
0
from PIL import Image def UpperCamelCase (lowercase_: Image , lowercase_: float ) -> Dict: def brightness(lowercase_: int ) -> float: return 128 + level + (c - 128) if not -255.0 <= level <= 255.0: raise ValueError("""level must be between -255.0 (black) and 255.0 (white)""" ) return img.point(_lowerCamelCase ) if __name__ == "__main__": # Load image with Image.open('image_data/lena.jpg') as img: # Change brightness to 100 A_ = change_brightness(img, 100) brigt_img.save('image_data/lena_brightness.png', format='png')
721
import io import itertools import json from dataclasses import dataclass from typing import Optional import pyarrow as pa import pyarrow.json as paj import datasets from datasets.table import table_cast from datasets.utils.file_utils import readline A_ : Tuple = datasets.utils.logging.get_logger(__name__) @dataclass class _a (datasets.BuilderConfig ): '''simple docstring''' UpperCAmelCase__: Optional[datasets.Features] = None UpperCAmelCase__: str = "utf-8" UpperCAmelCase__: Optional[str] = None UpperCAmelCase__: Optional[str] = None UpperCAmelCase__: bool = True # deprecated UpperCAmelCase__: Optional[int] = None # deprecated UpperCAmelCase__: int = 10 << 20 # 10MB UpperCAmelCase__: Optional[bool] = None class _a (datasets.ArrowBasedBuilder ): '''simple docstring''' UpperCAmelCase__: List[str] = JsonConfig def __A ( self ): if self.config.block_size is not None: logger.warning("""The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead""" ) A__ : Union[str, Any] = self.config.block_size if self.config.use_threads is not True: logger.warning( """The JSON loader parameter `use_threads` is deprecated and doesn't have any effect anymore.""" ) if self.config.newlines_in_values is not None: raise ValueError("""The JSON loader parameter `newlines_in_values` is no longer supported""" ) return datasets.DatasetInfo(features=self.config.features ) def __A ( self , A__ ): if not self.config.data_files: raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}""" ) A__ : int = dl_manager.download_and_extract(self.config.data_files ) if isinstance(A__ , (str, list, tuple) ): A__ : Optional[Any] = data_files if isinstance(A__ , A__ ): A__ : List[str] = [files] A__ : int = [dl_manager.iter_files(A__ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""files""": files} )] A__ : List[str] = [] for split_name, files in data_files.items(): if isinstance(A__ , A__ ): A__ : Optional[int] = [files] A__ : Optional[int] = [dl_manager.iter_files(A__ ) for file in files] splits.append(datasets.SplitGenerator(name=A__ , gen_kwargs={"""files""": files} ) ) return splits def __A ( self , A__ ): if self.config.features is not None: # adding missing columns for column_name in set(self.config.features ) - set(pa_table.column_names ): A__ : Optional[Any] = self.config.features.arrow_schema.field(A__ ).type A__ : str = pa_table.append_column(A__ , pa.array([None] * len(A__ ) , type=A__ ) ) # more expensive cast to support nested structures with keys in a different order # allows str <-> int/float or str to Audio for example A__ : Optional[int] = table_cast(A__ , self.config.features.arrow_schema ) return pa_table def __A ( self , A__ ): for file_idx, file in enumerate(itertools.chain.from_iterable(A__ ) ): # If the file is one json object and if we need to look at the list of items in one specific field if self.config.field is not None: with open(A__ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: A__ : Optional[Any] = json.load(A__ ) # We keep only the field we are interested in A__ : Optional[int] = dataset[self.config.field] # We accept two format: a list of dicts or a dict of lists if isinstance(A__ , (list, tuple) ): A__ : Union[str, Any] = set().union(*[row.keys() for row in dataset] ) A__ : Any = {col: [row.get(A__ ) for row in dataset] for col in keys} else: A__ : Any = dataset A__ : Any = pa.Table.from_pydict(A__ ) yield file_idx, self._cast_table(A__ ) # If the file has one json object per line else: with open(A__ , """rb""" ) as f: A__ : List[str] = 0 # Use block_size equal to the chunk size divided by 32 to leverage multithreading # Set a default minimum value of 16kB if the chunk size is really small A__ : List[str] = max(self.config.chunksize // 32 , 16 << 10 ) A__ : Any = ( self.config.encoding_errors if self.config.encoding_errors is not None else """strict""" ) while True: A__ : Dict = f.read(self.config.chunksize ) if not batch: break # Finish current line try: batch += f.readline() except (AttributeError, io.UnsupportedOperation): batch += readline(A__ ) # PyArrow only accepts utf-8 encoded bytes if self.config.encoding != "utf-8": A__ : List[Any] = batch.decode(self.config.encoding , errors=A__ ).encode("""utf-8""" ) try: while True: try: A__ : str = paj.read_json( io.BytesIO(A__ ) , read_options=paj.ReadOptions(block_size=A__ ) ) break except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e: if ( isinstance(A__ , pa.ArrowInvalid ) and "straddling" not in str(A__ ) or block_size > len(A__ ) ): raise else: # Increase the block size in case it was too small. # The block size will be reset for the next file. logger.debug( F"""Batch of {len(A__ )} bytes couldn't be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.""" ) block_size *= 2 except pa.ArrowInvalid as e: try: with open( A__ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: A__ : Optional[Any] = json.load(A__ ) except json.JSONDecodeError: logger.error(F"""Failed to read file '{file}' with error {type(A__ )}: {e}""" ) raise e # If possible, parse the file as a list of json objects and exit the loop if isinstance(A__ , A__ ): # list is the only sequence type supported in JSON try: A__ : str = set().union(*[row.keys() for row in dataset] ) A__ : List[str] = {col: [row.get(A__ ) for row in dataset] for col in keys} A__ : int = pa.Table.from_pydict(A__ ) except (pa.ArrowInvalid, AttributeError) as e: logger.error(F"""Failed to read file '{file}' with error {type(A__ )}: {e}""" ) raise ValueError(F"""Not able to read records in the JSON file at {file}.""" ) from None yield file_idx, self._cast_table(A__ ) break else: logger.error(F"""Failed to read file '{file}' with error {type(A__ )}: {e}""" ) raise ValueError( F"""Not able to read records in the JSON file at {file}. """ F"""You should probably indicate the field of the JSON file containing your records. """ F"""This JSON file contain the following fields: {str(list(dataset.keys() ) )}. """ F"""Select the correct one and provide it as `field='XXX'` to the dataset loading method. """ ) from None # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(A__ ) batch_idx += 1
64
0
from typing import Union import fire import torch from tqdm import tqdm def UpperCamelCase (lowercase_: str , lowercase_: Union[str, Any] = "cpu" , lowercase_: List[Any] = None ) -> List[str]: A__ : Optional[int] = torch.load(lowercase_ , map_location=lowercase_ ) for k, v in tqdm(state_dict.items() ): if not isinstance(lowercase_ , torch.Tensor ): raise TypeError("""FP16 conversion only works on paths that are saved state dicts, like pytorch_model.bin""" ) A__ : Any = v.half() if save_path is None: # overwrite src_path A__ : str = src_path torch.save(lowercase_ , lowercase_ ) if __name__ == "__main__": fire.Fire(convert)
700
import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore A_ : Dict = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" A_ : Optional[Any] = [file for file in filepaths if file != file.lower()] if upper_files: print(f'''{len(upper_files)} files contain uppercase characters:''') print('\n'.join(upper_files) + '\n') A_ : Tuple = [file for file in filepaths if ' ' in file] if space_files: print(f'''{len(space_files)} files contain space characters:''') print('\n'.join(space_files) + '\n') A_ : Any = [file for file in filepaths if '-' in file] if hyphen_files: print(f'''{len(hyphen_files)} files contain hyphen characters:''') print('\n'.join(hyphen_files) + '\n') A_ : List[str] = [file for file in filepaths if os.sep not in file] if nodir_files: print(f'''{len(nodir_files)} files are not in a directory:''') print('\n'.join(nodir_files) + '\n') A_ : Any = len(upper_files + space_files + hyphen_files + nodir_files) if bad_files: import sys sys.exit(bad_files)
64
0
from __future__ import annotations import unittest from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available from transformers.testing_utils import 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, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel @require_tf class _a : '''simple docstring''' UpperCAmelCase__: List[str] = BlenderbotSmallConfig UpperCAmelCase__: Dict = {} UpperCAmelCase__: List[str] = '''gelu''' def __init__( self , A__ , A__=13 , A__=7 , A__=True , A__=False , A__=99 , A__=32 , A__=2 , A__=4 , A__=37 , A__=0.1 , A__=0.1 , A__=20 , A__=2 , A__=1 , A__=0 , ): A__ : List[str] = parent A__ : List[Any] = batch_size A__ : Optional[Any] = seq_length A__ : Dict = is_training A__ : int = use_labels A__ : str = vocab_size A__ : Tuple = hidden_size A__ : List[Any] = num_hidden_layers A__ : Union[str, Any] = num_attention_heads A__ : Optional[int] = intermediate_size A__ : List[str] = hidden_dropout_prob A__ : List[str] = attention_probs_dropout_prob A__ : List[str] = max_position_embeddings A__ : int = eos_token_id A__ : Tuple = pad_token_id A__ : List[Any] = bos_token_id def __A ( self ): A__ : Tuple = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) A__ : str = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) A__ : List[Any] = tf.concat([input_ids, eos_tensor] , axis=1 ) A__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ : Optional[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 , ) A__ : Any = prepare_blenderbot_small_inputs_dict(lowercase__ , lowercase__ , lowercase__ ) return config, inputs_dict def __A ( self , A__ , A__ ): A__ : int = TFBlenderbotSmallModel(config=lowercase__ ).get_decoder() A__ : Union[str, Any] = inputs_dict["input_ids"] A__ : List[Any] = input_ids[:1, :] A__ : List[str] = inputs_dict["attention_mask"][:1, :] A__ : Any = inputs_dict["head_mask"] A__ : List[Any] = 1 # first forward pass A__ : Optional[int] = model(lowercase__ , attention_mask=lowercase__ , head_mask=lowercase__ , use_cache=lowercase__ ) A__ : List[str] = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids A__ : str = ids_tensor((self.batch_size, 3) , config.vocab_size ) A__ : int = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and A__ : Optional[int] = tf.concat([input_ids, next_tokens] , axis=-1 ) A__ : Optional[Any] = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) A__ : Optional[Any] = model(lowercase__ , attention_mask=lowercase__ )[0] A__ : Any = model(lowercase__ , attention_mask=lowercase__ , past_key_values=lowercase__ )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice A__ : List[str] = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) A__ : Tuple = output_from_no_past[:, -3:, random_slice_idx] A__ : Tuple = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(lowercase__ , lowercase__ , rtol=1e-3 ) def UpperCamelCase (lowercase_: List[Any] , lowercase_: Union[str, Any] , lowercase_: Union[str, Any] , lowercase_: Tuple=None , lowercase_: Tuple=None , lowercase_: Union[str, Any]=None , lowercase_: List[Any]=None , lowercase_: int=None , ) -> int: if attention_mask is None: A__ : int = tf.cast(tf.math.not_equal(SCREAMING_SNAKE_CASE_ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: A__ : Union[str, Any] = 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: A__ : Any = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: A__ : Optional[int] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: A__ : Optional[int] = 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 (_UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: Any = ( (TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else () ) UpperCAmelCase__: Dict = (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else () UpperCAmelCase__: Optional[int] = ( { '''conversational''': TFBlenderbotSmallForConditionalGeneration, '''feature-extraction''': TFBlenderbotSmallModel, '''summarization''': TFBlenderbotSmallForConditionalGeneration, '''text2text-generation''': TFBlenderbotSmallForConditionalGeneration, '''translation''': TFBlenderbotSmallForConditionalGeneration, } if is_tf_available() else {} ) UpperCAmelCase__: List[str] = True UpperCAmelCase__: Optional[Any] = False UpperCAmelCase__: Optional[int] = False def __A ( self ): A__ : str = TFBlenderbotSmallModelTester(self ) A__ : Dict = ConfigTester(self , config_class=lowercase__ ) def __A ( self ): self.config_tester.run_common_tests() def __A ( self ): A__ : int = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*lowercase__ ) @require_tokenizers @require_tf class _a (unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: str = [ '''Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like ''' ''' i\'m going to throw up.\nand why is that?''' ] UpperCAmelCase__: Tuple = '''facebook/blenderbot_small-90M''' @cached_property def __A ( self ): return BlenderbotSmallTokenizer.from_pretrained("""facebook/blenderbot-90M""" ) @cached_property def __A ( self ): A__ : str = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def __A ( self ): A__ : int = self.tokenizer(self.src_text , return_tensors="""tf""" ) A__ : str = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=lowercase__ , ) A__ : str = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=lowercase__ )[0] assert generated_words in ( "i don't know. i just feel like i'm going to throw up. it's not fun.", "i'm not sure. i just feel like i've been feeling like i have to be in a certain place", "i'm not sure. i just feel like i've been in a bad situation.", )
701
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def UpperCamelCase (*lowercase_: Optional[int] , lowercase_: Optional[Union[Dict, Any]] = None , lowercase_: Dict=True , lowercase_: Tuple=2 ) -> Dict: from .. import __version__ A__ : Dict = take_from A__ : str = () if not isinstance(args[0] , lowercase_ ): A__ : int = (args,) for attribute, version_name, message in args: if version.parse(version.parse(lowercase_ ).base_version ) >= version.parse(lowercase_ ): raise ValueError( f"""The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers'""" f""" version {__version__} is >= {version_name}""" ) A__ : Any = None if isinstance(lowercase_ , lowercase_ ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(lowercase_ ),) A__ : List[str] = f"""The `{attribute}` argument is deprecated and will be removed in version {version_name}.""" elif hasattr(lowercase_ , lowercase_ ): values += (getattr(lowercase_ , lowercase_ ),) A__ : Optional[Any] = f"""The `{attribute}` attribute is deprecated and will be removed in version {version_name}.""" elif deprecated_kwargs is None: A__ : int = f"""`{attribute}` is deprecated and will be removed in version {version_name}.""" if warning is not None: A__ : int = warning + """ """ if standard_warn else """""" warnings.warn(warning + message , lowercase_ , stacklevel=lowercase_ ) if isinstance(lowercase_ , lowercase_ ) and len(lowercase_ ) > 0: A__ : Union[str, Any] = inspect.getouterframes(inspect.currentframe() )[1] A__ : Optional[Any] = call_frame.filename A__ : Optional[int] = call_frame.lineno A__ : Any = call_frame.function A__ , A__ : List[str] = next(iter(deprecated_kwargs.items() ) ) raise TypeError(f"""{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`""" ) if len(lowercase_ ) == 0: return elif len(lowercase_ ) == 1: return values[0] return values
64
0
import collections import inspect import unittest from transformers import SwinvaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _a : '''simple docstring''' def __init__( self , A__ , A__=13 , A__=32 , A__=2 , A__=3 , A__=16 , A__=[1, 2, 1] , A__=[2, 2, 4] , A__=2 , A__=2.0 , A__=True , A__=0.0 , A__=0.0 , A__=0.1 , A__="gelu" , A__=False , A__=True , A__=0.0_2 , A__=1e-5 , A__=True , A__=None , A__=True , A__=10 , A__=8 , ): A__ : str = parent A__ : Union[str, Any] = batch_size A__ : List[str] = image_size A__ : Optional[Any] = patch_size A__ : Tuple = num_channels A__ : Optional[int] = embed_dim A__ : Tuple = depths A__ : List[str] = num_heads A__ : List[Any] = window_size A__ : Any = mlp_ratio A__ : Optional[Any] = qkv_bias A__ : Any = hidden_dropout_prob A__ : Optional[int] = attention_probs_dropout_prob A__ : int = drop_path_rate A__ : Optional[Any] = hidden_act A__ : int = use_absolute_embeddings A__ : List[str] = patch_norm A__ : Optional[int] = layer_norm_eps A__ : List[str] = initializer_range A__ : Optional[Any] = is_training A__ : List[Any] = scope A__ : Dict = use_labels A__ : List[Any] = type_sequence_label_size A__ : Optional[Any] = encoder_stride def __A ( self ): A__ : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A__ : Optional[Any] = None if self.use_labels: A__ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ : int = self.get_config() return config, pixel_values, labels def __A ( self ): return SwinvaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __A ( self , A__ , A__ , A__ ): A__ : Optional[int] = SwinvaModel(config=A__ ) model.to(A__ ) model.eval() A__ : Optional[int] = model(A__ ) A__ : str = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) A__ : Tuple = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def __A ( self , A__ , A__ , A__ ): A__ : Any = SwinvaForMaskedImageModeling(config=A__ ) model.to(A__ ) model.eval() A__ : str = model(A__ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images A__ : Any = 1 A__ : Dict = SwinvaForMaskedImageModeling(A__ ) model.to(A__ ) model.eval() A__ : Optional[int] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A__ : List[str] = model(A__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __A ( self , A__ , A__ , A__ ): A__ : str = self.type_sequence_label_size A__ : List[Any] = SwinvaForImageClassification(A__ ) model.to(A__ ) model.eval() A__ : Union[str, Any] = model(A__ , labels=A__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __A ( self ): A__ : Tuple = self.prepare_config_and_inputs() A__ : Optional[int] = config_and_inputs A__ : str = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class _a (__magic_name__ , __magic_name__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: int = ( (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else () ) UpperCAmelCase__: int = ( {'''feature-extraction''': SwinvaModel, '''image-classification''': SwinvaForImageClassification} if is_torch_available() else {} ) UpperCAmelCase__: Tuple = False UpperCAmelCase__: Any = False UpperCAmelCase__: str = False UpperCAmelCase__: Optional[Any] = False def __A ( self ): A__ : Optional[Any] = SwinvaModelTester(self ) A__ : int = ConfigTester(self , config_class=A__ , embed_dim=37 ) def __A ( self ): self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __A ( self ): A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A__ ) @unittest.skip(reason="""Got `CUDA error: misaligned address` with PyTorch 2.0.0.""" ) def __A ( self ): pass @unittest.skip(reason="""Swinv2 does not use inputs_embeds""" ) def __A ( self ): pass def __A ( self ): A__ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A__ : int = model_class(A__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) A__ : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(A__ , nn.Linear ) ) def __A ( self ): A__ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A__ : Optional[int] = model_class(A__ ) A__ : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A__ : Tuple = [*signature.parameters.keys()] A__ : Dict = ['pixel_values'] self.assertListEqual(arg_names[:1] , A__ ) def __A ( self ): A__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() A__ : Optional[int] = True for model_class in self.all_model_classes: A__ : Tuple = True A__ : str = False A__ : List[Any] = True A__ : Dict = model_class(A__ ) model.to(A__ ) model.eval() with torch.no_grad(): A__ : int = model(**self._prepare_for_class(A__ , A__ ) ) A__ : Dict = outputs.attentions A__ : Dict = len(self.model_tester.depths ) self.assertEqual(len(A__ ) , A__ ) # check that output_attentions also work using config del inputs_dict["output_attentions"] A__ : List[str] = True A__ : Optional[int] = config.window_size**2 A__ : str = model_class(A__ ) model.to(A__ ) model.eval() with torch.no_grad(): A__ : Optional[Any] = model(**self._prepare_for_class(A__ , A__ ) ) A__ : Optional[Any] = outputs.attentions self.assertEqual(len(A__ ) , A__ ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) A__ : Tuple = len(A__ ) # Check attention is always last and order is fine A__ : str = True A__ : Union[str, Any] = True A__ : str = model_class(A__ ) model.to(A__ ) model.eval() with torch.no_grad(): A__ : List[Any] = model(**self._prepare_for_class(A__ , A__ ) ) if hasattr(self.model_tester , """num_hidden_states_types""" ): A__ : Optional[Any] = self.model_tester.num_hidden_states_types else: # also another +1 for reshaped_hidden_states A__ : Any = 2 self.assertEqual(out_len + added_hidden_states , len(A__ ) ) A__ : Dict = outputs.attentions self.assertEqual(len(A__ ) , A__ ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) def __A ( self , A__ , A__ , A__ , A__ ): A__ : int = model_class(A__ ) model.to(A__ ) model.eval() with torch.no_grad(): A__ : Optional[Any] = model(**self._prepare_for_class(A__ , A__ ) ) A__ : Optional[Any] = outputs.hidden_states A__ : str = getattr( self.model_tester , """expected_num_hidden_layers""" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(A__ ) , A__ ) # Swinv2 has a different seq_length A__ : int = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) A__ : List[str] = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) A__ : Union[str, Any] = outputs.reshaped_hidden_states self.assertEqual(len(A__ ) , A__ ) A__ : Any = reshaped_hidden_states[0].shape A__ : List[str] = ( reshaped_hidden_states[0].view(A__ , A__ , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def __A ( self ): A__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() A__ : str = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: A__ : Any = True self.check_hidden_states_output(A__ , A__ , A__ , A__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] A__ : List[str] = True self.check_hidden_states_output(A__ , A__ , A__ , A__ ) def __A ( self ): A__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() A__ : Any = 3 A__ : int = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) A__ : str = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) A__ : str = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) A__ : Any = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: A__ : str = True self.check_hidden_states_output(A__ , A__ , A__ , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] A__ : Any = True self.check_hidden_states_output(A__ , A__ , A__ , (padded_height, padded_width) ) def __A ( self ): A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*A__ ) def __A ( self ): A__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A__ ) @slow def __A ( self ): for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ : List[str] = SwinvaModel.from_pretrained(A__ ) self.assertIsNotNone(A__ ) def __A ( self ): A__ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() A__ : Optional[int] = _config_zero_init(A__ ) for model_class in self.all_model_classes: A__ : int = model_class(config=A__ ) for name, param in model.named_parameters(): if "embeddings" not in name and "logit_scale" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F"""Parameter {name} of model {model_class} seems not properly initialized""" , ) @require_vision @require_torch class _a (unittest.TestCase ): '''simple docstring''' @cached_property def __A ( self ): return ( AutoImageProcessor.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256""" ) if is_vision_available() else None ) @slow def __A ( self ): A__ : Tuple = SwinvaForImageClassification.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256""" ).to( A__ ) A__ : Dict = self.default_image_processor A__ : List[str] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) A__ : Any = image_processor(images=A__ , return_tensors="""pt""" ).to(A__ ) # forward pass with torch.no_grad(): A__ : Union[str, Any] = model(**A__ ) # verify the logits A__ : List[str] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , A__ ) A__ : Optional[Any] = torch.tensor([-0.3_9_4_7, -0.4_3_0_6, 0.0_0_2_6] ).to(A__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , A__ , atol=1e-4 ) )
702
import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import ( rename_keys, ) from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME from transformers.utils.hub import convert_file_size_to_int def UpperCamelCase (lowercase_: List[str] , lowercase_: str ) -> Optional[Any]: if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer A__ : Union[str, Any] = flax_key_tuple[:-1] + ("""weight""",) A__ : Optional[int] = torch.permute(lowercase_ , (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(lowercase_ ): # linear layer A__ : Optional[Any] = flax_key_tuple[:-1] + ("""weight""",) A__ : int = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: A__ : Optional[int] = flax_key_tuple[:-1] + ("""weight""",) return flax_key_tuple, flax_tensor def UpperCamelCase (lowercase_: Tuple , lowercase_: Optional[int] , lowercase_: str ) -> Union[str, Any]: if "metadata" in layer: A__ : Tuple = layer.split("""metadata""" ) A__ : Optional[Any] = """""".join(split_layer[0] )[:-1] A__ : Optional[Any] = [tuple(("""metadata""" + split_layer[1]).split("""/""" ) )] elif "kvstore" in layer: A__ : str = layer.split("""kvstore""" ) A__ : int = """""".join(split_layer[0] )[:-1] A__ : Optional[int] = [tuple(("""kvstore""" + split_layer[1]).split("""/""" ) )] else: A__ : Any = layer.split("""/""" ) A__ : int = """/""".join(split_layer[:-1] ) A__ : str = (split_layer[-1],) if "kvstore/path" in layer: A__ : Dict = f"""{switch_checkpoint_path}/{checkpoint_info[layer]}""" elif "kvstore/driver" in layer: A__ : Optional[int] = """file""" else: A__ : str = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def UpperCamelCase (lowercase_: str , lowercase_: List[Any] ) -> int: A__ : int = rename_keys(lowercase_ ) A__ : Any = {} for k, v in current_block.items(): A__ : Dict = v A__ : str = new_current_block torch.save(lowercase_ , lowercase_ ) def UpperCamelCase (lowercase_: Dict , lowercase_: Optional[Any] , lowercase_: Optional[Any] , lowercase_: Optional[int] , lowercase_: str = WEIGHTS_NAME ) -> Tuple: A__ : Optional[int] = convert_file_size_to_int(lowercase_ ) A__ : List[Any] = [] A__ : int = {} A__ : List[str] = 0 A__ : Any = 0 os.makedirs(lowercase_ , exist_ok=lowercase_ ) with gfile.GFile(switch_checkpoint_path + """/checkpoint""" , """rb""" ) as fp: A__ : Optional[Any] = serialization.msgpack_restore(fp.read() )["""optimizer"""]["""target"""] A__ : Dict = flatten_dict(lowercase_ , sep="""/""" ) A__ : Any = {} for layer in checkpoint_info.keys(): A__ , A__ , A__ : Union[str, Any] = get_key_and_tensorstore_dict( lowercase_ , lowercase_ , lowercase_ ) if curr_real_layer_name in all_layers: A__ : Optional[int] = content else: A__ : List[Any] = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file A__ : Optional[Any] = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() A__ : List[Any] = torch.tensor(lowercase_ ) A__ : List[Any] = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts A__ , A__ : Any = rename_base_flax_keys(tuple(key.split("""/""" ) ) , lowercase_ ) A__ : Any = """/""".join(lowercase_ ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: A__ : List[Any] = os.path.join( lowercase_ , weights_name.replace(""".bin""" , f"""-{len(lowercase_ )+1:05d}-of-???.bin""" ) ) rename_and_save_block(lowercase_ , lowercase_ ) sharded_state_dicts.append(current_block.keys() ) del current_block A__ : Any = {} A__ : str = 0 A__ : List[str] = raw_weights.to(getattr(lowercase_ , lowercase_ ) ) current_block_size += weight_size total_size += weight_size # Add the last block A__ : Union[str, Any] = os.path.join(lowercase_ , weights_name.replace(""".bin""" , f"""-{len(lowercase_ )+1:05d}-of-???.bin""" ) ) rename_and_save_block(lowercase_ , lowercase_ ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(lowercase_ ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index A__ : str = {} A__ : Any = {} for idx, shard in enumerate(lowercase_ ): A__ : Any = weights_name.replace( """.bin""" , f"""-{idx+1:05d}-of-{len(lowercase_ ):05d}.bin""" ) # len(sharded_state_dicts):05d} A__ : Dict = os.path.join(lowercase_ , weights_name.replace(""".bin""" , f"""-{idx+1:05d}-of-???.bin""" ) ) os.rename(lowercase_ , os.path.join(lowercase_ , lowercase_ ) ) A__ : str = shard for key in shard: A__ : Any = shard_file # Add the metadata A__ : Tuple = {"""total_size""": total_size} A__ : Union[str, Any] = {"""metadata""": metadata, """weight_map""": weight_map} with open(os.path.join(lowercase_ , lowercase_ ) , """w""" , encoding="""utf-8""" ) as f: A__ : Dict = json.dumps(lowercase_ , indent=2 , sort_keys=lowercase_ ) + """\n""" f.write(lowercase_ ) return metadata, index if __name__ == "__main__": A_ : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--switch_t5x_checkpoint_path', default='/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600', type=str, required=False, help='Path to a directory containing a folder per layer. Follows the original Google format.', ) parser.add_argument('--max_shard_size', default='10GB', required=False, help='Max shard size') parser.add_argument('--dtype', default='bfloat16', type=str, required=False, help='dtype of the saved model') parser.add_argument( '--pytorch_dump_folder_path', default='/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted', type=str, required=False, help='Path to the output pytorch model.', ) A_ : Dict = parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def UpperCamelCase () -> int: from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer A__ : str = SwitchTransformersConfig.from_pretrained("""google/switch-base-8""" ) config.save_pretrained("""/home/arthur_huggingface_co/transformers/switch_converted""" ) A__ : str = SwitchTransformersForConditionalGeneration.from_pretrained( """/home/arthur_huggingface_co/transformers/switch_converted""" , device_map="""auto""" ) A__ : Tuple = TaTokenizer.from_pretrained("""t5-small""" ) A__ : Dict = """A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.""" A__ : Union[str, Any] = tokenizer(lowercase_ , return_tensors="""pt""" ).input_ids A__ : Tuple = model.generate(lowercase_ , decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
64
0
import warnings 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 = { 'nvidia/segformer-b0-finetuned-ade-512-512': ( 'https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json' ), # See all SegFormer models at https://huggingface.co/models?filter=segformer } class _a (__A ): '''simple docstring''' UpperCAmelCase__: Optional[int] = '''segformer''' def __init__( self , A__=3 , A__=4 , A__=[2, 2, 2, 2] , A__=[8, 4, 2, 1] , A__=[32, 64, 160, 256] , A__=[7, 3, 3, 3] , A__=[4, 2, 2, 2] , A__=[1, 2, 5, 8] , A__=[4, 4, 4, 4] , A__="gelu" , A__=0.0 , A__=0.0 , A__=0.1 , A__=0.0_2 , A__=0.1 , A__=1e-6 , A__=256 , A__=255 , **A__ , ): super().__init__(**A__ ) if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False: warnings.warn( """Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be""" """ removed, as the behaviour will default to that of reshape_last_stage = True.""" , A__ , ) A__ : Optional[int] = num_channels A__ : int = num_encoder_blocks A__ : Optional[int] = depths A__ : Optional[int] = sr_ratios A__ : int = hidden_sizes A__ : List[str] = patch_sizes A__ : Any = strides A__ : Union[str, Any] = mlp_ratios A__ : str = num_attention_heads A__ : List[str] = hidden_act A__ : Any = hidden_dropout_prob A__ : Optional[Any] = attention_probs_dropout_prob A__ : Union[str, Any] = classifier_dropout_prob A__ : Dict = initializer_range A__ : Any = drop_path_rate A__ : Dict = layer_norm_eps A__ : Optional[int] = decoder_hidden_size A__ : Any = kwargs.get("""reshape_last_stage""" , A__ ) A__ : Tuple = semantic_loss_ignore_index class _a (__A ): '''simple docstring''' UpperCAmelCase__: List[str] = version.parse('''1.11''' ) @property def __A ( self ): return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def __A ( self ): return 1e-4 @property def __A ( self ): return 12
703
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available A_ : Optional[Any] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : str = ['BartphoTokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bartpho import BartphoTokenizer else: import sys A_ : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
64
0
from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo A_ : List[str] = '\\n@misc{wu2016googles,\n title={Google\'s Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey\n and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin\n Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto\n Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and\n Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes\n and Jeffrey Dean},\n year={2016},\n eprint={1609.08144},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}\n' A_ : Optional[Any] = '\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe \'GLEU score\'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore\'s range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n' A_ : Union[str, Any] = '\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n predictions (list of str): list of translations to score.\n Each translation should be tokenized into a list of tokens.\n references (list of list of str): list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\n min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n \'google_bleu\': google_bleu score\n\nExamples:\n Example 1:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.44\n\n Example 2:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.61\n\n Example 3:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.53\n\n Example 4:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.4\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _a (datasets.Metric ): '''simple docstring''' def __A ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Sequence(datasets.Value("""string""" , id="""token""" ) , id="""sequence""" ), """references""": datasets.Sequence( datasets.Sequence(datasets.Value("""string""" , id="""token""" ) , id="""sequence""" ) , id="""references""" ), } ) , ) def __A ( self , A__ , A__ , A__ = 1 , A__ = 4 , ): return { "google_bleu": gleu_score.corpus_gleu( list_of_references=_A , hypotheses=_A , min_len=_A , max_len=_A ) }
704
import argparse import hashlib import os import urllib import warnings import torch from torch import nn from tqdm import tqdm from transformers import WhisperConfig, WhisperForConditionalGeneration A_ : Dict = { 'tiny.en': 'https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt', 'tiny': 'https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt', 'base.en': 'https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt', 'base': 'https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt', 'small.en': 'https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt', 'small': 'https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt', 'medium.en': 'https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt', 'medium': 'https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt', 'large': 'https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt', 'large-v2': 'https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt', } def UpperCamelCase (lowercase_: Optional[Any] ) -> Optional[int]: A__ : List[Any] = ["""layers""", """blocks"""] for k in ignore_keys: state_dict.pop(lowercase_ , lowercase_ ) A_ : Any = { 'blocks': 'layers', 'mlp.0': 'fc1', 'mlp.2': 'fc2', 'mlp_ln': 'final_layer_norm', '.attn.query': '.self_attn.q_proj', '.attn.key': '.self_attn.k_proj', '.attn.value': '.self_attn.v_proj', '.attn_ln': '.self_attn_layer_norm', '.attn.out': '.self_attn.out_proj', '.cross_attn.query': '.encoder_attn.q_proj', '.cross_attn.key': '.encoder_attn.k_proj', '.cross_attn.value': '.encoder_attn.v_proj', '.cross_attn_ln': '.encoder_attn_layer_norm', '.cross_attn.out': '.encoder_attn.out_proj', 'decoder.ln.': 'decoder.layer_norm.', 'encoder.ln.': 'encoder.layer_norm.', 'token_embedding': 'embed_tokens', 'encoder.positional_embedding': 'encoder.embed_positions.weight', 'decoder.positional_embedding': 'decoder.embed_positions.weight', 'ln_post': 'layer_norm', } def UpperCamelCase (lowercase_: str ) -> Any: A__ : Dict = list(s_dict.keys() ) for key in keys: A__ : List[str] = key for k, v in WHISPER_MAPPING.items(): if k in key: A__ : List[Any] = new_key.replace(lowercase_ , lowercase_ ) print(f"""{key} -> {new_key}""" ) A__ : Tuple = s_dict.pop(lowercase_ ) return s_dict def UpperCamelCase (lowercase_: Tuple ) -> Optional[int]: A__ , A__ : Any = emb.weight.shape A__ : str = nn.Linear(lowercase_ , lowercase_ , bias=lowercase_ ) A__ : Union[str, Any] = emb.weight.data return lin_layer def UpperCamelCase (lowercase_: str , lowercase_: str ) -> bytes: os.makedirs(lowercase_ , exist_ok=lowercase_ ) A__ : Tuple = os.path.basename(lowercase_ ) A__ : int = url.split("""/""" )[-2] A__ : Dict = os.path.join(lowercase_ , lowercase_ ) if os.path.exists(lowercase_ ) and not os.path.isfile(lowercase_ ): raise RuntimeError(f"""{download_target} exists and is not a regular file""" ) if os.path.isfile(lowercase_ ): A__ : Optional[Any] = open(lowercase_ , """rb""" ).read() if hashlib.shaaaa(lowercase_ ).hexdigest() == expected_shaaaa: return model_bytes else: warnings.warn(f"""{download_target} exists, but the SHA256 checksum does not match; re-downloading the file""" ) with urllib.request.urlopen(lowercase_ ) as source, open(lowercase_ , """wb""" ) as output: with tqdm( total=int(source.info().get("""Content-Length""" ) ) , ncols=80 , unit="""iB""" , unit_scale=lowercase_ , unit_divisor=1024 ) as loop: while True: A__ : Any = source.read(8192 ) if not buffer: break output.write(lowercase_ ) loop.update(len(lowercase_ ) ) A__ : Dict = open(lowercase_ , """rb""" ).read() if hashlib.shaaaa(lowercase_ ).hexdigest() != expected_shaaaa: raise RuntimeError( """Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model.""" ) return model_bytes def UpperCamelCase (lowercase_: List[Any] , lowercase_: Tuple ) -> Optional[Any]: if ".pt" not in checkpoint_path: A__ : Tuple = _download(_MODELS[checkpoint_path] ) else: A__ : Optional[int] = torch.load(lowercase_ , map_location="""cpu""" ) A__ : str = original_checkpoint["""dims"""] A__ : List[Any] = original_checkpoint["""model_state_dict"""] A__ : Optional[Any] = state_dict["""decoder.token_embedding.weight"""] remove_ignore_keys_(lowercase_ ) rename_keys(lowercase_ ) A__ : List[str] = True A__ : Optional[Any] = state_dict["""decoder.layers.0.fc1.weight"""].shape[0] A__ : List[Any] = WhisperConfig( vocab_size=dimensions["""n_vocab"""] , encoder_ffn_dim=lowercase_ , decoder_ffn_dim=lowercase_ , num_mel_bins=dimensions["""n_mels"""] , d_model=dimensions["""n_audio_state"""] , max_target_positions=dimensions["""n_text_ctx"""] , encoder_layers=dimensions["""n_audio_layer"""] , encoder_attention_heads=dimensions["""n_audio_head"""] , decoder_layers=dimensions["""n_text_layer"""] , decoder_attention_heads=dimensions["""n_text_state"""] , max_source_positions=dimensions["""n_audio_ctx"""] , ) A__ : Optional[Any] = WhisperForConditionalGeneration(lowercase_ ) A__ , A__ : List[Any] = model.model.load_state_dict(lowercase_ , strict=lowercase_ ) if len(lowercase_ ) > 0 and not set(lowercase_ ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( """Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,""" f""" but all the following weights are missing {missing}""" ) if tie_embeds: A__ : Any = make_linear_from_emb(model.model.decoder.embed_tokens ) else: A__ : str = proj_out_weights model.save_pretrained(lowercase_ ) if __name__ == "__main__": A_ : Any = argparse.ArgumentParser() # # Required parameters parser.add_argument('--checkpoint_path', type=str, help='Patht to the downloaded checkpoints') parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') A_ : Tuple = parser.parse_args() convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)
64
0
from maths.prime_check import is_prime def UpperCamelCase (lowercase_: int ) -> List[str]: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): A__ : Optional[Any] = f"""Input value of [number={number}] must be an integer""" raise TypeError(lowerCAmelCase__ ) if is_prime(lowerCAmelCase__ ) and is_prime(number + 2 ): return number + 2 else: return -1 if __name__ == "__main__": import doctest doctest.testmod()
705
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DPMSolverMultistepScheduler, TextToVideoSDPipeline, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class _a (__magic_name__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: Any = TextToVideoSDPipeline UpperCAmelCase__: Any = TEXT_TO_IMAGE_PARAMS UpperCAmelCase__: Optional[Any] = TEXT_TO_IMAGE_BATCH_PARAMS # No `output_type`. UpperCAmelCase__: Optional[int] = frozenset( [ '''num_inference_steps''', '''generator''', '''latents''', '''return_dict''', '''callback''', '''callback_steps''', ] ) def __A ( self ): torch.manual_seed(0 ) A__ : Optional[int] = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """DownBlock3D""") , up_block_types=("""UpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""") , cross_attention_dim=32 , attention_head_dim=4 , ) A__ : Optional[int] = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule="""scaled_linear""" , clip_sample=A__ , set_alpha_to_one=A__ , ) torch.manual_seed(0 ) A__ : Union[str, Any] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) A__ : Union[str, Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act="""gelu""" , projection_dim=512 , ) A__ : Union[str, Any] = CLIPTextModel(A__ ) A__ : Tuple = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) A__ : Dict = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, } return components def __A ( self , A__ , A__=0 ): if str(A__ ).startswith("""mps""" ): A__ : Tuple = torch.manual_seed(A__ ) else: A__ : List[str] = torch.Generator(device=A__ ).manual_seed(A__ ) A__ : List[str] = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """pt""", } return inputs def __A ( self ): A__ : List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator A__ : Union[str, Any] = self.get_dummy_components() A__ : Union[str, Any] = TextToVideoSDPipeline(**A__ ) A__ : int = sd_pipe.to(A__ ) sd_pipe.set_progress_bar_config(disable=A__ ) A__ : int = self.get_dummy_inputs(A__ ) A__ : int = """np""" A__ : Any = sd_pipe(**A__ ).frames A__ : Dict = frames[0][-3:, -3:, -1] assert frames[0].shape == (64, 64, 3) A__ : Optional[Any] = np.array([1_5_8.0, 1_6_0.0, 1_5_3.0, 1_2_5.0, 1_0_0.0, 1_2_1.0, 1_1_1.0, 9_3.0, 1_1_3.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __A ( self ): self._test_attention_slicing_forward_pass(test_mean_pixel_difference=A__ , expected_max_diff=3e-3 ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def __A ( self ): self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=A__ , expected_max_diff=1e-2 ) @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def __A ( self ): pass @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def __A ( self ): pass @unittest.skip(reason="""`num_images_per_prompt` argument is not supported for this pipeline.""" ) def __A ( self ): pass def __A ( self ): return super().test_progress_bar() @slow @skip_mps class _a (unittest.TestCase ): '''simple docstring''' def __A ( self ): A__ : Union[str, Any] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy""" ) A__ : Tuple = TextToVideoSDPipeline.from_pretrained("""damo-vilab/text-to-video-ms-1.7b""" ) A__ : Any = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) A__ : int = pipe.to("""cuda""" ) A__ : Optional[Any] = """Spiderman is surfing""" A__ : List[str] = torch.Generator(device="""cpu""" ).manual_seed(0 ) A__ : Optional[Any] = pipe(A__ , generator=A__ , num_inference_steps=25 , output_type="""pt""" ).frames A__ : Dict = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5e-2 def __A ( self ): A__ : List[Any] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy""" ) A__ : Optional[int] = TextToVideoSDPipeline.from_pretrained("""damo-vilab/text-to-video-ms-1.7b""" ) A__ : List[str] = pipe.to("""cuda""" ) A__ : Dict = """Spiderman is surfing""" A__ : Union[str, Any] = torch.Generator(device="""cpu""" ).manual_seed(0 ) A__ : Optional[int] = pipe(A__ , generator=A__ , num_inference_steps=2 , output_type="""pt""" ).frames A__ : Optional[int] = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5e-2
64
0
import argparse import json import gdown import numpy as np import torch from huggingface_hub import hf_hub_download from transformers import ( VideoMAEConfig, VideoMAEForPreTraining, VideoMAEForVideoClassification, VideoMAEImageProcessor, ) def UpperCamelCase ( lowercase_: int ) -> Optional[int]: A__ : List[str] = VideoMAEConfig() set_architecture_configs(lowerCAmelCase_ , lowerCAmelCase_ ) if "finetuned" not in model_name: A__ : Tuple = False if "finetuned" in model_name: A__ : Optional[int] = "huggingface/label-files" if "kinetics" in model_name: A__ : Union[str, Any] = 400 A__ : Dict = "kinetics400-id2label.json" elif "ssv2" in model_name: A__ : Optional[int] = 174 A__ : Optional[int] = "something-something-v2-id2label.json" else: raise ValueError("""Model name should either contain 'kinetics' or 'ssv2' in case it's fine-tuned.""" ) A__ : Dict = json.load(open(hf_hub_download(lowerCAmelCase_ , lowerCAmelCase_ , repo_type="""dataset""" ) , """r""" ) ) A__ : str = {int(lowerCAmelCase_ ): v for k, v in idalabel.items()} A__ : Tuple = idalabel A__ : Dict = {v: k for k, v in idalabel.items()} return config def UpperCamelCase ( lowercase_: Optional[int] , lowercase_: Optional[int] ) -> Any: if "small" in model_name: A__ : Dict = 384 A__ : Optional[int] = 1536 A__ : int = 12 A__ : Tuple = 16 A__ : List[str] = 12 A__ : Dict = 3 A__ : Dict = 192 A__ : Any = 768 elif "large" in model_name: A__ : Any = 1024 A__ : Tuple = 4096 A__ : Union[str, Any] = 24 A__ : List[str] = 16 A__ : Union[str, Any] = 12 A__ : Any = 8 A__ : Tuple = 512 A__ : str = 2048 elif "huge" in model_name: A__ : str = 1280 A__ : int = 5120 A__ : List[Any] = 32 A__ : Dict = 16 A__ : Tuple = 12 A__ : Union[str, Any] = 8 A__ : Dict = 640 A__ : Tuple = 2560 elif "base" not in model_name: raise ValueError("""Model name should include either \"small\", \"base\", \"large\", or \"huge\"""" ) def UpperCamelCase ( lowercase_: Optional[int] ) -> Optional[int]: if "encoder." in name: A__ : List[str] = name.replace("""encoder.""" , """""" ) if "cls_token" in name: A__ : List[str] = name.replace("""cls_token""" , """videomae.embeddings.cls_token""" ) if "decoder_pos_embed" in name: A__ : Optional[Any] = name.replace("""decoder_pos_embed""" , """decoder.decoder_pos_embed""" ) if "pos_embed" in name and "decoder" not in name: A__ : List[Any] = name.replace("""pos_embed""" , """videomae.embeddings.position_embeddings""" ) if "patch_embed.proj" in name: A__ : List[Any] = name.replace("""patch_embed.proj""" , """videomae.embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: A__ : Optional[int] = name.replace("""patch_embed.norm""" , """videomae.embeddings.norm""" ) if "decoder.blocks" in name: A__ : Optional[int] = name.replace("""decoder.blocks""" , """decoder.decoder_layers""" ) if "blocks" in name: A__ : Dict = name.replace("""blocks""" , """videomae.encoder.layer""" ) if "attn.proj" in name: A__ : Union[str, Any] = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name and "bias" not in name: A__ : Any = name.replace("""attn""" , """attention.self""" ) if "attn" in name: A__ : Any = name.replace("""attn""" , """attention.attention""" ) if "norm1" in name: A__ : Tuple = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: A__ : str = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: A__ : Tuple = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: A__ : Optional[int] = name.replace("""mlp.fc2""" , """output.dense""" ) if "decoder_embed" in name: A__ : Any = name.replace("""decoder_embed""" , """decoder.decoder_embed""" ) if "decoder_norm" in name: A__ : Tuple = name.replace("""decoder_norm""" , """decoder.decoder_norm""" ) if "decoder_pred" in name: A__ : List[str] = name.replace("""decoder_pred""" , """decoder.decoder_pred""" ) if "norm.weight" in name and "decoder" not in name and "fc" not in name: A__ : List[Any] = name.replace("""norm.weight""" , """videomae.layernorm.weight""" ) if "norm.bias" in name and "decoder" not in name and "fc" not in name: A__ : Optional[Any] = name.replace("""norm.bias""" , """videomae.layernorm.bias""" ) if "head" in name and "decoder" not in name: A__ : List[Any] = name.replace("""head""" , """classifier""" ) return name def UpperCamelCase ( lowercase_: Tuple , lowercase_: Optional[Any] ) -> Any: for key in orig_state_dict.copy().keys(): A__ : int = orig_state_dict.pop(lowerCAmelCase_ ) if key.startswith("""encoder.""" ): A__ : Any = key.replace("""encoder.""" , """""" ) if "qkv" in key: A__ : List[str] = key.split(""".""" ) if key.startswith("""decoder.blocks""" ): A__ : Tuple = config.decoder_hidden_size A__ : int = int(key_split[2] ) A__ : List[str] = "decoder.decoder_layers." if "weight" in key: A__ : str = val[:dim, :] A__ : List[Any] = val[dim : dim * 2, :] A__ : Union[str, Any] = val[-dim:, :] else: A__ : Union[str, Any] = config.hidden_size A__ : Any = int(key_split[1] ) A__ : List[Any] = "videomae.encoder.layer." if "weight" in key: A__ : Optional[int] = val[:dim, :] A__ : Dict = val[dim : dim * 2, :] A__ : List[Any] = val[-dim:, :] else: A__ : Dict = val return orig_state_dict def UpperCamelCase ( ) -> Optional[int]: A__ : Optional[int] = hf_hub_download( repo_id="""hf-internal-testing/spaghetti-video""" , filename="""eating_spaghetti.npy""" , repo_type="""dataset""" ) A__ : Union[str, Any] = np.load(lowerCAmelCase_ ) return list(lowerCAmelCase_ ) def UpperCamelCase ( lowercase_: int , lowercase_: Tuple , lowercase_: Dict , lowercase_: Dict ) -> List[str]: A__ : Any = get_videomae_config(lowerCAmelCase_ ) if "finetuned" in model_name: A__ : Optional[Any] = VideoMAEForVideoClassification(lowerCAmelCase_ ) else: A__ : Union[str, Any] = VideoMAEForPreTraining(lowerCAmelCase_ ) # download original checkpoint, hosted on Google Drive A__ : Tuple = "pytorch_model.bin" gdown.cached_download(lowerCAmelCase_ , lowerCAmelCase_ , quiet=lowerCAmelCase_ ) A__ : Optional[Any] = torch.load(lowerCAmelCase_ , map_location="""cpu""" ) if "model" in files: A__ : Dict = files["model"] else: A__ : Optional[Any] = files["module"] A__ : Optional[int] = convert_state_dict(lowerCAmelCase_ , lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) model.eval() # verify model on basic input A__ : List[Any] = VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) A__ : Any = prepare_video() A__ : Optional[Any] = image_processor(lowerCAmelCase_ , return_tensors="""pt""" ) if "finetuned" not in model_name: A__ : Union[str, Any] = hf_hub_download(repo_id="""hf-internal-testing/bool-masked-pos""" , filename="""bool_masked_pos.pt""" ) A__ : Union[str, Any] = torch.load(lowerCAmelCase_ ) A__ : str = model(**lowerCAmelCase_ ) A__ : List[str] = outputs.logits A__ : List[Any] = [ "videomae-small-finetuned-kinetics", "videomae-small-finetuned-ssv2", # Kinetics-400 checkpoints (short = pretrained only for 800 epochs instead of 1600) "videomae-base-short", "videomae-base-short-finetuned-kinetics", "videomae-base", "videomae-base-finetuned-kinetics", "videomae-large", "videomae-large-finetuned-kinetics", "videomae-huge-finetuned-kinetics", # Something-Something-v2 checkpoints (short = pretrained only for 800 epochs instead of 2400) "videomae-base-short-ssv2", "videomae-base-short-finetuned-ssv2", "videomae-base-ssv2", "videomae-base-finetuned-ssv2", ] # NOTE: logits were tested with image_mean and image_std equal to [0.5, 0.5, 0.5] and [0.5, 0.5, 0.5] if model_name == "videomae-small-finetuned-kinetics": A__ : str = torch.Size([1, 400] ) A__ : List[Any] = torch.tensor([-0.9291, -0.4061, -0.9307] ) elif model_name == "videomae-small-finetuned-ssv2": A__ : str = torch.Size([1, 174] ) A__ : Optional[int] = torch.tensor([0.2671, -0.4689, -0.8235] ) elif model_name == "videomae-base": A__ : List[Any] = torch.Size([1, 1408, 1536] ) A__ : Optional[int] = torch.tensor([[0.7739, 0.7968, 0.7089], [0.6701, 0.7487, 0.6209], [0.4287, 0.5158, 0.4773]] ) elif model_name == "videomae-base-short": A__ : Union[str, Any] = torch.Size([1, 1408, 1536] ) A__ : Any = torch.tensor([[0.7994, 0.9612, 0.8508], [0.7401, 0.8958, 0.8302], [0.5862, 0.7468, 0.7325]] ) # we verified the loss both for normalized and unnormalized targets for this one A__ : Any = torch.tensor([0.5142] ) if config.norm_pix_loss else torch.tensor([0.6469] ) elif model_name == "videomae-large": A__ : Dict = torch.Size([1, 1408, 1536] ) A__ : str = torch.tensor([[0.7149, 0.7997, 0.6966], [0.6768, 0.7869, 0.6948], [0.5139, 0.6221, 0.5605]] ) elif model_name == "videomae-large-finetuned-kinetics": A__ : int = torch.Size([1, 400] ) A__ : Optional[Any] = torch.tensor([0.0771, 0.0011, -0.3625] ) elif model_name == "videomae-huge-finetuned-kinetics": A__ : Union[str, Any] = torch.Size([1, 400] ) A__ : Optional[Any] = torch.tensor([0.2433, 0.1632, -0.4894] ) elif model_name == "videomae-base-short-finetuned-kinetics": A__ : Tuple = torch.Size([1, 400] ) A__ : Tuple = torch.tensor([0.6588, 0.0990, -0.2493] ) elif model_name == "videomae-base-finetuned-kinetics": A__ : Optional[Any] = torch.Size([1, 400] ) A__ : Optional[Any] = torch.tensor([0.3669, -0.0688, -0.2421] ) elif model_name == "videomae-base-short-ssv2": A__ : List[str] = torch.Size([1, 1408, 1536] ) A__ : Optional[Any] = torch.tensor([[0.4712, 0.5296, 0.5786], [0.2278, 0.2729, 0.4026], [0.0352, 0.0730, 0.2506]] ) elif model_name == "videomae-base-short-finetuned-ssv2": A__ : Dict = torch.Size([1, 174] ) A__ : Tuple = torch.tensor([-0.0537, -0.1539, -0.3266] ) elif model_name == "videomae-base-ssv2": A__ : Union[str, Any] = torch.Size([1, 1408, 1536] ) A__ : Any = torch.tensor([[0.8131, 0.8727, 0.8546], [0.7366, 0.9377, 0.8870], [0.5935, 0.8874, 0.8564]] ) elif model_name == "videomae-base-finetuned-ssv2": A__ : Optional[int] = torch.Size([1, 174] ) A__ : List[Any] = torch.tensor([0.1961, -0.8337, -0.6389] ) else: raise ValueError(f"""Model name not supported. Should be one of {model_names}""" ) # verify logits assert logits.shape == expected_shape if "finetuned" in model_name: assert torch.allclose(logits[0, :3] , lowerCAmelCase_ , atol=1E-4 ) else: print("""Logits:""" , logits[0, :3, :3] ) assert torch.allclose(logits[0, :3, :3] , lowerCAmelCase_ , atol=1E-4 ) print("""Logits ok!""" ) # verify loss, if applicable if model_name == "videomae-base-short": A__ : Dict = outputs.loss assert torch.allclose(lowerCAmelCase_ , lowerCAmelCase_ , atol=1E-4 ) print("""Loss ok!""" ) if pytorch_dump_folder_path is not None: print(f"""Saving model and image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) if push_to_hub: print("""Pushing to the hub...""" ) model.push_to_hub(lowerCAmelCase_ , organization="""nielsr""" ) if __name__ == "__main__": A_ : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint_url', default='https://drive.google.com/u/1/uc?id=1tEhLyskjb755TJ65ptsrafUG2llSwQE1&amp;export=download&amp;confirm=t&amp;uuid=aa3276eb-fb7e-482a-adec-dc7171df14c4', type=str, help=( 'URL of the original PyTorch checkpoint (on Google Drive) you\'d like to convert. Should be a direct' ' download link.' ), ) parser.add_argument( '--pytorch_dump_folder_path', default='/Users/nielsrogge/Documents/VideoMAE/Test', type=str, help='Path to the output PyTorch model directory.', ) parser.add_argument('--model_name', default='videomae-base', type=str, help='Name of the model.') parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) A_ : Optional[int] = parser.parse_args() convert_videomae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)
706
def UpperCamelCase (lowercase_: int ) -> int: if not isinstance(lowercase_ , lowercase_ ): raise TypeError("""Input value must be an 'int' type""" ) A__ : int = 0 while number: position += 1 number >>= 1 return position if __name__ == "__main__": import doctest doctest.testmod()
64
0
import math def UpperCamelCase (lowercase_: Dict ) -> List[str]: A__ : Any = 0 A__ : List[Any] = 0 while num > 0: A__ : Union[str, Any] = num % 8 A__ : Tuple = octal + (remainder * math.floor(math.pow(10 , _snake_case ) )) counter += 1 A__ : Union[str, Any] = math.floor(num / 8 ) # basically /= 8 without remainder if any # This formatting removes trailing '.0' from `octal`. return f"""0o{int(_snake_case )}""" def UpperCamelCase () -> Dict: print("""\n2 in octal is:""" ) print(decimal_to_octal(2 ) ) # = 2 print("""\n8 in octal is:""" ) print(decimal_to_octal(8 ) ) # = 10 print("""\n65 in octal is:""" ) print(decimal_to_octal(65 ) ) # = 101 print("""\n216 in octal is:""" ) print(decimal_to_octal(216 ) ) # = 330 print("""\n512 in octal is:""" ) print(decimal_to_octal(512 ) ) # = 1000 print("""\n""" ) if __name__ == "__main__": main()
707
from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def UpperCamelCase (lowercase_: np.ndarray , lowercase_: np.ndarray , lowercase_: np.ndarray , lowercase_: int , lowercase_: int ) -> np.ndarray: A__ : Any = cva.getAffineTransform(lowercase_ , lowercase_ ) return cva.warpAffine(lowercase_ , lowercase_ , (rows, cols) ) if __name__ == "__main__": # read original image A_ : List[Any] = cva.imread( str(Path(__file__).resolve().parent.parent / 'image_data' / 'lena.jpg') ) # turn image in gray scale value A_ : List[Any] = cva.cvtColor(image, cva.COLOR_BGR2GRAY) # get image shape A_ , A_ : Optional[Any] = gray_img.shape # set different points to rotate image A_ : str = np.array([[50, 50], [200, 50], [50, 200]], np.floataa) A_ : Dict = np.array([[10, 100], [200, 50], [100, 250]], np.floataa) A_ : Optional[int] = np.array([[50, 50], [150, 50], [120, 200]], np.floataa) A_ : Optional[int] = np.array([[10, 100], [80, 50], [180, 250]], np.floataa) # add all rotated images in a list A_ : Dict = [ 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_ : Union[str, Any] = plt.figure(1) A_ : Union[str, Any] = ['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()
64
0
def UpperCamelCase (lowercase_: list ) -> list: if len(_A ) <= 1: return [tuple(_A )] A__ : Union[str, Any] = [] def generate(lowercase_: int , lowercase_: list ): A__ : Optional[Any] = [0] * n res.append(tuple(_A ) ) A__ : int = 0 while i < n: if c[i] < i: if i % 2 == 0: A__ , A__ : Union[str, Any] = arr[i], arr[0] else: A__ , A__ : int = arr[i], arr[c[i]] res.append(tuple(_A ) ) c[i] += 1 A__ : List[str] = 0 else: A__ : Dict = 0 i += 1 generate(len(_A ) , _A ) return res if __name__ == "__main__": A_ = input('Enter numbers separated by a comma:\n').strip() A_ = [int(item) for item in user_input.split(',')] print(heaps(arr))
708
import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class _a (unittest.TestCase ): '''simple docstring''' def __A ( self , A__ ): for model_result in results.values(): for batch_size, sequence_length in zip(model_result["""bs"""] , model_result["""ss"""] ): A__ : str = model_result["""result"""][batch_size][sequence_length] self.assertIsNotNone(A__ ) def __A ( self ): A__ : Dict = """sshleifer/tiny-gpt2""" A__ : Tuple = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : int = PyTorchBenchmark(A__ ) A__ : List[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ): A__ : Dict = """sgugger/tiny-distilbert-classification""" A__ : Dict = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , only_pretrain_model=A__ , ) A__ : str = PyTorchBenchmark(A__ ) A__ : List[str] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ): A__ : Any = """sshleifer/tiny-gpt2""" A__ : List[Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , torchscript=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : Tuple = PyTorchBenchmark(A__ ) A__ : str = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == """cpu""" , """Cant do half precision""" ) def __A ( self ): A__ : Optional[Any] = """sshleifer/tiny-gpt2""" A__ : Optional[Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , fpaa=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : str = PyTorchBenchmark(A__ ) A__ : Any = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ): A__ : Optional[Any] = """sshleifer/tiny-gpt2""" A__ : Tuple = AutoConfig.from_pretrained(A__ ) # set architectures equal to `None` A__ : List[Any] = None A__ : str = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : List[str] = PyTorchBenchmark(A__ , configs=[config] ) A__ : Any = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ): A__ : Optional[int] = """sshleifer/tiny-gpt2""" A__ : Optional[int] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : Any = PyTorchBenchmark(A__ ) A__ : Dict = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == """cpu""" , """Can't do half precision""" ) def __A ( self ): A__ : Optional[int] = """sshleifer/tiny-gpt2""" A__ : List[str] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , fpaa=A__ , multi_process=A__ , ) A__ : Dict = PyTorchBenchmark(A__ ) A__ : Optional[int] = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __A ( self ): A__ : int = """sshleifer/tiny-gpt2""" A__ : Optional[int] = AutoConfig.from_pretrained(A__ ) A__ : str = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : int = PyTorchBenchmark(A__ , configs=[config] ) A__ : Tuple = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ): A__ : List[str] = """sshleifer/tinier_bart""" A__ : List[str] = AutoConfig.from_pretrained(A__ ) A__ : List[str] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : Union[str, Any] = PyTorchBenchmark(A__ , configs=[config] ) A__ : str = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ): A__ : Optional[int] = """sshleifer/tiny-gpt2""" A__ : Union[str, Any] = AutoConfig.from_pretrained(A__ ) A__ : Tuple = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : int = PyTorchBenchmark(A__ , configs=[config] ) A__ : Tuple = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __A ( self ): A__ : Dict = """sshleifer/tinier_bart""" A__ : int = AutoConfig.from_pretrained(A__ ) A__ : Union[str, Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : List[Any] = PyTorchBenchmark(A__ , configs=[config] ) A__ : Optional[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __A ( self ): A__ : int = """sshleifer/tiny-gpt2""" with tempfile.TemporaryDirectory() as tmp_dir: A__ : Dict = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , save_to_csv=A__ , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(A__ , """inf_time.csv""" ) , train_memory_csv_file=os.path.join(A__ , """train_mem.csv""" ) , inference_memory_csv_file=os.path.join(A__ , """inf_mem.csv""" ) , train_time_csv_file=os.path.join(A__ , """train_time.csv""" ) , env_info_csv_file=os.path.join(A__ , """env.csv""" ) , multi_process=A__ , ) A__ : Optional[Any] = PyTorchBenchmark(A__ ) benchmark.run() self.assertTrue(Path(os.path.join(A__ , """inf_time.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(A__ , """train_time.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(A__ , """inf_mem.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(A__ , """train_mem.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(A__ , """env.csv""" ) ).exists() ) def __A ( self ): A__ : Optional[int] = """sshleifer/tiny-gpt2""" def _check_summary_is_not_empty(A__ ): self.assertTrue(hasattr(A__ , """sequential""" ) ) self.assertTrue(hasattr(A__ , """cumulative""" ) ) self.assertTrue(hasattr(A__ , """current""" ) ) self.assertTrue(hasattr(A__ , """total""" ) ) with tempfile.TemporaryDirectory() as tmp_dir: A__ : Dict = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(A__ , """log.txt""" ) , log_print=A__ , trace_memory_line_by_line=A__ , multi_process=A__ , ) A__ : Dict = PyTorchBenchmark(A__ ) A__ : str = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(A__ , """log.txt""" ) ).exists() )
64
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available A_ : str = { 'configuration_chinese_clip': [ 'CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ChineseCLIPConfig', 'ChineseCLIPOnnxConfig', 'ChineseCLIPTextConfig', 'ChineseCLIPVisionConfig', ], 'processing_chinese_clip': ['ChineseCLIPProcessor'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Optional[Any] = ['ChineseCLIPFeatureExtractor'] A_ : int = ['ChineseCLIPImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : List[Any] = [ 'CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST', 'ChineseCLIPModel', 'ChineseCLIPPreTrainedModel', 'ChineseCLIPTextModel', 'ChineseCLIPVisionModel', ] if TYPE_CHECKING: from .configuration_chinese_clip import ( CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, ChineseCLIPConfig, ChineseCLIPOnnxConfig, ChineseCLIPTextConfig, ChineseCLIPVisionConfig, ) from .processing_chinese_clip import ChineseCLIPProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_chinese_clip import ChineseCLIPFeatureExtractor, ChineseCLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_chinese_clip import ( CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, ChineseCLIPModel, ChineseCLIPPreTrainedModel, ChineseCLIPTextModel, ChineseCLIPVisionModel, ) else: import sys A_ : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
709
# tests directory-specific settings - this file is run automatically # by pytest before any tests are run import doctest import sys import warnings from os.path import abspath, dirname, join import _pytest from transformers.testing_utils import HfDoctestModule, HfDocTestParser # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. A_ : Optional[int] = abspath(join(dirname(__file__), 'src')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='ignore', category=FutureWarning) def UpperCamelCase (lowercase_: List[str] ) -> Any: config.addinivalue_line( """markers""" , """is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested""" ) config.addinivalue_line( """markers""" , """is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested""" ) config.addinivalue_line("""markers""" , """is_pipeline_test: mark test to run only when pipelines are tested""" ) config.addinivalue_line("""markers""" , """is_staging_test: mark test to run only in the staging environment""" ) config.addinivalue_line("""markers""" , """accelerate_tests: mark test that require accelerate""" ) config.addinivalue_line("""markers""" , """tool_tests: mark the tool tests that are run on their specific schedule""" ) def UpperCamelCase (lowercase_: Optional[int] ) -> Optional[Any]: from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(lowercase_ ) def UpperCamelCase (lowercase_: List[str] ) -> Optional[Any]: from transformers.testing_utils import pytest_terminal_summary_main A__ : List[Any] = terminalreporter.config.getoption("""--make-reports""" ) if make_reports: pytest_terminal_summary_main(lowercase_ , id=lowercase_ ) def UpperCamelCase (lowercase_: Union[str, Any] , lowercase_: int ) -> List[str]: # If no tests are collected, pytest exists with code 5, which makes the CI fail. if exitstatus == 5: A__ : Tuple = 0 # Doctest custom flag to ignore output. A_ : Tuple = doctest.register_optionflag('IGNORE_RESULT') A_ : Dict = doctest.OutputChecker class _a (__magic_name__ ): '''simple docstring''' def __A ( self , A__ , A__ , A__ ): if IGNORE_RESULT & optionflags: return True return OutputChecker.check_output(self , A__ , A__ , A__ ) A_ : str = CustomOutputChecker A_ : Dict = HfDoctestModule A_ : Optional[int] = HfDocTestParser
64
0
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST, OpenAIGPTConfig, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification, OpenAIGPTLMHeadModel, OpenAIGPTModel, ) class _a : '''simple docstring''' def __init__( self , A__ , A__=13 , A__=7 , A__=True , A__=True , A__=True , A__=99 , A__=32 , A__=5 , A__=4 , A__=37 , A__="gelu" , A__=0.1 , A__=0.1 , A__=512 , A__=16 , A__=2 , A__=0.0_2 , A__=3 , A__=4 , A__=None , ): A__ : List[str] = parent A__ : Optional[Any] = batch_size A__ : Any = seq_length A__ : int = is_training A__ : Dict = use_token_type_ids A__ : Dict = use_labels A__ : Dict = vocab_size A__ : List[Any] = hidden_size A__ : Optional[Any] = num_hidden_layers A__ : Dict = num_attention_heads A__ : Optional[int] = intermediate_size A__ : List[Any] = hidden_act A__ : str = hidden_dropout_prob A__ : Optional[Any] = attention_probs_dropout_prob A__ : List[str] = max_position_embeddings A__ : List[str] = type_vocab_size A__ : Union[str, Any] = type_sequence_label_size A__ : Union[str, Any] = initializer_range A__ : Union[str, Any] = num_labels A__ : Tuple = num_choices A__ : Union[str, Any] = scope A__ : List[Any] = self.vocab_size - 1 def __A ( self ): A__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ : Any = None if self.use_token_type_ids: A__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) A__ : str = None A__ : Union[str, Any] = None A__ : Tuple = None if self.use_labels: A__ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ : str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A__ : Optional[int] = ids_tensor([self.batch_size] , self.num_choices ) A__ : Tuple = OpenAIGPTConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) A__ : Dict = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, head_mask, token_type_ids, sequence_labels, token_labels, choice_labels, ) def __A ( self , A__ , A__ , A__ , A__ , *A__ ): A__ : Any = OpenAIGPTModel(config=_A ) model.to(_A ) model.eval() A__ : Optional[Any] = model(_A , token_type_ids=_A , head_mask=_A ) A__ : Tuple = model(_A , token_type_ids=_A ) A__ : Optional[Any] = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __A ( self , A__ , A__ , A__ , A__ , *A__ ): A__ : Dict = OpenAIGPTLMHeadModel(_A ) model.to(_A ) model.eval() A__ : Union[str, Any] = model(_A , token_type_ids=_A , labels=_A ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __A ( self , A__ , A__ , A__ , A__ , *A__ ): A__ : Optional[Any] = OpenAIGPTDoubleHeadsModel(_A ) model.to(_A ) model.eval() A__ : Optional[Any] = model(_A , token_type_ids=_A , labels=_A ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __A ( self , A__ , A__ , A__ , A__ , *A__ ): A__ : List[str] = self.num_labels A__ : Any = OpenAIGPTForSequenceClassification(_A ) model.to(_A ) model.eval() A__ : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ : Dict = model(_A , token_type_ids=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __A ( self ): A__ : List[str] = self.prepare_config_and_inputs() ( A__ ) : Optional[Any] = config_and_inputs A__ : int = { 'input_ids': input_ids, 'token_type_ids': token_type_ids, 'head_mask': head_mask, } return config, inputs_dict @require_torch class _a (snake_case__ , snake_case__ , snake_case__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: Tuple = ( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) UpperCAmelCase__: Optional[int] = ( (OpenAIGPTLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly UpperCAmelCase__: str = ( { '''feature-extraction''': OpenAIGPTModel, '''text-classification''': OpenAIGPTForSequenceClassification, '''text-generation''': OpenAIGPTLMHeadModel, '''zero-shot''': OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) def __A ( self , A__ , A__ , A__ , A__ , A__ ): if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a # tiny config could not be created. return True return False def __A ( self , A__ , A__ , A__=False ): A__ : int = super()._prepare_for_class(_A , _A , return_labels=_A ) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": A__ : Optional[Any] = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) , dtype=torch.long , device=_A , ) A__ : Union[str, Any] = inputs_dict['labels'] A__ : Tuple = inputs_dict['labels'] A__ : List[str] = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices) , dtype=torch.long , device=_A , ) A__ : List[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_A ) return inputs_dict def __A ( self ): A__ : int = OpenAIGPTModelTester(self ) A__ : Union[str, Any] = ConfigTester(self , config_class=_A , n_embd=37 ) def __A ( self ): self.config_tester.run_common_tests() def __A ( self ): A__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*_A ) def __A ( self ): A__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*_A ) def __A ( self ): A__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*_A ) def __A ( self ): A__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*_A ) @slow def __A ( self ): for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ : Optional[int] = OpenAIGPTModel.from_pretrained(_A ) self.assertIsNotNone(_A ) @require_torch class _a (unittest.TestCase ): '''simple docstring''' @slow def __A ( self ): A__ : str = OpenAIGPTLMHeadModel.from_pretrained("""openai-gpt""" ) model.to(_A ) A__ : Dict = torch.tensor([[481, 4735, 544]] , dtype=torch.long , device=_A ) # the president is A__ : int = [ 481, 4735, 544, 246, 963, 870, 762, 239, 244, 4_0477, 244, 249, 719, 881, 487, 544, 240, 244, 603, 481, ] # the president is a very good man. " \n " i\'m sure he is, " said the A__ : Union[str, Any] = model.generate(_A , do_sample=_A ) self.assertListEqual(output_ids[0].tolist() , _A )
710
from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, 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, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class _a : '''simple docstring''' UpperCAmelCase__: List[Any] = PegasusConfig UpperCAmelCase__: Optional[int] = {} UpperCAmelCase__: List[str] = '''gelu''' def __init__( self , A__ , A__=13 , A__=7 , A__=True , A__=False , A__=99 , A__=32 , A__=2 , A__=4 , A__=37 , A__=0.1 , A__=0.1 , A__=40 , A__=2 , A__=1 , A__=0 , ): A__ : Dict = parent A__ : Dict = batch_size A__ : Any = seq_length A__ : Optional[Any] = is_training A__ : int = use_labels A__ : Any = vocab_size A__ : Union[str, Any] = hidden_size A__ : Tuple = num_hidden_layers A__ : Tuple = num_attention_heads A__ : List[Any] = intermediate_size A__ : Union[str, Any] = hidden_dropout_prob A__ : Optional[Any] = attention_probs_dropout_prob A__ : List[Any] = max_position_embeddings A__ : Any = eos_token_id A__ : List[Any] = pad_token_id A__ : List[Any] = bos_token_id def __A ( self ): A__ : str = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) A__ : Dict = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) A__ : List[Any] = tf.concat([input_ids, eos_tensor] , axis=1 ) A__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ : Tuple = 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 , ) A__ : str = prepare_pegasus_inputs_dict(A__ , A__ , A__ ) return config, inputs_dict def __A ( self , A__ , A__ ): A__ : int = TFPegasusModel(config=A__ ).get_decoder() A__ : List[Any] = inputs_dict["""input_ids"""] A__ : Any = input_ids[:1, :] A__ : Optional[Any] = inputs_dict["""attention_mask"""][:1, :] A__ : Optional[int] = inputs_dict["""head_mask"""] A__ : Any = 1 # first forward pass A__ : Tuple = model(A__ , attention_mask=A__ , head_mask=A__ , use_cache=A__ ) A__ , A__ : Dict = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids A__ : Tuple = ids_tensor((self.batch_size, 3) , config.vocab_size ) A__ : Optional[Any] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and A__ : List[Any] = tf.concat([input_ids, next_tokens] , axis=-1 ) A__ : Tuple = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) A__ : Optional[Any] = model(A__ , attention_mask=A__ )[0] A__ : Any = model(A__ , attention_mask=A__ , past_key_values=A__ )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice A__ : int = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) A__ : Any = output_from_no_past[:, -3:, random_slice_idx] A__ : Tuple = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(A__ , A__ , rtol=1e-3 ) def UpperCamelCase (lowercase_: Union[str, Any] , lowercase_: Dict , lowercase_: List[Any] , lowercase_: Dict=None , lowercase_: int=None , lowercase_: List[Any]=None , lowercase_: List[Any]=None , lowercase_: str=None , ) -> int: if attention_mask is None: A__ : List[str] = tf.cast(tf.math.not_equal(lowercase_ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: A__ : Dict = 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: A__ : Any = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: A__ : Tuple = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: A__ : List[str] = 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 (__magic_name__ , __magic_name__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: List[Any] = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () UpperCAmelCase__: Tuple = (TFPegasusForConditionalGeneration,) if is_tf_available() else () UpperCAmelCase__: Tuple = ( { '''conversational''': TFPegasusForConditionalGeneration, '''feature-extraction''': TFPegasusModel, '''summarization''': TFPegasusForConditionalGeneration, '''text2text-generation''': TFPegasusForConditionalGeneration, '''translation''': TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) UpperCAmelCase__: int = True UpperCAmelCase__: Union[str, Any] = False UpperCAmelCase__: List[str] = False def __A ( self ): A__ : Optional[Any] = TFPegasusModelTester(self ) A__ : Tuple = ConfigTester(self , config_class=A__ ) def __A ( self ): self.config_tester.run_common_tests() def __A ( self ): A__ : int = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*A__ ) @require_sentencepiece @require_tokenizers @require_tf class _a (unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: Optional[int] = [ ''' 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!" ''', ] UpperCAmelCase__: Any = [ '''California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to''' ''' reduce the risk of wildfires.''', '''N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.''', ] # differs slightly from pytorch, likely due to numerical differences in linear layers UpperCAmelCase__: List[str] = '''google/pegasus-xsum''' @cached_property def __A ( self ): return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def __A ( self ): A__ : int = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def __A ( self , **A__ ): A__ : str = self.translate_src_text(**A__ ) assert self.expected_text == generated_words def __A ( self , **A__ ): A__ : List[str] = self.tokenizer(self.src_text , **A__ , padding=A__ , return_tensors="""tf""" ) A__ : Optional[int] = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=A__ , ) A__ : Dict = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=A__ ) return generated_words @slow def __A ( self ): self._assert_generated_batch_equal_expected()
64
0
from typing import Any import numpy as np def UpperCamelCase (lowercase_: Dict ) -> bool: return np.array_equal(__snake_case , matrix.conjugate().T ) def UpperCamelCase (lowercase_: Any , lowercase_: Optional[Any] ) -> Any: A__ : Optional[int] = v.conjugate().T A__ : Any = v_star.dot(__snake_case ) assert isinstance(__snake_case , np.ndarray ) return (v_star_dot.dot(__snake_case )) / (v_star.dot(__snake_case )) def UpperCamelCase () -> None: A__ : Tuple = np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]] ) A__ : Tuple = np.array([[1], [2], [3]] ) assert is_hermitian(__snake_case ), f"""{a} is not hermitian.""" print(rayleigh_quotient(__snake_case , __snake_case ) ) A__ : str = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]] ) assert is_hermitian(__snake_case ), f"""{a} is not hermitian.""" assert rayleigh_quotient(__snake_case , __snake_case ) == float(3 ) if __name__ == "__main__": import doctest doctest.testmod() tests()
711
class _a : '''simple docstring''' def __init__( self ): A__ : str = """""" A__ : Any = """""" A__ : List[Any] = [] def __A ( self , A__ , A__ ): if m == -1: return n + 1 elif n == -1: return m + 1 elif self.dp[m][n] > -1: return self.dp[m][n] else: if self.worda[m] == self.worda[n]: A__ : Optional[Any] = self.__min_dist_top_down_dp(m - 1 , n - 1 ) else: A__ : Union[str, Any] = self.__min_dist_top_down_dp(A__ , n - 1 ) A__ : Union[str, Any] = self.__min_dist_top_down_dp(m - 1 , A__ ) A__ : Union[str, Any] = self.__min_dist_top_down_dp(m - 1 , n - 1 ) A__ : List[Any] = 1 + min(A__ , A__ , A__ ) return self.dp[m][n] def __A ( self , A__ , A__ ): A__ : Tuple = worda A__ : Dict = worda A__ : Optional[Any] = [[-1 for _ in range(len(A__ ) )] for _ in range(len(A__ ) )] return self.__min_dist_top_down_dp(len(A__ ) - 1 , len(A__ ) - 1 ) def __A ( self , A__ , A__ ): A__ : Optional[Any] = worda A__ : Dict = worda A__ : Union[str, Any] = len(A__ ) A__ : List[str] = len(A__ ) A__ : int = [[0 for _ in range(n + 1 )] for _ in range(m + 1 )] for i in range(m + 1 ): for j in range(n + 1 ): if i == 0: # first string is empty A__ : Tuple = j elif j == 0: # second string is empty A__ : Dict = i elif worda[i - 1] == worda[j - 1]: # last characters are equal A__ : str = self.dp[i - 1][j - 1] else: A__ : Union[str, Any] = self.dp[i][j - 1] A__ : str = self.dp[i - 1][j] A__ : Union[str, Any] = self.dp[i - 1][j - 1] A__ : Tuple = 1 + min(A__ , A__ , A__ ) return self.dp[m][n] if __name__ == "__main__": A_ : Union[str, Any] = EditDistance() print('****************** Testing Edit Distance DP Algorithm ******************') print() A_ : int = input('Enter the first string: ').strip() A_ : List[str] = input('Enter the second string: ').strip() print() print(f'''The minimum edit distance is: {solver.min_dist_top_down(Sa, Sa)}''') print(f'''The minimum edit distance is: {solver.min_dist_bottom_up(Sa, Sa)}''') print() print('*************** End of Testing Edit Distance DP Algorithm ***************')
64
0
import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class _a (lowercase_ ): '''simple docstring''' UpperCAmelCase__: List[str] = (DEISMultistepScheduler,) UpperCAmelCase__: Tuple = (('''num_inference_steps''', 25),) def __A ( self , **A__ ): A__ : Dict = { """num_train_timesteps""": 1000, """beta_start""": 0.0_0_0_1, """beta_end""": 0.0_2, """beta_schedule""": """linear""", """solver_order""": 2, } config.update(**lowerCamelCase_ ) return config def __A ( self , A__=0 , **A__ ): A__ : Any = dict(self.forward_default_kwargs ) A__ : List[str] = kwargs.pop("""num_inference_steps""" , lowerCamelCase_ ) A__ : Dict = self.dummy_sample A__ : Any = 0.1 * sample A__ : str = [residual + 0.2, residual + 0.1_5, residual + 0.1_0] for scheduler_class in self.scheduler_classes: A__ : int = self.get_scheduler_config(**lowerCamelCase_ ) A__ : Optional[int] = scheduler_class(**lowerCamelCase_ ) scheduler.set_timesteps(lowerCamelCase_ ) # copy over dummy past residuals A__ : Optional[Any] = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowerCamelCase_ ) A__ : Optional[int] = scheduler_class.from_pretrained(lowerCamelCase_ ) new_scheduler.set_timesteps(lowerCamelCase_ ) # copy over dummy past residuals A__ : List[str] = dummy_past_residuals[: new_scheduler.config.solver_order] A__ : str = sample, sample for t in range(lowerCamelCase_ , time_step + scheduler.config.solver_order + 1 ): A__ : Tuple = scheduler.step(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ).prev_sample A__ : Optional[int] = new_scheduler.step(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def __A ( self ): pass def __A ( self , A__=0 , **A__ ): A__ : Tuple = dict(self.forward_default_kwargs ) A__ : Optional[Any] = kwargs.pop("""num_inference_steps""" , lowerCamelCase_ ) A__ : Optional[int] = self.dummy_sample A__ : Optional[Any] = 0.1 * sample A__ : Optional[Any] = [residual + 0.2, residual + 0.1_5, residual + 0.1_0] for scheduler_class in self.scheduler_classes: A__ : str = self.get_scheduler_config() A__ : Any = scheduler_class(**lowerCamelCase_ ) scheduler.set_timesteps(lowerCamelCase_ ) # copy over dummy past residuals (must be after setting timesteps) A__ : List[str] = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowerCamelCase_ ) A__ : List[str] = scheduler_class.from_pretrained(lowerCamelCase_ ) # copy over dummy past residuals new_scheduler.set_timesteps(lowerCamelCase_ ) # copy over dummy past residual (must be after setting timesteps) A__ : Dict = dummy_past_residuals[: new_scheduler.config.solver_order] A__ : List[Any] = scheduler.step(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ).prev_sample A__ : Tuple = new_scheduler.step(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def __A ( self , A__=None , **A__ ): if scheduler is None: A__ : Optional[int] = self.scheduler_classes[0] A__ : Optional[Any] = self.get_scheduler_config(**lowerCamelCase_ ) A__ : int = scheduler_class(**lowerCamelCase_ ) A__ : List[Any] = self.scheduler_classes[0] A__ : str = self.get_scheduler_config(**lowerCamelCase_ ) A__ : str = scheduler_class(**lowerCamelCase_ ) A__ : Tuple = 10 A__ : Any = self.dummy_model() A__ : Union[str, Any] = self.dummy_sample_deter scheduler.set_timesteps(lowerCamelCase_ ) for i, t in enumerate(scheduler.timesteps ): A__ : Dict = model(lowerCamelCase_ , lowerCamelCase_ ) A__ : Optional[int] = scheduler.step(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ).prev_sample return sample def __A ( self ): A__ : Tuple = dict(self.forward_default_kwargs ) A__ : int = kwargs.pop("""num_inference_steps""" , lowerCamelCase_ ) for scheduler_class in self.scheduler_classes: A__ : str = self.get_scheduler_config() A__ : Optional[Any] = scheduler_class(**lowerCamelCase_ ) A__ : Optional[int] = self.dummy_sample A__ : Any = 0.1 * sample if num_inference_steps is not None and hasattr(lowerCamelCase_ , """set_timesteps""" ): scheduler.set_timesteps(lowerCamelCase_ ) elif num_inference_steps is not None and not hasattr(lowerCamelCase_ , """set_timesteps""" ): A__ : str = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) A__ : Optional[Any] = [residual + 0.2, residual + 0.1_5, residual + 0.1_0] A__ : int = dummy_past_residuals[: scheduler.config.solver_order] A__ : int = scheduler.timesteps[5] A__ : int = scheduler.timesteps[6] A__ : List[Any] = scheduler.step(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ).prev_sample A__ : Tuple = scheduler.step(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def __A ( self ): A__ : str = DEISMultistepScheduler(**self.get_scheduler_config() ) A__ : Union[str, Any] = self.full_loop(scheduler=lowerCamelCase_ ) A__ : List[Any] = torch.mean(torch.abs(lowerCamelCase_ ) ) assert abs(result_mean.item() - 0.2_3_9_1_6 ) < 1e-3 A__ : List[str] = DPMSolverSinglestepScheduler.from_config(scheduler.config ) A__ : Tuple = DPMSolverMultistepScheduler.from_config(scheduler.config ) A__ : Dict = UniPCMultistepScheduler.from_config(scheduler.config ) A__ : int = DEISMultistepScheduler.from_config(scheduler.config ) A__ : Optional[Any] = self.full_loop(scheduler=lowerCamelCase_ ) A__ : List[str] = torch.mean(torch.abs(lowerCamelCase_ ) ) assert abs(result_mean.item() - 0.2_3_9_1_6 ) < 1e-3 def __A ( self ): for timesteps in [25, 50, 100, 999, 1000]: self.check_over_configs(num_train_timesteps=lowerCamelCase_ ) def __A ( self ): self.check_over_configs(thresholding=lowerCamelCase_ ) for order in [1, 2, 3]: for solver_type in ["logrho"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=lowerCamelCase_ , prediction_type=lowerCamelCase_ , sample_max_value=lowerCamelCase_ , algorithm_type="""deis""" , solver_order=lowerCamelCase_ , solver_type=lowerCamelCase_ , ) def __A ( self ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=lowerCamelCase_ ) def __A ( self ): for algorithm_type in ["deis"]: for solver_type in ["logrho"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=lowerCamelCase_ , solver_type=lowerCamelCase_ , prediction_type=lowerCamelCase_ , algorithm_type=lowerCamelCase_ , ) A__ : Dict = self.full_loop( solver_order=lowerCamelCase_ , solver_type=lowerCamelCase_ , prediction_type=lowerCamelCase_ , algorithm_type=lowerCamelCase_ , ) assert not torch.isnan(lowerCamelCase_ ).any(), "Samples have nan numbers" def __A ( self ): self.check_over_configs(lower_order_final=lowerCamelCase_ ) self.check_over_configs(lower_order_final=lowerCamelCase_ ) def __A ( self ): for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1000]: self.check_over_forward(num_inference_steps=lowerCamelCase_ , time_step=0 ) def __A ( self ): A__ : List[Any] = self.full_loop() A__ : List[Any] = torch.mean(torch.abs(lowerCamelCase_ ) ) assert abs(result_mean.item() - 0.2_3_9_1_6 ) < 1e-3 def __A ( self ): A__ : List[str] = self.full_loop(prediction_type="""v_prediction""" ) A__ : Any = torch.mean(torch.abs(lowerCamelCase_ ) ) assert abs(result_mean.item() - 0.0_9_1 ) < 1e-3 def __A ( self ): A__ : Optional[int] = self.scheduler_classes[0] A__ : List[str] = self.get_scheduler_config(thresholding=lowerCamelCase_ , dynamic_thresholding_ratio=0 ) A__ : Dict = scheduler_class(**lowerCamelCase_ ) A__ : List[str] = 10 A__ : Optional[int] = self.dummy_model() A__ : Dict = self.dummy_sample_deter.half() scheduler.set_timesteps(lowerCamelCase_ ) for i, t in enumerate(scheduler.timesteps ): A__ : List[Any] = model(lowerCamelCase_ , lowerCamelCase_ ) A__ : List[Any] = scheduler.step(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ).prev_sample assert sample.dtype == torch.floataa
712
def UpperCamelCase (lowercase_: int , lowercase_: int ) -> int: while second != 0: A__ : int = first & second first ^= second A__ : int = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() A_ : Optional[Any] = int(input('Enter the first number: ').strip()) A_ : List[str] = int(input('Enter the second number: ').strip()) print(f'''{add(first, second) = }''')
64
0
import os import zipfile import requests from get_ci_error_statistics import download_artifact, get_artifacts_links def UpperCamelCase (lowercase_: Dict , lowercase_: Any=7 ) -> Any: A__ : List[Any] = None if token is not None: A__ : List[Any] = {"""Accept""": """application/vnd.github+json""", """Authorization""": f"""Bearer {token}"""} # The id of a workflow (not of a workflow run) A__ : List[Any] = """636036""" A__ : List[str] = f"""https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs""" # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results url += f"""?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}""" A__ : Dict = requests.get(A__ , headers=A__ ).json() return result["workflow_runs"] def UpperCamelCase (lowercase_: List[str] ) -> int: A__ : List[Any] = get_daily_ci_runs(A__ ) A__ : Tuple = None for workflow_run in workflow_runs: if workflow_run["status"] == "completed": A__ : Optional[int] = workflow_run["""id"""] break return workflow_run_id def UpperCamelCase (lowercase_: List[Any] , lowercase_: str , lowercase_: Optional[int] ) -> Union[str, Any]: A__ : Union[str, Any] = get_last_daily_ci_runs(A__ ) if workflow_run_id is not None: A__ : Any = get_artifacts_links(worflow_run_id=A__ , token=A__ ) for artifact_name in artifact_names: if artifact_name in artifacts_links: A__ : str = artifacts_links[artifact_name] download_artifact( artifact_name=A__ , artifact_url=A__ , output_dir=A__ , token=A__ ) def UpperCamelCase (lowercase_: List[Any] , lowercase_: Optional[Any] , lowercase_: Any ) -> Tuple: get_last_daily_ci_artifacts(A__ , A__ , A__ ) A__ : List[str] = {} for artifact_name in artifact_names: A__ : int = os.path.join(A__ , f"""{artifact_name}.zip""" ) if os.path.isfile(A__ ): A__ : Optional[int] = {} with zipfile.ZipFile(A__ ) as z: for filename in z.namelist(): if not os.path.isdir(A__ ): # read the file with z.open(A__ ) as f: A__ : int = f.read().decode("""UTF-8""" ) return results
713
from __future__ import annotations from collections.abc import Callable A_ : List[Any] = list[list[float | int]] def UpperCamelCase (lowercase_: Matrix , lowercase_: Matrix ) -> Matrix: A__ : int = len(lowercase_ ) A__ : Matrix = [[0 for _ in range(size + 1 )] for _ in range(lowercase_ )] A__ : int A__ : int A__ : int A__ : int A__ : int A__ : float for row in range(lowercase_ ): for col in range(lowercase_ ): A__ : List[str] = matrix[row][col] A__ : int = vector[row][0] A__ : Optional[int] = 0 A__ : str = 0 while row < size and col < size: # pivoting A__ : int = max((abs(augmented[rowa][col] ), rowa) for rowa in range(lowercase_ , lowercase_ ) )[ 1 ] if augmented[pivot_row][col] == 0: col += 1 continue else: A__ , A__ : Union[str, Any] = augmented[pivot_row], augmented[row] for rowa in range(row + 1 , lowercase_ ): A__ : List[Any] = augmented[rowa][col] / augmented[row][col] A__ : Dict = 0 for cola in range(col + 1 , size + 1 ): augmented[rowa][cola] -= augmented[row][cola] * ratio row += 1 col += 1 # back substitution for col in range(1 , lowercase_ ): for row in range(lowercase_ ): A__ : List[str] = augmented[row][col] / augmented[col][col] for cola in range(lowercase_ , size + 1 ): augmented[row][cola] -= augmented[col][cola] * ratio # round to get rid of numbers like 2.000000000000004 return [ [round(augmented[row][size] / augmented[row][row] , 10 )] for row in range(lowercase_ ) ] def UpperCamelCase (lowercase_: list[int] ) -> Callable[[int], int]: A__ : int = len(lowercase_ ) A__ : Matrix = [[0 for _ in range(lowercase_ )] for _ in range(lowercase_ )] A__ : Matrix = [[0] for _ in range(lowercase_ )] A__ : Matrix A__ : int A__ : int A__ : int for x_val, y_val in enumerate(lowercase_ ): for col in range(lowercase_ ): A__ : Dict = (x_val + 1) ** (size - col - 1) A__ : Any = y_val A__ : Union[str, Any] = solve(lowercase_ , lowercase_ ) def interpolated_func(lowercase_: int ) -> int: return sum( round(coeffs[x_val][0] ) * (var ** (size - x_val - 1)) for x_val in range(lowercase_ ) ) return interpolated_func def UpperCamelCase (lowercase_: int ) -> int: return ( 1 - variable + variable**2 - variable**3 + variable**4 - variable**5 + variable**6 - variable**7 + variable**8 - variable**9 + variable**10 ) def UpperCamelCase (lowercase_: Callable[[int], int] = question_function , lowercase_: int = 10 ) -> int: A__ : list[int] = [func(lowercase_ ) for x_val in range(1 , order + 1 )] A__ : list[Callable[[int], int]] = [ interpolate(data_points[:max_coeff] ) for max_coeff in range(1 , order + 1 ) ] A__ : int = 0 A__ : Callable[[int], int] A__ : int for poly in polynomials: A__ : List[str] = 1 while func(lowercase_ ) == poly(lowercase_ ): x_val += 1 ret += poly(lowercase_ ) return ret if __name__ == "__main__": print(f'''{solution() = }''')
64
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available A_ : Any = { 'configuration_poolformer': [ 'POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PoolFormerConfig', 'PoolFormerOnnxConfig', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : List[str] = ['PoolFormerFeatureExtractor'] A_ : Optional[int] = ['PoolFormerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Optional[int] = [ 'POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'PoolFormerForImageClassification', 'PoolFormerModel', 'PoolFormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_poolformer import ( POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, PoolFormerConfig, PoolFormerOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_poolformer import PoolFormerFeatureExtractor from .image_processing_poolformer import PoolFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_poolformer import ( POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, PoolFormerForImageClassification, PoolFormerModel, PoolFormerPreTrainedModel, ) else: import sys A_ : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure)
714
from functools import lru_cache @lru_cache def UpperCamelCase (lowercase_: int ) -> int: 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()
64
0
from __future__ import annotations import inspect import unittest from transformers import ViTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFViTForImageClassification, TFViTModel if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class _a : '''simple docstring''' def __init__( self , A__ , A__=13 , A__=30 , A__=2 , A__=3 , A__=True , A__=True , A__=32 , A__=2 , A__=4 , A__=37 , A__="gelu" , A__=0.1 , A__=0.1 , A__=10 , A__=0.0_2 , A__=3 , A__=None , ): A__ : List[Any] = parent A__ : Union[str, Any] = batch_size A__ : Tuple = image_size A__ : int = patch_size A__ : str = num_channels A__ : Optional[int] = is_training A__ : Optional[Any] = use_labels A__ : Any = hidden_size A__ : Tuple = num_hidden_layers A__ : Optional[int] = num_attention_heads A__ : Any = intermediate_size A__ : str = hidden_act A__ : Dict = hidden_dropout_prob A__ : Optional[int] = attention_probs_dropout_prob A__ : Any = type_sequence_label_size A__ : Optional[Any] = initializer_range A__ : Dict = scope # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) A__ : Any = (image_size // patch_size) ** 2 A__ : Optional[int] = num_patches + 1 def __A ( self ): A__ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A__ : str = None if self.use_labels: A__ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ : int = self.get_config() return config, pixel_values, labels def __A ( self ): return ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=lowercase_ , initializer_range=self.initializer_range , ) def __A ( self , A__ , A__ , A__ ): A__ : Dict = TFViTModel(config=lowercase_ ) A__ : Dict = model(lowercase_ , training=lowercase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # Test with an image with different size than the one specified in config. A__ : Any = self.image_size // 2 A__ : Any = pixel_values[:, :, :image_size, :image_size] A__ : Any = model(lowercase_ , interpolate_pos_encoding=lowercase_ , training=lowercase_ ) A__ : Optional[Any] = (image_size // self.patch_size) ** 2 + 1 self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, seq_length, self.hidden_size) ) def __A ( self , A__ , A__ , A__ ): A__ : List[str] = self.type_sequence_label_size A__ : Optional[Any] = TFViTForImageClassification(lowercase_ ) A__ : Optional[int] = model(lowercase_ , labels=lowercase_ , training=lowercase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # Test with an image with different size than the one specified in config. A__ : int = self.image_size // 2 A__ : Optional[int] = pixel_values[:, :, :image_size, :image_size] A__ : Optional[Any] = model(lowercase_ , interpolate_pos_encoding=lowercase_ , training=lowercase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images A__ : Dict = 1 A__ : str = TFViTForImageClassification(lowercase_ ) A__ : Union[str, Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A__ : List[Any] = model(lowercase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __A ( self ): A__ : Any = self.prepare_config_and_inputs() A__ , A__ , A__ : List[str] = config_and_inputs A__ : int = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class _a (__magic_name__ , __magic_name__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: List[str] = (TFViTModel, TFViTForImageClassification) if is_tf_available() else () UpperCAmelCase__: Dict = ( {'''feature-extraction''': TFViTModel, '''image-classification''': TFViTForImageClassification} if is_tf_available() else {} ) UpperCAmelCase__: Union[str, Any] = False UpperCAmelCase__: Optional[Any] = False UpperCAmelCase__: Union[str, Any] = False def __A ( self ): A__ : str = TFViTModelTester(self ) A__ : Optional[Any] = ConfigTester(self , config_class=lowercase_ , has_text_modality=lowercase_ , hidden_size=37 ) def __A ( self ): self.config_tester.run_common_tests() @unittest.skip(reason="""ViT does not use inputs_embeds""" ) def __A ( self ): pass @unittest.skip(reason="""ViT does not use inputs_embeds""" ) def __A ( self ): pass def __A ( self ): A__ , A__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A__ : Any = model_class(lowercase_ ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) A__ : List[str] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowercase_ , tf.keras.layers.Layer ) ) def __A ( self ): A__ , A__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A__ : Union[str, Any] = model_class(lowercase_ ) A__ : List[Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A__ : Any = [*signature.parameters.keys()] A__ : int = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , lowercase_ ) def __A ( self ): A__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_ ) def __A ( self ): A__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase_ ) @slow def __A ( self ): A__ : Optional[Any] = TFViTModel.from_pretrained("""google/vit-base-patch16-224""" ) self.assertIsNotNone(lowercase_ ) def UpperCamelCase () -> Dict: A__ : List[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class _a (unittest.TestCase ): '''simple docstring''' @cached_property def __A ( self ): return ViTImageProcessor.from_pretrained("""google/vit-base-patch16-224""" ) if is_vision_available() else None @slow def __A ( self ): A__ : Dict = TFViTForImageClassification.from_pretrained("""google/vit-base-patch16-224""" ) A__ : List[str] = self.default_image_processor A__ : List[str] = prepare_img() A__ : Any = image_processor(images=lowercase_ , return_tensors="""tf""" ) # forward pass A__ : str = model(**lowercase_ ) # verify the logits A__ : Any = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , lowercase_ ) A__ : Union[str, Any] = tf.constant([-0.2_7_4_4, 0.8_2_1_5, -0.0_8_3_6] ) tf.debugging.assert_near(outputs.logits[0, :3] , lowercase_ , atol=1e-4 )
715
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import datasets import datasets.config from .utils import require_beam class _a (datasets.BeamBasedBuilder ): '''simple docstring''' def __A ( self ): return datasets.DatasetInfo( features=datasets.Features({"""content""": datasets.Value("""string""" )} ) , supervised_keys=A__ , ) def __A ( self , A__ , A__ ): return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""examples""": get_test_dummy_examples()} )] def __A ( self , A__ , A__ ): import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(A__ ) class _a (datasets.BeamBasedBuilder ): '''simple docstring''' def __A ( self ): return datasets.DatasetInfo( features=datasets.Features({"""a""": datasets.Sequence({"""b""": datasets.Value("""string""" )} )} ) , supervised_keys=A__ , ) def __A ( self , A__ , A__ ): return [ datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""examples""": get_test_nested_examples()} ) ] def __A ( self , A__ , A__ ): import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(A__ ) def UpperCamelCase () -> Dict: return [(i, {"content": content}) for i, content in enumerate(["""foo""", """bar""", """foobar"""] )] def UpperCamelCase () -> Tuple: return [(i, {"a": {"b": [content]}}) for i, content in enumerate(["""foo""", """bar""", """foobar"""] )] class _a (__magic_name__ ): '''simple docstring''' @require_beam def __A ( self ): A__ : Dict = len(get_test_dummy_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: A__ : int = DummyBeamDataset(cache_dir=A__ , beam_runner="""DirectRunner""" ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(A__ , builder.name , """default""" , """0.0.0""" , F"""{builder.name}-train.arrow""" ) ) ) self.assertDictEqual(builder.info.features , datasets.Features({"""content""": datasets.Value("""string""" )} ) ) A__ : int = builder.as_dataset() self.assertEqual(dset["""train"""].num_rows , A__ ) self.assertEqual(dset["""train"""].info.splits["""train"""].num_examples , A__ ) self.assertDictEqual(dset["""train"""][0] , get_test_dummy_examples()[0][1] ) self.assertDictEqual( dset["""train"""][expected_num_examples - 1] , get_test_dummy_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(A__ , builder.name , """default""" , """0.0.0""" , """dataset_info.json""" ) ) ) del dset @require_beam def __A ( self ): import apache_beam as beam A__ : int = beam.io.parquetio.WriteToParquet A__ : List[str] = len(get_test_dummy_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: A__ : str = DummyBeamDataset(cache_dir=A__ , beam_runner="""DirectRunner""" ) with patch("""apache_beam.io.parquetio.WriteToParquet""" ) as write_parquet_mock: A__ : Optional[Any] = partial(A__ , num_shards=2 ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join( A__ , builder.name , """default""" , """0.0.0""" , F"""{builder.name}-train-00000-of-00002.arrow""" ) ) ) self.assertTrue( os.path.exists( os.path.join( A__ , builder.name , """default""" , """0.0.0""" , F"""{builder.name}-train-00000-of-00002.arrow""" ) ) ) self.assertDictEqual(builder.info.features , datasets.Features({"""content""": datasets.Value("""string""" )} ) ) A__ : Optional[int] = builder.as_dataset() self.assertEqual(dset["""train"""].num_rows , A__ ) self.assertEqual(dset["""train"""].info.splits["""train"""].num_examples , A__ ) # Order is not preserved when sharding, so we just check that all the elements are there self.assertListEqual(sorted(dset["""train"""]["""content"""] ) , sorted(["""foo""", """bar""", """foobar"""] ) ) self.assertTrue( os.path.exists(os.path.join(A__ , builder.name , """default""" , """0.0.0""" , """dataset_info.json""" ) ) ) del dset @require_beam def __A ( self ): with tempfile.TemporaryDirectory() as tmp_cache_dir: A__ : int = DummyBeamDataset(cache_dir=A__ ) self.assertRaises(datasets.builder.MissingBeamOptions , builder.download_and_prepare ) @require_beam def __A ( self ): A__ : List[Any] = len(get_test_nested_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: A__ : Optional[int] = NestedBeamDataset(cache_dir=A__ , beam_runner="""DirectRunner""" ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(A__ , builder.name , """default""" , """0.0.0""" , F"""{builder.name}-train.arrow""" ) ) ) self.assertDictEqual( builder.info.features , datasets.Features({"""a""": datasets.Sequence({"""b""": datasets.Value("""string""" )} )} ) ) A__ : Optional[int] = builder.as_dataset() self.assertEqual(dset["""train"""].num_rows , A__ ) self.assertEqual(dset["""train"""].info.splits["""train"""].num_examples , A__ ) self.assertDictEqual(dset["""train"""][0] , get_test_nested_examples()[0][1] ) self.assertDictEqual( dset["""train"""][expected_num_examples - 1] , get_test_nested_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(A__ , builder.name , """default""" , """0.0.0""" , """dataset_info.json""" ) ) ) del dset
64
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) A_ : Optional[int] = { 'configuration_blenderbot': [ 'BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BlenderbotConfig', 'BlenderbotOnnxConfig', ], 'tokenization_blenderbot': ['BlenderbotTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Optional[Any] = ['BlenderbotTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Optional[int] = [ 'BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BlenderbotForCausalLM', 'BlenderbotForConditionalGeneration', 'BlenderbotModel', 'BlenderbotPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Optional[int] = [ 'TFBlenderbotForConditionalGeneration', 'TFBlenderbotModel', 'TFBlenderbotPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Dict = [ 'FlaxBlenderbotForConditionalGeneration', 'FlaxBlenderbotModel', 'FlaxBlenderbotPreTrainedModel', ] if TYPE_CHECKING: from .configuration_blenderbot import ( BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotConfig, BlenderbotOnnxConfig, ) from .tokenization_blenderbot import BlenderbotTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_fast import BlenderbotTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot import ( BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot import ( TFBlenderbotForConditionalGeneration, TFBlenderbotModel, TFBlenderbotPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, FlaxBlenderbotPreTrainedModel, ) else: import sys A_ : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
716
import warnings from ...utils import logging from .image_processing_poolformer import PoolFormerImageProcessor A_ : Union[str, Any] = logging.get_logger(__name__) class _a (__magic_name__ ): '''simple docstring''' def __init__( self , *A__ , **A__ ): warnings.warn( """The class PoolFormerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use PoolFormerImageProcessor instead.""" , A__ , ) super().__init__(*A__ , **A__ )
64
0
from __future__ import annotations def UpperCamelCase (lowercase_: List[Any] , lowercase_: Any ) -> str: if len(lowercase_ ) <= 1 or n <= 1: return insert_next(lowercase_ , n - 1 ) rec_insertion_sort(lowercase_ , n - 1 ) def UpperCamelCase (lowercase_: Union[str, Any] , lowercase_: Any ) -> List[Any]: if index >= len(lowercase_ ) or collection[index - 1] <= collection[index]: return # Swaps adjacent elements since they are not in ascending order A__ : Dict = ( collection[index], collection[index - 1], ) insert_next(lowercase_ , index + 1 ) if __name__ == "__main__": A_ : Union[str, Any] = input('Enter integers separated by spaces: ') A_ : list[int] = [int(num) for num in numbers.split()] rec_insertion_sort(number_list, len(number_list)) print(number_list)
717
import inspect import logging import os import random import shutil import tempfile import unittest import pytest import torch from torch import nn from torch.utils.data import DataLoader, TensorDataset from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_cuda from accelerate.utils import ProjectConfiguration, set_seed A_ : Any = logging.getLogger(__name__) def UpperCamelCase (lowercase_: Optional[Any]=2 , lowercase_: Union[str, Any]=3 , lowercase_: int=16 , lowercase_: int = 10 , lowercase_: int = 2 ) -> int: def get_dataset(lowercase_: Optional[int] ): A__ : Optional[Any] = torch.randn(batch_size * n_batches , 1 ) return TensorDataset(lowercase_ , a * x + b + 0.1 * torch.randn(batch_size * n_batches , 1 ) ) A__ : Dict = get_dataset(lowercase_ ) A__ : Any = get_dataset(lowercase_ ) A__ : Dict = DataLoader(lowercase_ , shuffle=lowercase_ , batch_size=lowercase_ , num_workers=4 ) A__ : Optional[Any] = DataLoader(lowercase_ , shuffle=lowercase_ , batch_size=lowercase_ , num_workers=4 ) return (train_dataloader, valid_dataloader) def UpperCamelCase (lowercase_: Optional[Any] , lowercase_: List[str] , lowercase_: int , lowercase_: int , lowercase_: List[str] , lowercase_: Dict=None ) -> List[Any]: A__ : List[Any] = [] for epoch in range(lowercase_ ): # Train quickly model.train() for batch in dataloader: A__ , A__ : Any = batch A__ : Any = model(lowercase_ ) A__ : Any = torch.nn.functional.mse_loss(lowercase_ , lowercase_ ) accelerator.backward(lowercase_ ) optimizer.step() optimizer.zero_grad() rands.append(random.random() ) # Introduce some randomness if scheduler is not None: scheduler.step() return rands class _a (nn.Module ): '''simple docstring''' def __init__( self ): super().__init__() A__ : str = nn.Parameter(torch.randn(1 ) ) A__ : Any = nn.Parameter(torch.randn(1 ) ) def __A ( self , A__ ): return x * self.a + self.b class _a (unittest.TestCase ): '''simple docstring''' def __A ( self ): with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) A__ : Optional[Any] = DummyModel() A__ : Optional[Any] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) A__ , A__ : str = dummy_dataloaders() A__ : Dict = ProjectConfiguration(total_limit=1 , project_dir=A__ , automatic_checkpoint_naming=A__ ) # Train baseline A__ : List[str] = Accelerator(project_config=A__ ) A__ , A__ , A__ , A__ : Any = accelerator.prepare( A__ , A__ , A__ , A__ ) # Save initial accelerator.save_state() # Save second state accelerator.save_state() self.assertEqual(len(os.listdir(accelerator.project_dir ) ) , 1 ) def __A ( self ): with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) A__ : str = DummyModel() A__ : Optional[int] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) A__ , A__ : int = dummy_dataloaders() # Train baseline A__ : str = Accelerator() A__ , A__ , A__ , A__ : List[str] = accelerator.prepare( A__ , A__ , A__ , A__ ) # Save initial A__ : List[Any] = os.path.join(A__ , """initial""" ) accelerator.save_state(A__ ) ((A__) , (A__)) : str = model.a.item(), model.b.item() A__ : Dict = optimizer.state_dict() A__ : List[str] = train(3 , A__ , A__ , A__ , A__ ) ((A__) , (A__)) : str = model.a.item(), model.b.item() A__ : Any = optimizer.state_dict() # Train partially set_seed(42 ) A__ : Optional[int] = DummyModel() A__ : Dict = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) A__ , A__ : Dict = dummy_dataloaders() A__ : List[str] = Accelerator() A__ , A__ , A__ , A__ : Optional[Any] = accelerator.prepare( A__ , A__ , A__ , A__ ) accelerator.load_state(A__ ) ((A__) , (A__)) : Tuple = model.a.item(), model.b.item() A__ : Union[str, Any] = optimizer.state_dict() self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) A__ : List[str] = train(2 , A__ , A__ , A__ , A__ ) # Save everything A__ : Optional[int] = os.path.join(A__ , """checkpoint""" ) accelerator.save_state(A__ ) # Load everything back in and make sure all states work accelerator.load_state(A__ ) test_rands += train(1 , A__ , A__ , A__ , A__ ) ((A__) , (A__)) : Union[str, Any] = model.a.item(), model.b.item() A__ : Optional[int] = optimizer.state_dict() self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) def __A ( self ): with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) A__ : int = DummyModel() A__ : Optional[int] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) A__ , A__ : List[str] = dummy_dataloaders() A__ : str = ProjectConfiguration(automatic_checkpoint_naming=A__ ) # Train baseline A__ : Any = Accelerator(project_dir=A__ , project_config=A__ ) A__ , A__ , A__ , A__ : str = accelerator.prepare( A__ , A__ , A__ , A__ ) # Save initial accelerator.save_state() ((A__) , (A__)) : Tuple = model.a.item(), model.b.item() A__ : int = optimizer.state_dict() A__ : int = train(3 , A__ , A__ , A__ , A__ ) ((A__) , (A__)) : Optional[Any] = model.a.item(), model.b.item() A__ : Any = optimizer.state_dict() # Train partially set_seed(42 ) A__ : Dict = DummyModel() A__ : List[Any] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) A__ , A__ : Union[str, Any] = dummy_dataloaders() A__ : List[Any] = ProjectConfiguration(iteration=1 , automatic_checkpoint_naming=A__ ) A__ : Dict = Accelerator(project_dir=A__ , project_config=A__ ) A__ , A__ , A__ , A__ : Union[str, Any] = accelerator.prepare( A__ , A__ , A__ , A__ ) accelerator.load_state(os.path.join(A__ , """checkpoints""" , """checkpoint_0""" ) ) ((A__) , (A__)) : Optional[int] = model.a.item(), model.b.item() A__ : Tuple = optimizer.state_dict() self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) A__ : str = train(2 , A__ , A__ , A__ , A__ ) # Save everything accelerator.save_state() # Load everything back in and make sure all states work accelerator.load_state(os.path.join(A__ , """checkpoints""" , """checkpoint_1""" ) ) test_rands += train(1 , A__ , A__ , A__ , A__ ) ((A__) , (A__)) : Optional[int] = model.a.item(), model.b.item() A__ : List[Any] = optimizer.state_dict() self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) def __A ( self ): A__ : Union[str, Any] = torch.tensor([1, 2, 3] ) A__ : int = torch.tensor([2, 3, 4] ) A__ : List[Any] = DummyModel() A__ : List[Any] = torch.optim.Adam(net.parameters() ) A__ : Tuple = Accelerator() with self.assertRaises(A__ ) as ve: accelerator.register_for_checkpointing(A__ , A__ , A__ , A__ ) A__ : Any = str(ve.exception ) self.assertTrue("""Item at index 0""" in message ) self.assertTrue("""Item at index 1""" in message ) self.assertFalse("""Item at index 2""" in message ) self.assertFalse("""Item at index 3""" in message ) def __A ( self ): with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) A__ : Any = DummyModel() A__ : Union[str, Any] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) A__ : Dict = torch.optim.lr_scheduler.StepLR(A__ , step_size=1 , gamma=0.9_9 ) A__ , A__ : List[Any] = dummy_dataloaders() A__ : Tuple = ProjectConfiguration(automatic_checkpoint_naming=A__ ) # Train baseline A__ : Optional[Any] = Accelerator(project_dir=A__ , project_config=A__ ) A__ , A__ , A__ , A__ , A__ : Union[str, Any] = accelerator.prepare( A__ , A__ , A__ , A__ , A__ ) # Save initial accelerator.save_state() A__ : Tuple = scheduler.state_dict() train(3 , A__ , A__ , A__ , A__ , A__ ) self.assertNotEqual(A__ , scheduler.state_dict() ) # Load everything back in and make sure all states work accelerator.load_state(os.path.join(A__ , """checkpoints""" , """checkpoint_0""" ) ) self.assertEqual(A__ , scheduler.state_dict() ) def __A ( self ): with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) A__ : Optional[Any] = DummyModel() A__ : int = ProjectConfiguration(automatic_checkpoint_naming=A__ , total_limit=2 ) # Train baseline A__ : List[str] = Accelerator(project_dir=A__ , project_config=A__ ) A__ : Union[str, Any] = accelerator.prepare(A__ ) # Save 3 states: for _ in range(11 ): accelerator.save_state() self.assertTrue(not os.path.exists(os.path.join(A__ , """checkpoints""" , """checkpoint_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(A__ , """checkpoints""" , """checkpoint_9""" ) ) ) self.assertTrue(os.path.exists(os.path.join(A__ , """checkpoints""" , """checkpoint_10""" ) ) ) @require_cuda def __A ( self ): A__ : Dict = ["""torchrun""", F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__ )] execute_subprocess_async(A__ , env=os.environ.copy() ) if __name__ == "__main__": A_ : List[str] = '/tmp/accelerate/state_checkpointing' A_ : Optional[Any] = DummyModel() A_ : Union[str, Any] = torch.optim.Adam(params=model.parameters(), lr=1E-3) A_ : str = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99) A_ , A_ : List[Any] = dummy_dataloaders() A_ : int = ProjectConfiguration(automatic_checkpoint_naming=True) # Train baseline A_ : List[str] = Accelerator(project_dir=savedir, project_config=project_config, mixed_precision='no') if accelerator.process_index == 0: if os.path.exists(savedir): shutil.rmtree(savedir) os.makedirs(savedir) A_ , A_ , A_ , A_ , A_ : List[Any] = accelerator.prepare( model, optimizer, train_dataloader, valid_dataloader, scheduler ) A_ , A_ : Dict = accelerator.prepare(model, optimizer) train(3, model, train_dataloader, optimizer, accelerator, scheduler) # Check that the intial optimizer is loaded on the GPU for group in optimizer.param_groups: A_ : str = group['params'][0].device break assert param_device.type == accelerator.device.type A_ : Optional[Any] = model.cpu() accelerator.wait_for_everyone() accelerator.save_state() accelerator.wait_for_everyone() # Check CPU state accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='cpu') for group in optimizer.param_groups: A_ : str = group['params'][0].device break assert ( param_device.type == torch.device('cpu').type ), f"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}" # Check device state model.to(accelerator.device) accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='on_device') for group in optimizer.param_groups: A_ : Tuple = group['params'][0].device break assert ( param_device.type == accelerator.device.type ), f"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}" # Check error with pytest.raises(TypeError, match='Unsupported optimizer map location passed'): accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='invalid') accelerator.wait_for_everyone() if accelerator.process_index == 0: shutil.rmtree(savedir) accelerator.wait_for_everyone()
64
0
from __future__ import annotations from itertools import permutations from random import randint from timeit import repeat def UpperCamelCase () -> tuple[list[int], int]: A__ : Optional[int] = [randint(-1000 , 1000 ) for i in range(10 )] A__ : str = randint(-5000 , 5000 ) return (arr, r) A_ : Optional[int] = make_dataset() def UpperCamelCase (lowercase_: str , lowercase_: Optional[int] ) -> tuple[int, ...]: for triplet in permutations(lowercase_ , 3 ): if sum(lowercase_ ) == target: return tuple(sorted(lowercase_ ) ) return (0, 0, 0) def UpperCamelCase (lowercase_: int , lowercase_: Union[str, Any] ) -> tuple[int, int, int]: arr.sort() A__ : Optional[int] = len(lowercase_ ) for i in range(n - 1 ): A__ : int = i + 1, n - 1 while left < right: if arr[i] + arr[left] + arr[right] == target: return (arr[i], arr[left], arr[right]) elif arr[i] + arr[left] + arr[right] < target: left += 1 elif arr[i] + arr[left] + arr[right] > target: right -= 1 return (0, 0, 0) def UpperCamelCase () -> tuple[float, float]: A__ : List[str] = "\nfrom __main__ import dataset, triplet_sum1, triplet_sum2\n" A__ : Union[str, Any] = "\ntriplet_sum1(*dataset)\n" A__ : Union[str, Any] = "\ntriplet_sum2(*dataset)\n" A__ : List[str] = repeat(setup=lowercase_ , stmt=lowercase_ , repeat=5 , number=10000 ) A__ : Tuple = repeat(setup=lowercase_ , stmt=lowercase_ , repeat=5 , number=10000 ) return (min(lowercase_ ), min(lowercase_ )) if __name__ == "__main__": from doctest import testmod testmod() A_ : Any = solution_times() print(f'''The time for naive implementation is {times[0]}.''') print(f'''The time for optimized implementation is {times[1]}.''')
718
def UpperCamelCase (lowercase_: str , lowercase_: str ) -> bool: A__ : Union[str, Any] = len(lowercase_ ) A__ : List[Any] = len(lowercase_ ) A__ : List[Any] = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] A__ : str = True for i in range(lowercase_ ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: A__ : int = True if a[i].islower(): A__ : Dict = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
64
0
import os # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_doctest_list.py A_ : Optional[Any] = '.' if __name__ == "__main__": A_ : Optional[int] = os.path.join(REPO_PATH, 'utils/documentation_tests.txt') A_ : int = [] A_ : int = [] with open(doctest_file_path) as fp: for line in fp: A_ : Optional[int] = line.strip() A_ : Any = os.path.join(REPO_PATH, line) if not (os.path.isfile(path) or os.path.isdir(path)): non_existent_paths.append(line) all_paths.append(path) if len(non_existent_paths) > 0: A_ : List[str] = '\n'.join(non_existent_paths) raise ValueError(f'''`utils/documentation_tests.txt` contains non-existent paths:\n{non_existent_paths}''') if all_paths != sorted(all_paths): raise ValueError('Files in `utils/documentation_tests.txt` are not in alphabetical order.')
719
import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin A_ : Dict = random.Random() if is_torch_available(): import torch def UpperCamelCase (lowercase_: Tuple , lowercase_: Tuple=1.0 , lowercase_: Dict=None , lowercase_: int=None ) -> str: if rng is None: A__ : Optional[Any] = global_rng A__ : List[str] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class _a (unittest.TestCase ): '''simple docstring''' def __init__( self , A__ , A__=7 , A__=400 , A__=2000 , A__=1 , A__=0.0 , A__=1_6000 , A__=True , A__=True , ): A__ : Any = parent A__ : Optional[int] = batch_size A__ : Union[str, Any] = min_seq_length A__ : Dict = max_seq_length A__ : Tuple = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) A__ : str = feature_size A__ : Optional[int] = padding_value A__ : List[str] = sampling_rate A__ : List[str] = return_attention_mask A__ : int = do_normalize def __A ( self ): return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def __A ( self , A__=False , A__=False ): def _flatten(A__ ): return list(itertools.chain(*A__ ) ) if equal_length: A__ : Dict = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size A__ : Union[str, Any] = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: A__ : Optional[int] = [np.asarray(A__ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class _a (__magic_name__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: int = ASTFeatureExtractor def __A ( self ): A__ : Optional[Any] = ASTFeatureExtractionTester(self ) def __A ( self ): # Tests that all call wrap to encode_plus and batch_encode_plus A__ : Optional[int] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 A__ : List[Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] A__ : Optional[Any] = [np.asarray(A__ ) for speech_input in speech_inputs] # Test not batched input A__ : Tuple = feat_extract(speech_inputs[0] , return_tensors="""np""" ).input_values A__ : Tuple = feat_extract(np_speech_inputs[0] , return_tensors="""np""" ).input_values self.assertTrue(np.allclose(A__ , A__ , atol=1e-3 ) ) # Test batched A__ : Tuple = feat_extract(A__ , padding=A__ , return_tensors="""np""" ).input_values A__ : Tuple = feat_extract(A__ , padding=A__ , return_tensors="""np""" ).input_values for enc_seq_a, enc_seq_a in zip(A__ , A__ ): self.assertTrue(np.allclose(A__ , A__ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. A__ : int = [floats_list((1, x) )[0] for x in (800, 800, 800)] A__ : List[str] = np.asarray(A__ ) A__ : Union[str, Any] = feat_extract(A__ , return_tensors="""np""" ).input_values A__ : Optional[Any] = feat_extract(A__ , return_tensors="""np""" ).input_values for enc_seq_a, enc_seq_a in zip(A__ , A__ ): self.assertTrue(np.allclose(A__ , A__ , atol=1e-3 ) ) @require_torch def __A ( self ): import torch A__ : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) A__ : Tuple = np.random.rand(100 ).astype(np.floataa ) A__ : Tuple = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: A__ : List[str] = feature_extractor.pad([{"""input_values""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) A__ : Any = feature_extractor.pad([{"""input_values""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def __A ( self , A__ ): from datasets import load_dataset A__ : str = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech A__ : str = ds.sort("""id""" ).select(range(A__ ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] @require_torch def __A ( self ): # fmt: off A__ : Optional[Any] = torch.tensor( [-0.9_8_9_4, -1.2_7_7_6, -0.9_0_6_6, -1.2_7_7_6, -0.9_3_4_9, -1.2_6_0_9, -1.0_3_8_6, -1.2_7_7_6, -1.1_5_6_1, -1.2_7_7_6, -1.2_0_5_2, -1.2_7_2_3, -1.2_1_9_0, -1.2_1_3_2, -1.2_7_7_6, -1.1_1_3_3, -1.1_9_5_3, -1.1_3_4_3, -1.1_5_8_4, -1.2_2_0_3, -1.1_7_7_0, -1.2_4_7_4, -1.2_3_8_1, -1.1_9_3_6, -0.9_2_7_0, -0.8_3_1_7, -0.8_0_4_9, -0.7_7_0_6, -0.7_5_6_5, -0.7_8_6_9] ) # fmt: on A__ : Any = self._load_datasamples(1 ) A__ : Tuple = ASTFeatureExtractor() A__ : Dict = feature_extractor(A__ , return_tensors="""pt""" ).input_values self.assertEquals(input_values.shape , (1, 1024, 128) ) self.assertTrue(torch.allclose(input_values[0, 0, :30] , A__ , atol=1e-4 ) )
64
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) A_ : Any = { """configuration_gpt_bigcode""": ["""GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTBigCodeConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Dict = [ """GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST""", """GPTBigCodeForSequenceClassification""", """GPTBigCodeForTokenClassification""", """GPTBigCodeForCausalLM""", """GPTBigCodeModel""", """GPTBigCodePreTrainedModel""", ] if TYPE_CHECKING: from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_bigcode import ( GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTBigCodeForCausalLM, GPTBigCodeForSequenceClassification, GPTBigCodeForTokenClassification, GPTBigCodeModel, GPTBigCodePreTrainedModel, ) else: import sys A_ : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
720
from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class _a (__magic_name__ , __magic_name__ , __magic_name__ ): '''simple docstring''' UpperCAmelCase__: str = [r'''h\.\d+\.attn\.bias''', r'''h\.\d+\.attn\.masked_bias'''] @register_to_config def __init__( self , A__ , A__ , A__ = None , A__ = 5_0257 , A__ = 1024 , A__ = 768 , A__ = 12 , A__ = 12 , A__ = None , A__ = "gelu_new" , A__ = 0.1 , A__ = 0.1 , A__ = 0.1 , A__ = 1e-5 , A__ = 0.0_2 , A__ = True , A__ = True , A__ = False , A__ = False , ): super().__init__() A__ : Union[str, Any] = prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( F"""`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and""" F""" `n_embd`: {n_embd} are not equal.""" ) A__ : str = prefix_inner_dim A__ : Optional[Any] = prefix_hidden_dim A__ : Tuple = ( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) A__ : int = ( nn.Linear(self.prefix_hidden_dim , A__ ) if self.prefix_hidden_dim is not None else nn.Identity() ) A__ : Tuple = GPTaConfig( vocab_size=A__ , n_positions=A__ , n_embd=A__ , n_layer=A__ , n_head=A__ , n_inner=A__ , activation_function=A__ , resid_pdrop=A__ , embd_pdrop=A__ , attn_pdrop=A__ , layer_norm_epsilon=A__ , initializer_range=A__ , scale_attn_weights=A__ , use_cache=A__ , scale_attn_by_inverse_layer_idx=A__ , reorder_and_upcast_attn=A__ , ) A__ : int = GPTaLMHeadModel(A__ ) def __A ( self , A__ , A__ , A__ = None , A__ = None , ): A__ : List[str] = self.transformer.transformer.wte(A__ ) A__ : int = self.encode_prefix(A__ ) A__ : int = self.decode_prefix(A__ ) A__ : Optional[Any] = torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: A__ : Any = self.get_dummy_token(input_ids.shape[0] , input_ids.device ) A__ : List[Any] = torch.cat((dummy_token, input_ids) , dim=1 ) A__ : List[str] = self.transformer(inputs_embeds=A__ , labels=A__ , attention_mask=A__ ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def __A ( self , A__ , A__ ): return torch.zeros(A__ , self.prefix_length , dtype=torch.intaa , device=A__ ) def __A ( self , A__ ): return self.encode_prefix(A__ ) @torch.no_grad() def __A ( self , A__ , A__ , A__ ): A__ : List[Any] = torch.split(A__ , 1 , dim=0 ) A__ : Optional[int] = [] A__ : str = [] for feature in features: A__ : Dict = self.decode_prefix(feature.to(A__ ) ) # back to the clip feature # Only support beam search for now A__ , A__ : Union[str, Any] = self.generate_beam( input_embeds=A__ , device=A__ , eos_token_id=A__ ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) A__ : int = torch.stack(A__ ) A__ : List[Any] = torch.stack(A__ ) return generated_tokens, generated_seq_lengths @torch.no_grad() def __A ( self , A__=None , A__=None , A__=None , A__ = 5 , A__ = 67 , A__ = 1.0 , A__ = None , ): A__ : Any = eos_token_id A__ : Any = None A__ : Optional[int] = None A__ : Optional[Any] = torch.ones(A__ , device=A__ , dtype=torch.int ) A__ : Any = torch.zeros(A__ , device=A__ , dtype=torch.bool ) if input_embeds is not None: A__ : Dict = input_embeds else: A__ : str = self.transformer.transformer.wte(A__ ) for i in range(A__ ): A__ : Dict = self.transformer(inputs_embeds=A__ ) A__ : str = outputs.logits A__ : Union[str, Any] = logits[:, -1, :] / (temperature if temperature > 0 else 1.0) A__ : Any = logits.softmax(-1 ).log() if scores is None: A__ , A__ : Optional[int] = logits.topk(A__ , -1 ) A__ : List[Any] = generated.expand(A__ , *generated.shape[1:] ) A__ , A__ : List[Any] = next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: A__ : Optional[Any] = next_tokens else: A__ : List[Any] = tokens.expand(A__ , *tokens.shape[1:] ) A__ : int = torch.cat((tokens, next_tokens) , dim=1 ) else: A__ : Optional[int] = -float(np.inf ) A__ : List[Any] = 0 A__ : str = scores[:, None] + logits seq_lengths[~is_stopped] += 1 A__ : Dict = scores_sum / seq_lengths[:, None] A__ , A__ : List[Any] = scores_sum_average.view(-1 ).topk(A__ , -1 ) A__ : Tuple = next_tokens // scores_sum.shape[1] A__ : Optional[Any] = seq_lengths[next_tokens_source] A__ : List[str] = next_tokens % scores_sum.shape[1] A__ : Optional[int] = next_tokens.unsqueeze(1 ) A__ : int = tokens[next_tokens_source] A__ : List[Any] = torch.cat((tokens, next_tokens) , dim=1 ) A__ : str = generated[next_tokens_source] A__ : Optional[Any] = scores_sum_average * seq_lengths A__ : Union[str, Any] = is_stopped[next_tokens_source] A__ : str = self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) A__ : Optional[int] = torch.cat((generated, next_token_embed) , dim=1 ) A__ : List[str] = is_stopped + next_tokens.eq(A__ ).squeeze() if is_stopped.all(): break A__ : Dict = scores / seq_lengths A__ : Dict = scores.argsort(descending=A__ ) # tokens tensors are already padded to max_seq_length A__ : Union[str, Any] = [tokens[i] for i in order] A__ : Any = torch.stack(A__ , dim=0 ) A__ : Dict = torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
64
0
import warnings from ...utils import logging from .image_processing_deformable_detr import DeformableDetrImageProcessor A_ = logging.get_logger(__name__) class _a (lowercase__ ): '''simple docstring''' def __init__( self , *A__ , **A__ ): warnings.warn( """The class DeformableDetrFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use DeformableDetrImageProcessor instead.""" , UpperCAmelCase__ , ) super().__init__(*UpperCAmelCase__ , **UpperCAmelCase__ )
721
import io import itertools import json from dataclasses import dataclass from typing import Optional import pyarrow as pa import pyarrow.json as paj import datasets from datasets.table import table_cast from datasets.utils.file_utils import readline A_ : Tuple = datasets.utils.logging.get_logger(__name__) @dataclass class _a (datasets.BuilderConfig ): '''simple docstring''' UpperCAmelCase__: Optional[datasets.Features] = None UpperCAmelCase__: str = "utf-8" UpperCAmelCase__: Optional[str] = None UpperCAmelCase__: Optional[str] = None UpperCAmelCase__: bool = True # deprecated UpperCAmelCase__: Optional[int] = None # deprecated UpperCAmelCase__: int = 10 << 20 # 10MB UpperCAmelCase__: Optional[bool] = None class _a (datasets.ArrowBasedBuilder ): '''simple docstring''' UpperCAmelCase__: List[str] = JsonConfig def __A ( self ): if self.config.block_size is not None: logger.warning("""The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead""" ) A__ : Union[str, Any] = self.config.block_size if self.config.use_threads is not True: logger.warning( """The JSON loader parameter `use_threads` is deprecated and doesn't have any effect anymore.""" ) if self.config.newlines_in_values is not None: raise ValueError("""The JSON loader parameter `newlines_in_values` is no longer supported""" ) return datasets.DatasetInfo(features=self.config.features ) def __A ( self , A__ ): if not self.config.data_files: raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}""" ) A__ : int = dl_manager.download_and_extract(self.config.data_files ) if isinstance(A__ , (str, list, tuple) ): A__ : Optional[Any] = data_files if isinstance(A__ , A__ ): A__ : List[str] = [files] A__ : int = [dl_manager.iter_files(A__ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""files""": files} )] A__ : List[str] = [] for split_name, files in data_files.items(): if isinstance(A__ , A__ ): A__ : Optional[int] = [files] A__ : Optional[int] = [dl_manager.iter_files(A__ ) for file in files] splits.append(datasets.SplitGenerator(name=A__ , gen_kwargs={"""files""": files} ) ) return splits def __A ( self , A__ ): if self.config.features is not None: # adding missing columns for column_name in set(self.config.features ) - set(pa_table.column_names ): A__ : Optional[Any] = self.config.features.arrow_schema.field(A__ ).type A__ : str = pa_table.append_column(A__ , pa.array([None] * len(A__ ) , type=A__ ) ) # more expensive cast to support nested structures with keys in a different order # allows str <-> int/float or str to Audio for example A__ : Optional[int] = table_cast(A__ , self.config.features.arrow_schema ) return pa_table def __A ( self , A__ ): for file_idx, file in enumerate(itertools.chain.from_iterable(A__ ) ): # If the file is one json object and if we need to look at the list of items in one specific field if self.config.field is not None: with open(A__ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: A__ : Optional[Any] = json.load(A__ ) # We keep only the field we are interested in A__ : Optional[int] = dataset[self.config.field] # We accept two format: a list of dicts or a dict of lists if isinstance(A__ , (list, tuple) ): A__ : Union[str, Any] = set().union(*[row.keys() for row in dataset] ) A__ : Any = {col: [row.get(A__ ) for row in dataset] for col in keys} else: A__ : Any = dataset A__ : Any = pa.Table.from_pydict(A__ ) yield file_idx, self._cast_table(A__ ) # If the file has one json object per line else: with open(A__ , """rb""" ) as f: A__ : List[str] = 0 # Use block_size equal to the chunk size divided by 32 to leverage multithreading # Set a default minimum value of 16kB if the chunk size is really small A__ : List[str] = max(self.config.chunksize // 32 , 16 << 10 ) A__ : Any = ( self.config.encoding_errors if self.config.encoding_errors is not None else """strict""" ) while True: A__ : Dict = f.read(self.config.chunksize ) if not batch: break # Finish current line try: batch += f.readline() except (AttributeError, io.UnsupportedOperation): batch += readline(A__ ) # PyArrow only accepts utf-8 encoded bytes if self.config.encoding != "utf-8": A__ : List[Any] = batch.decode(self.config.encoding , errors=A__ ).encode("""utf-8""" ) try: while True: try: A__ : str = paj.read_json( io.BytesIO(A__ ) , read_options=paj.ReadOptions(block_size=A__ ) ) break except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e: if ( isinstance(A__ , pa.ArrowInvalid ) and "straddling" not in str(A__ ) or block_size > len(A__ ) ): raise else: # Increase the block size in case it was too small. # The block size will be reset for the next file. logger.debug( F"""Batch of {len(A__ )} bytes couldn't be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.""" ) block_size *= 2 except pa.ArrowInvalid as e: try: with open( A__ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: A__ : Optional[Any] = json.load(A__ ) except json.JSONDecodeError: logger.error(F"""Failed to read file '{file}' with error {type(A__ )}: {e}""" ) raise e # If possible, parse the file as a list of json objects and exit the loop if isinstance(A__ , A__ ): # list is the only sequence type supported in JSON try: A__ : str = set().union(*[row.keys() for row in dataset] ) A__ : List[str] = {col: [row.get(A__ ) for row in dataset] for col in keys} A__ : int = pa.Table.from_pydict(A__ ) except (pa.ArrowInvalid, AttributeError) as e: logger.error(F"""Failed to read file '{file}' with error {type(A__ )}: {e}""" ) raise ValueError(F"""Not able to read records in the JSON file at {file}.""" ) from None yield file_idx, self._cast_table(A__ ) break else: logger.error(F"""Failed to read file '{file}' with error {type(A__ )}: {e}""" ) raise ValueError( F"""Not able to read records in the JSON file at {file}. """ F"""You should probably indicate the field of the JSON file containing your records. """ F"""This JSON file contain the following fields: {str(list(dataset.keys() ) )}. """ F"""Select the correct one and provide it as `field='XXX'` to the dataset loading method. """ ) from None # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(A__ ) batch_idx += 1
64
0
def UpperCamelCase (lowercase_: Optional[int] , lowercase_: Any ) -> Tuple: A__ : Any = len(_lowerCAmelCase ) print("""The following activities are selected:""" ) # The first activity is always selected A__ : Optional[Any] = 0 print(_lowerCAmelCase , end=""",""" ) # Consider rest of the activities for j in range(_lowerCAmelCase ): # If this activity has start time greater than # or equal to the finish time of previously # selected activity, then select it if start[j] >= finish[i]: print(_lowerCAmelCase , end=""",""" ) A__ : int = j if __name__ == "__main__": import doctest doctest.testmod() A_ : Optional[int] = [1, 3, 0, 5, 8, 5] A_ : Any = [2, 4, 6, 7, 9, 9] print_max_activities(start, finish)
700
import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore A_ : Dict = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" A_ : Optional[Any] = [file for file in filepaths if file != file.lower()] if upper_files: print(f'''{len(upper_files)} files contain uppercase characters:''') print('\n'.join(upper_files) + '\n') A_ : Tuple = [file for file in filepaths if ' ' in file] if space_files: print(f'''{len(space_files)} files contain space characters:''') print('\n'.join(space_files) + '\n') A_ : Any = [file for file in filepaths if '-' in file] if hyphen_files: print(f'''{len(hyphen_files)} files contain hyphen characters:''') print('\n'.join(hyphen_files) + '\n') A_ : List[str] = [file for file in filepaths if os.sep not in file] if nodir_files: print(f'''{len(nodir_files)} files are not in a directory:''') print('\n'.join(nodir_files) + '\n') A_ : Any = len(upper_files + space_files + hyphen_files + nodir_files) if bad_files: import sys sys.exit(bad_files)
64
0
import logging from dataclasses import dataclass, field from pathlib import Path from typing import Optional, Union from .generation.configuration_utils import GenerationConfig from .training_args import TrainingArguments from .utils import add_start_docstrings A_ : Dict = logging.getLogger(__name__) @dataclass @add_start_docstrings(TrainingArguments.__doc__ ) class _a (lowerCamelCase__ ): '''simple docstring''' UpperCAmelCase__: Tuple = field(default=lowerCamelCase__ , metadata={'''help''': '''Whether to use SortishSampler or not.'''} ) UpperCAmelCase__: int = field( default=lowerCamelCase__ , metadata={'''help''': '''Whether to use generate to calculate generative metrics (ROUGE, BLEU).'''} ) UpperCAmelCase__: Union[str, Any] = field( default=lowerCamelCase__ , metadata={ '''help''': ( '''The `max_length` to use on each evaluation loop when `predict_with_generate=True`. Will default ''' '''to the `max_length` value of the model configuration.''' ) } , ) UpperCAmelCase__: Dict = field( default=lowerCamelCase__ , metadata={ '''help''': ( '''The `num_beams` to use on each evaluation loop when `predict_with_generate=True`. Will default ''' '''to the `num_beams` value of the model configuration.''' ) } , ) UpperCAmelCase__: Optional[Any] = field( default=lowerCamelCase__ , metadata={ '''help''': '''Model id, file path or url pointing to a GenerationConfig json file, to use during prediction.''' } , ) def __A ( self ): A__ : List[Any] = super().to_dict() for k, v in d.items(): if isinstance(__lowerCamelCase , __lowerCamelCase ): A__ : str = v.to_dict() return d
701
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def UpperCamelCase (*lowercase_: Optional[int] , lowercase_: Optional[Union[Dict, Any]] = None , lowercase_: Dict=True , lowercase_: Tuple=2 ) -> Dict: from .. import __version__ A__ : Dict = take_from A__ : str = () if not isinstance(args[0] , lowercase_ ): A__ : int = (args,) for attribute, version_name, message in args: if version.parse(version.parse(lowercase_ ).base_version ) >= version.parse(lowercase_ ): raise ValueError( f"""The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers'""" f""" version {__version__} is >= {version_name}""" ) A__ : Any = None if isinstance(lowercase_ , lowercase_ ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(lowercase_ ),) A__ : List[str] = f"""The `{attribute}` argument is deprecated and will be removed in version {version_name}.""" elif hasattr(lowercase_ , lowercase_ ): values += (getattr(lowercase_ , lowercase_ ),) A__ : Optional[Any] = f"""The `{attribute}` attribute is deprecated and will be removed in version {version_name}.""" elif deprecated_kwargs is None: A__ : int = f"""`{attribute}` is deprecated and will be removed in version {version_name}.""" if warning is not None: A__ : int = warning + """ """ if standard_warn else """""" warnings.warn(warning + message , lowercase_ , stacklevel=lowercase_ ) if isinstance(lowercase_ , lowercase_ ) and len(lowercase_ ) > 0: A__ : Union[str, Any] = inspect.getouterframes(inspect.currentframe() )[1] A__ : Optional[Any] = call_frame.filename A__ : Optional[int] = call_frame.lineno A__ : Any = call_frame.function A__ , A__ : List[str] = next(iter(deprecated_kwargs.items() ) ) raise TypeError(f"""{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`""" ) if len(lowercase_ ) == 0: return elif len(lowercase_ ) == 1: return values[0] return values
64
0
from __future__ import annotations from cmath import sqrt def UpperCamelCase (lowercase_: str , lowercase_: str , lowercase_: Tuple ) -> tuple[complex, complex]: if a == 0: raise ValueError("""Coefficient \'a\' must not be zero.""" ) A__ : Optional[int] = b * b - 4 * a * c A__ : Tuple = (-b + sqrt(UpperCamelCase__ )) / (2 * a) A__ : List[Any] = (-b - sqrt(UpperCamelCase__ )) / (2 * a) return ( root_a.real if not root_a.imag else root_a, root_a.real if not root_a.imag else root_a, ) def UpperCamelCase () -> Optional[int]: A__ , A__ : List[str] = quadratic_roots(a=5 , b=6 , c=1 ) print(f"""The solutions are: {solutiona} and {solutiona}""" ) if __name__ == "__main__": main()
702
import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import ( rename_keys, ) from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME from transformers.utils.hub import convert_file_size_to_int def UpperCamelCase (lowercase_: List[str] , lowercase_: str ) -> Optional[Any]: if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer A__ : Union[str, Any] = flax_key_tuple[:-1] + ("""weight""",) A__ : Optional[int] = torch.permute(lowercase_ , (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(lowercase_ ): # linear layer A__ : Optional[Any] = flax_key_tuple[:-1] + ("""weight""",) A__ : int = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: A__ : Optional[int] = flax_key_tuple[:-1] + ("""weight""",) return flax_key_tuple, flax_tensor def UpperCamelCase (lowercase_: Tuple , lowercase_: Optional[int] , lowercase_: str ) -> Union[str, Any]: if "metadata" in layer: A__ : Tuple = layer.split("""metadata""" ) A__ : Optional[Any] = """""".join(split_layer[0] )[:-1] A__ : Optional[Any] = [tuple(("""metadata""" + split_layer[1]).split("""/""" ) )] elif "kvstore" in layer: A__ : str = layer.split("""kvstore""" ) A__ : int = """""".join(split_layer[0] )[:-1] A__ : Optional[int] = [tuple(("""kvstore""" + split_layer[1]).split("""/""" ) )] else: A__ : Any = layer.split("""/""" ) A__ : int = """/""".join(split_layer[:-1] ) A__ : str = (split_layer[-1],) if "kvstore/path" in layer: A__ : Dict = f"""{switch_checkpoint_path}/{checkpoint_info[layer]}""" elif "kvstore/driver" in layer: A__ : Optional[int] = """file""" else: A__ : str = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def UpperCamelCase (lowercase_: str , lowercase_: List[Any] ) -> int: A__ : int = rename_keys(lowercase_ ) A__ : Any = {} for k, v in current_block.items(): A__ : Dict = v A__ : str = new_current_block torch.save(lowercase_ , lowercase_ ) def UpperCamelCase (lowercase_: Dict , lowercase_: Optional[Any] , lowercase_: Optional[Any] , lowercase_: Optional[int] , lowercase_: str = WEIGHTS_NAME ) -> Tuple: A__ : Optional[int] = convert_file_size_to_int(lowercase_ ) A__ : List[Any] = [] A__ : int = {} A__ : List[str] = 0 A__ : Any = 0 os.makedirs(lowercase_ , exist_ok=lowercase_ ) with gfile.GFile(switch_checkpoint_path + """/checkpoint""" , """rb""" ) as fp: A__ : Optional[Any] = serialization.msgpack_restore(fp.read() )["""optimizer"""]["""target"""] A__ : Dict = flatten_dict(lowercase_ , sep="""/""" ) A__ : Any = {} for layer in checkpoint_info.keys(): A__ , A__ , A__ : Union[str, Any] = get_key_and_tensorstore_dict( lowercase_ , lowercase_ , lowercase_ ) if curr_real_layer_name in all_layers: A__ : Optional[int] = content else: A__ : List[Any] = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file A__ : Optional[Any] = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() A__ : List[Any] = torch.tensor(lowercase_ ) A__ : List[Any] = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts A__ , A__ : Any = rename_base_flax_keys(tuple(key.split("""/""" ) ) , lowercase_ ) A__ : Any = """/""".join(lowercase_ ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: A__ : List[Any] = os.path.join( lowercase_ , weights_name.replace(""".bin""" , f"""-{len(lowercase_ )+1:05d}-of-???.bin""" ) ) rename_and_save_block(lowercase_ , lowercase_ ) sharded_state_dicts.append(current_block.keys() ) del current_block A__ : Any = {} A__ : str = 0 A__ : List[str] = raw_weights.to(getattr(lowercase_ , lowercase_ ) ) current_block_size += weight_size total_size += weight_size # Add the last block A__ : Union[str, Any] = os.path.join(lowercase_ , weights_name.replace(""".bin""" , f"""-{len(lowercase_ )+1:05d}-of-???.bin""" ) ) rename_and_save_block(lowercase_ , lowercase_ ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(lowercase_ ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index A__ : str = {} A__ : Any = {} for idx, shard in enumerate(lowercase_ ): A__ : Any = weights_name.replace( """.bin""" , f"""-{idx+1:05d}-of-{len(lowercase_ ):05d}.bin""" ) # len(sharded_state_dicts):05d} A__ : Dict = os.path.join(lowercase_ , weights_name.replace(""".bin""" , f"""-{idx+1:05d}-of-???.bin""" ) ) os.rename(lowercase_ , os.path.join(lowercase_ , lowercase_ ) ) A__ : str = shard for key in shard: A__ : Any = shard_file # Add the metadata A__ : Tuple = {"""total_size""": total_size} A__ : Union[str, Any] = {"""metadata""": metadata, """weight_map""": weight_map} with open(os.path.join(lowercase_ , lowercase_ ) , """w""" , encoding="""utf-8""" ) as f: A__ : Dict = json.dumps(lowercase_ , indent=2 , sort_keys=lowercase_ ) + """\n""" f.write(lowercase_ ) return metadata, index if __name__ == "__main__": A_ : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--switch_t5x_checkpoint_path', default='/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600', type=str, required=False, help='Path to a directory containing a folder per layer. Follows the original Google format.', ) parser.add_argument('--max_shard_size', default='10GB', required=False, help='Max shard size') parser.add_argument('--dtype', default='bfloat16', type=str, required=False, help='dtype of the saved model') parser.add_argument( '--pytorch_dump_folder_path', default='/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted', type=str, required=False, help='Path to the output pytorch model.', ) A_ : Dict = parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def UpperCamelCase () -> int: from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer A__ : str = SwitchTransformersConfig.from_pretrained("""google/switch-base-8""" ) config.save_pretrained("""/home/arthur_huggingface_co/transformers/switch_converted""" ) A__ : str = SwitchTransformersForConditionalGeneration.from_pretrained( """/home/arthur_huggingface_co/transformers/switch_converted""" , device_map="""auto""" ) A__ : Tuple = TaTokenizer.from_pretrained("""t5-small""" ) A__ : Dict = """A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.""" A__ : Union[str, Any] = tokenizer(lowercase_ , return_tensors="""pt""" ).input_ids A__ : Tuple = model.generate(lowercase_ , decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
64
0
import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py A_ : int = 'src/diffusers' A_ : Optional[Any] = '.' # This is to make sure the diffusers module imported is the one in the repo. A_ : List[str] = importlib.util.spec_from_file_location( 'diffusers', os.path.join(DIFFUSERS_PATH, '__init__.py'), submodule_search_locations=[DIFFUSERS_PATH], ) A_ : List[Any] = spec.loader.load_module() def UpperCamelCase (lowercase_: List[str] , lowercase_: List[Any] ) -> Union[str, Any]: return line.startswith(__SCREAMING_SNAKE_CASE ) or len(__SCREAMING_SNAKE_CASE ) <= 1 or re.search(r"""^\s*\)(\s*->.*:|:)\s*$""" , __SCREAMING_SNAKE_CASE ) is not None def UpperCamelCase (lowercase_: Optional[Any] ) -> str: A__ : Optional[int] = object_name.split(""".""" ) A__ : Dict = 0 # First let's find the module where our object lives. A__ : int = parts[i] while i < len(__SCREAMING_SNAKE_CASE ) and not os.path.isfile(os.path.join(__SCREAMING_SNAKE_CASE , f"""{module}.py""" ) ): i += 1 if i < len(__SCREAMING_SNAKE_CASE ): A__ : List[Any] = os.path.join(__SCREAMING_SNAKE_CASE , parts[i] ) if i >= len(__SCREAMING_SNAKE_CASE ): raise ValueError(f"""`object_name` should begin with the name of a module of diffusers but got {object_name}.""" ) with open(os.path.join(__SCREAMING_SNAKE_CASE , f"""{module}.py""" ) , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: A__ : str = f.readlines() # Now let's find the class / func in the code! A__ : Any = "" A__ : Optional[Any] = 0 for name in parts[i + 1 :]: while ( line_index < len(__SCREAMING_SNAKE_CASE ) and re.search(rf"""^{indent}(class|def)\s+{name}(\(|\:)""" , lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(__SCREAMING_SNAKE_CASE ): raise ValueError(f""" {object_name} does not match any function or class in {module}.""" ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). A__ : Union[str, Any] = line_index while line_index < len(__SCREAMING_SNAKE_CASE ) and _should_continue(lines[line_index] , __SCREAMING_SNAKE_CASE ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 A__ : Dict = lines[start_index:line_index] return "".join(__SCREAMING_SNAKE_CASE ) A_ : List[str] = re.compile(r'^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)') A_ : List[str] = re.compile(r'^\s*(\S+)->(\S+)(\s+.*|$)') A_ : List[Any] = re.compile(r'<FILL\s+[^>]*>') def UpperCamelCase (lowercase_: str ) -> Any: A__ : str = code.split("""\n""" ) A__ : Union[str, Any] = 0 while idx < len(__SCREAMING_SNAKE_CASE ) and len(lines[idx] ) == 0: idx += 1 if idx < len(__SCREAMING_SNAKE_CASE ): return re.search(r"""^(\s*)\S""" , lines[idx] ).groups()[0] return "" def UpperCamelCase (lowercase_: int ) -> List[str]: A__ : Optional[Any] = len(get_indent(__SCREAMING_SNAKE_CASE ) ) > 0 if has_indent: A__ : Optional[Any] = f"""class Bla:\n{code}""" A__ : List[Any] = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 , preview=__SCREAMING_SNAKE_CASE ) A__ : List[str] = black.format_str(__SCREAMING_SNAKE_CASE , mode=__SCREAMING_SNAKE_CASE ) A__ : Optional[Any] = style_docstrings_in_code(__SCREAMING_SNAKE_CASE ) return result[len("""class Bla:\n""" ) :] if has_indent else result def UpperCamelCase (lowercase_: str , lowercase_: Optional[Any]=False ) -> str: with open(__SCREAMING_SNAKE_CASE , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: A__ : List[Any] = f.readlines() A__ : str = [] A__ : Tuple = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(__SCREAMING_SNAKE_CASE ): A__ : Union[str, Any] = _re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. A__ : Union[str, Any] = search.groups() A__ : int = find_code_in_diffusers(__SCREAMING_SNAKE_CASE ) A__ : List[Any] = get_indent(__SCREAMING_SNAKE_CASE ) A__ : Dict = line_index + 1 if indent == theoretical_indent else line_index + 2 A__ : Dict = theoretical_indent A__ : Tuple = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. A__ : str = True while line_index < len(__SCREAMING_SNAKE_CASE ) and should_continue: line_index += 1 if line_index >= len(__SCREAMING_SNAKE_CASE ): break A__ : Dict = lines[line_index] A__ : List[Any] = _should_continue(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) and re.search(f"""^{indent}# End copy""" , __SCREAMING_SNAKE_CASE ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 A__ : Optional[int] = lines[start_index:line_index] A__ : Optional[Any] = "".join(__SCREAMING_SNAKE_CASE ) # Remove any nested `Copied from` comments to avoid circular copies A__ : int = [line for line in theoretical_code.split("""\n""" ) if _re_copy_warning.search(__SCREAMING_SNAKE_CASE ) is None] A__ : Dict = "\n".join(__SCREAMING_SNAKE_CASE ) # Before comparing, use the `replace_pattern` on the original code. if len(__SCREAMING_SNAKE_CASE ) > 0: A__ : Union[str, Any] = replace_pattern.replace("""with""" , """""" ).split(""",""" ) A__ : Optional[Any] = [_re_replace_pattern.search(__SCREAMING_SNAKE_CASE ) for p in patterns] for pattern in patterns: if pattern is None: continue A__ : Optional[Any] = pattern.groups() A__ : Optional[int] = re.sub(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if option.strip() == "all-casing": A__ : List[Any] = re.sub(obja.lower() , obja.lower() , __SCREAMING_SNAKE_CASE ) A__ : Optional[int] = re.sub(obja.upper() , obja.upper() , __SCREAMING_SNAKE_CASE ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line A__ : Optional[int] = blackify(lines[start_index - 1] + theoretical_code ) A__ : Optional[Any] = theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: A__ : List[str] = lines[:start_index] + [theoretical_code] + lines[line_index:] A__ : List[str] = start_index + 1 if overwrite and len(__SCREAMING_SNAKE_CASE ) > 0: # Warn the user a file has been modified. print(f"""Detected changes, rewriting {filename}.""" ) with open(__SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(__SCREAMING_SNAKE_CASE ) return diffs def UpperCamelCase (lowercase_: List[str] = False ) -> Optional[Any]: A__ : List[str] = glob.glob(os.path.join(__SCREAMING_SNAKE_CASE , """**/*.py""" ) , recursive=__SCREAMING_SNAKE_CASE ) A__ : List[Any] = [] for filename in all_files: A__ : Tuple = is_copy_consistent(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) diffs += [f"""- {filename}: copy does not match {d[0]} at line {d[1]}""" for d in new_diffs] if not overwrite and len(__SCREAMING_SNAKE_CASE ) > 0: A__ : str = "\n".join(__SCREAMING_SNAKE_CASE ) raise Exception( """Found the following copy inconsistencies:\n""" + diff + """\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them.""" ) if __name__ == "__main__": A_ : List[Any] = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') A_ : Any = parser.parse_args() check_copies(args.fix_and_overwrite)
703
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available A_ : Optional[Any] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : str = ['BartphoTokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bartpho import BartphoTokenizer else: import sys A_ : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
64
0
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 from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices A_ : Dict = logging.get_logger(__name__) A_ : str = { "microsoft/swin-tiny-patch4-window7-224": ( "https://huggingface.co/microsoft/swin-tiny-patch4-window7-224/resolve/main/config.json" ), # See all Swin models at https://huggingface.co/models?filter=swin } class _a (_UpperCAmelCase , _UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__: str = '''swin''' UpperCAmelCase__: Optional[int] = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , A__=224 , A__=4 , A__=3 , A__=96 , A__=[2, 2, 6, 2] , A__=[3, 6, 12, 24] , A__=7 , A__=4.0 , A__=True , A__=0.0 , A__=0.0 , A__=0.1 , A__="gelu" , A__=False , A__=0.0_2 , A__=1e-5 , A__=32 , A__=None , A__=None , **A__ , ): super().__init__(**A_ ) A__ : List[Any] = image_size A__ : int = patch_size A__ : Optional[int] = num_channels A__ : int = embed_dim A__ : List[str] = depths A__ : Optional[int] = len(A_ ) A__ : Union[str, Any] = num_heads A__ : List[str] = window_size A__ : Optional[int] = mlp_ratio A__ : Tuple = qkv_bias A__ : Union[str, Any] = hidden_dropout_prob A__ : List[Any] = attention_probs_dropout_prob A__ : Tuple = drop_path_rate A__ : Optional[int] = hidden_act A__ : Optional[int] = use_absolute_embeddings A__ : Dict = layer_norm_eps A__ : List[str] = initializer_range A__ : Dict = encoder_stride # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model A__ : Optional[Any] = int(embed_dim * 2 ** (len(A_ ) - 1) ) A__ : List[Any] = ["""stem"""] + [F"""stage{idx}""" for idx in range(1 , len(A_ ) + 1 )] A__ , A__ : int = get_aligned_output_features_output_indices( out_features=A_ , out_indices=A_ , stage_names=self.stage_names ) class _a (_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__: Union[str, Any] = version.parse('''1.11''' ) @property def __A ( self ): return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def __A ( self ): return 1e-4
704
import argparse import hashlib import os import urllib import warnings import torch from torch import nn from tqdm import tqdm from transformers import WhisperConfig, WhisperForConditionalGeneration A_ : Dict = { 'tiny.en': 'https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt', 'tiny': 'https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt', 'base.en': 'https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt', 'base': 'https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt', 'small.en': 'https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt', 'small': 'https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt', 'medium.en': 'https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt', 'medium': 'https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt', 'large': 'https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt', 'large-v2': 'https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt', } def UpperCamelCase (lowercase_: Optional[Any] ) -> Optional[int]: A__ : List[Any] = ["""layers""", """blocks"""] for k in ignore_keys: state_dict.pop(lowercase_ , lowercase_ ) A_ : Any = { 'blocks': 'layers', 'mlp.0': 'fc1', 'mlp.2': 'fc2', 'mlp_ln': 'final_layer_norm', '.attn.query': '.self_attn.q_proj', '.attn.key': '.self_attn.k_proj', '.attn.value': '.self_attn.v_proj', '.attn_ln': '.self_attn_layer_norm', '.attn.out': '.self_attn.out_proj', '.cross_attn.query': '.encoder_attn.q_proj', '.cross_attn.key': '.encoder_attn.k_proj', '.cross_attn.value': '.encoder_attn.v_proj', '.cross_attn_ln': '.encoder_attn_layer_norm', '.cross_attn.out': '.encoder_attn.out_proj', 'decoder.ln.': 'decoder.layer_norm.', 'encoder.ln.': 'encoder.layer_norm.', 'token_embedding': 'embed_tokens', 'encoder.positional_embedding': 'encoder.embed_positions.weight', 'decoder.positional_embedding': 'decoder.embed_positions.weight', 'ln_post': 'layer_norm', } def UpperCamelCase (lowercase_: str ) -> Any: A__ : Dict = list(s_dict.keys() ) for key in keys: A__ : List[str] = key for k, v in WHISPER_MAPPING.items(): if k in key: A__ : List[Any] = new_key.replace(lowercase_ , lowercase_ ) print(f"""{key} -> {new_key}""" ) A__ : Tuple = s_dict.pop(lowercase_ ) return s_dict def UpperCamelCase (lowercase_: Tuple ) -> Optional[int]: A__ , A__ : Any = emb.weight.shape A__ : str = nn.Linear(lowercase_ , lowercase_ , bias=lowercase_ ) A__ : Union[str, Any] = emb.weight.data return lin_layer def UpperCamelCase (lowercase_: str , lowercase_: str ) -> bytes: os.makedirs(lowercase_ , exist_ok=lowercase_ ) A__ : Tuple = os.path.basename(lowercase_ ) A__ : int = url.split("""/""" )[-2] A__ : Dict = os.path.join(lowercase_ , lowercase_ ) if os.path.exists(lowercase_ ) and not os.path.isfile(lowercase_ ): raise RuntimeError(f"""{download_target} exists and is not a regular file""" ) if os.path.isfile(lowercase_ ): A__ : Optional[Any] = open(lowercase_ , """rb""" ).read() if hashlib.shaaaa(lowercase_ ).hexdigest() == expected_shaaaa: return model_bytes else: warnings.warn(f"""{download_target} exists, but the SHA256 checksum does not match; re-downloading the file""" ) with urllib.request.urlopen(lowercase_ ) as source, open(lowercase_ , """wb""" ) as output: with tqdm( total=int(source.info().get("""Content-Length""" ) ) , ncols=80 , unit="""iB""" , unit_scale=lowercase_ , unit_divisor=1024 ) as loop: while True: A__ : Any = source.read(8192 ) if not buffer: break output.write(lowercase_ ) loop.update(len(lowercase_ ) ) A__ : Dict = open(lowercase_ , """rb""" ).read() if hashlib.shaaaa(lowercase_ ).hexdigest() != expected_shaaaa: raise RuntimeError( """Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model.""" ) return model_bytes def UpperCamelCase (lowercase_: List[Any] , lowercase_: Tuple ) -> Optional[Any]: if ".pt" not in checkpoint_path: A__ : Tuple = _download(_MODELS[checkpoint_path] ) else: A__ : Optional[int] = torch.load(lowercase_ , map_location="""cpu""" ) A__ : str = original_checkpoint["""dims"""] A__ : List[Any] = original_checkpoint["""model_state_dict"""] A__ : Optional[Any] = state_dict["""decoder.token_embedding.weight"""] remove_ignore_keys_(lowercase_ ) rename_keys(lowercase_ ) A__ : List[str] = True A__ : Optional[Any] = state_dict["""decoder.layers.0.fc1.weight"""].shape[0] A__ : List[Any] = WhisperConfig( vocab_size=dimensions["""n_vocab"""] , encoder_ffn_dim=lowercase_ , decoder_ffn_dim=lowercase_ , num_mel_bins=dimensions["""n_mels"""] , d_model=dimensions["""n_audio_state"""] , max_target_positions=dimensions["""n_text_ctx"""] , encoder_layers=dimensions["""n_audio_layer"""] , encoder_attention_heads=dimensions["""n_audio_head"""] , decoder_layers=dimensions["""n_text_layer"""] , decoder_attention_heads=dimensions["""n_text_state"""] , max_source_positions=dimensions["""n_audio_ctx"""] , ) A__ : Optional[Any] = WhisperForConditionalGeneration(lowercase_ ) A__ , A__ : List[Any] = model.model.load_state_dict(lowercase_ , strict=lowercase_ ) if len(lowercase_ ) > 0 and not set(lowercase_ ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( """Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,""" f""" but all the following weights are missing {missing}""" ) if tie_embeds: A__ : Any = make_linear_from_emb(model.model.decoder.embed_tokens ) else: A__ : str = proj_out_weights model.save_pretrained(lowercase_ ) if __name__ == "__main__": A_ : Any = argparse.ArgumentParser() # # Required parameters parser.add_argument('--checkpoint_path', type=str, help='Patht to the downloaded checkpoints') parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') A_ : Tuple = parser.parse_args() convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)
64
0
import argparse import os from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_task_guides.py A_ : str = 'src/transformers' A_ : Union[str, Any] = 'docs/source/en/tasks' def UpperCamelCase (lowercase_: List[Any] , lowercase_: List[str] , lowercase_: List[Any] ) -> Tuple: with open(_lowerCamelCase , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: A__ : Dict = f.readlines() # Find the start prompt. A__ : str = 0 while not lines[start_index].startswith(_lowerCamelCase ): start_index += 1 start_index += 1 A__ : List[str] = start_index while not lines[end_index].startswith(_lowerCamelCase ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # This is to make sure the transformers module imported is the one in the repo. A_ : Dict = direct_transformers_import(TRANSFORMERS_PATH) A_ : Dict = { 'asr.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_CTC_MAPPING_NAMES, 'audio_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, 'language_modeling.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, 'image_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, 'masked_language_modeling.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_MASKED_LM_MAPPING_NAMES, 'multiple_choice.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES, 'object_detection.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, 'question_answering.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, 'semantic_segmentation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, 'sequence_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, 'summarization.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, 'token_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, 'translation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, 'video_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES, 'document_question_answering.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES, 'monocular_depth_estimation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, } # This list contains model types used in some task guides that are not in `CONFIG_MAPPING_NAMES` (therefore not in any # `MODEL_MAPPING_NAMES` or any `MODEL_FOR_XXX_MAPPING_NAMES`). A_ : Optional[Any] = { 'summarization.md': ('nllb',), 'translation.md': ('nllb',), } def UpperCamelCase (lowercase_: Union[str, Any] ) -> List[str]: A__ : Optional[int] = TASK_GUIDE_TO_MODELS[task_guide] A__ : str = SPECIAL_TASK_GUIDE_TO_MODEL_TYPES.get(_lowerCamelCase , set() ) A__ : Optional[int] = { code: name for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if (code in model_maping_names or code in special_model_types) } return ", ".join([f"""[{name}](../model_doc/{code})""" for code, name in model_names.items()] ) + "\n" def UpperCamelCase (lowercase_: Tuple , lowercase_: int=False ) -> Any: A__ : List[str] = _find_text_in_file( filename=os.path.join(_lowerCamelCase , _lowerCamelCase ) , start_prompt="""<!--This tip is automatically generated by `make fix-copies`, do not fill manually!-->""" , end_prompt="""<!--End of the generated tip-->""" , ) A__ : str = get_model_list_for_task(_lowerCamelCase ) if current_list != new_list: if overwrite: with open(os.path.join(_lowerCamelCase , _lowerCamelCase ) , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(lines[:start_index] + [new_list] + lines[end_index:] ) else: raise ValueError( f"""The list of models that can be used in the {task_guide} guide needs an update. Run `make fix-copies`""" """ to fix this.""" ) if __name__ == "__main__": A_ : Tuple = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') A_ : Dict = parser.parse_args() for task_guide in TASK_GUIDE_TO_MODELS.keys(): check_model_list_for_task(task_guide, args.fix_and_overwrite)
705
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DPMSolverMultistepScheduler, TextToVideoSDPipeline, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class _a (__magic_name__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: Any = TextToVideoSDPipeline UpperCAmelCase__: Any = TEXT_TO_IMAGE_PARAMS UpperCAmelCase__: Optional[Any] = TEXT_TO_IMAGE_BATCH_PARAMS # No `output_type`. UpperCAmelCase__: Optional[int] = frozenset( [ '''num_inference_steps''', '''generator''', '''latents''', '''return_dict''', '''callback''', '''callback_steps''', ] ) def __A ( self ): torch.manual_seed(0 ) A__ : Optional[int] = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """DownBlock3D""") , up_block_types=("""UpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""") , cross_attention_dim=32 , attention_head_dim=4 , ) A__ : Optional[int] = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule="""scaled_linear""" , clip_sample=A__ , set_alpha_to_one=A__ , ) torch.manual_seed(0 ) A__ : Union[str, Any] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) A__ : Union[str, Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act="""gelu""" , projection_dim=512 , ) A__ : Union[str, Any] = CLIPTextModel(A__ ) A__ : Tuple = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) A__ : Dict = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, } return components def __A ( self , A__ , A__=0 ): if str(A__ ).startswith("""mps""" ): A__ : Tuple = torch.manual_seed(A__ ) else: A__ : List[str] = torch.Generator(device=A__ ).manual_seed(A__ ) A__ : List[str] = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """pt""", } return inputs def __A ( self ): A__ : List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator A__ : Union[str, Any] = self.get_dummy_components() A__ : Union[str, Any] = TextToVideoSDPipeline(**A__ ) A__ : int = sd_pipe.to(A__ ) sd_pipe.set_progress_bar_config(disable=A__ ) A__ : int = self.get_dummy_inputs(A__ ) A__ : int = """np""" A__ : Any = sd_pipe(**A__ ).frames A__ : Dict = frames[0][-3:, -3:, -1] assert frames[0].shape == (64, 64, 3) A__ : Optional[Any] = np.array([1_5_8.0, 1_6_0.0, 1_5_3.0, 1_2_5.0, 1_0_0.0, 1_2_1.0, 1_1_1.0, 9_3.0, 1_1_3.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __A ( self ): self._test_attention_slicing_forward_pass(test_mean_pixel_difference=A__ , expected_max_diff=3e-3 ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def __A ( self ): self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=A__ , expected_max_diff=1e-2 ) @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def __A ( self ): pass @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def __A ( self ): pass @unittest.skip(reason="""`num_images_per_prompt` argument is not supported for this pipeline.""" ) def __A ( self ): pass def __A ( self ): return super().test_progress_bar() @slow @skip_mps class _a (unittest.TestCase ): '''simple docstring''' def __A ( self ): A__ : Union[str, Any] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy""" ) A__ : Tuple = TextToVideoSDPipeline.from_pretrained("""damo-vilab/text-to-video-ms-1.7b""" ) A__ : Any = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) A__ : int = pipe.to("""cuda""" ) A__ : Optional[Any] = """Spiderman is surfing""" A__ : List[str] = torch.Generator(device="""cpu""" ).manual_seed(0 ) A__ : Optional[Any] = pipe(A__ , generator=A__ , num_inference_steps=25 , output_type="""pt""" ).frames A__ : Dict = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5e-2 def __A ( self ): A__ : List[Any] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy""" ) A__ : Optional[int] = TextToVideoSDPipeline.from_pretrained("""damo-vilab/text-to-video-ms-1.7b""" ) A__ : List[str] = pipe.to("""cuda""" ) A__ : Dict = """Spiderman is surfing""" A__ : Union[str, Any] = torch.Generator(device="""cpu""" ).manual_seed(0 ) A__ : Optional[int] = pipe(A__ , generator=A__ , num_inference_steps=2 , output_type="""pt""" ).frames A__ : Optional[int] = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5e-2
64
0
from typing import TYPE_CHECKING from ....utils import _LazyModule A_ : Optional[int] = {"tokenization_tapex": ["TapexTokenizer"]} if TYPE_CHECKING: from .tokenization_tapex import TapexTokenizer else: import sys A_ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure)
706
def UpperCamelCase (lowercase_: int ) -> int: if not isinstance(lowercase_ , lowercase_ ): raise TypeError("""Input value must be an 'int' type""" ) A__ : int = 0 while number: position += 1 number >>= 1 return position if __name__ == "__main__": import doctest doctest.testmod()
64
0
from argparse import ArgumentParser from .env import EnvironmentCommand def UpperCamelCase () -> List[Any]: A__ : Any = ArgumentParser("""Diffusers CLI tool""" , usage="""diffusers-cli <command> [<args>]""" ) A__ : Dict = parser.add_subparsers(help="""diffusers-cli command helpers""" ) # Register commands EnvironmentCommand.register_subcommand(lowercase_ ) # Let's go A__ : Optional[Any] = parser.parse_args() if not hasattr(lowercase_ , """func""" ): parser.print_help() exit(1 ) # Run A__ : Union[str, Any] = args.func(lowercase_ ) service.run() if __name__ == "__main__": main()
707
from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def UpperCamelCase (lowercase_: np.ndarray , lowercase_: np.ndarray , lowercase_: np.ndarray , lowercase_: int , lowercase_: int ) -> np.ndarray: A__ : Any = cva.getAffineTransform(lowercase_ , lowercase_ ) return cva.warpAffine(lowercase_ , lowercase_ , (rows, cols) ) if __name__ == "__main__": # read original image A_ : List[Any] = cva.imread( str(Path(__file__).resolve().parent.parent / 'image_data' / 'lena.jpg') ) # turn image in gray scale value A_ : List[Any] = cva.cvtColor(image, cva.COLOR_BGR2GRAY) # get image shape A_ , A_ : Optional[Any] = gray_img.shape # set different points to rotate image A_ : str = np.array([[50, 50], [200, 50], [50, 200]], np.floataa) A_ : Dict = np.array([[10, 100], [200, 50], [100, 250]], np.floataa) A_ : Optional[int] = np.array([[50, 50], [150, 50], [120, 200]], np.floataa) A_ : Optional[int] = np.array([[10, 100], [80, 50], [180, 250]], np.floataa) # add all rotated images in a list A_ : Dict = [ 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_ : Union[str, Any] = plt.figure(1) A_ : Union[str, Any] = ['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()
64
0
from math import sqrt def UpperCamelCase (lowercase_: int ) -> Optional[int]: A__ : Any = 0 for i in range(1 , int(sqrt(lowerCAmelCase__ ) + 1 ) ): if n % i == 0 and i != sqrt(lowerCAmelCase__ ): total += i + n // i elif i == sqrt(lowerCAmelCase__ ): total += i return total - n def UpperCamelCase (lowercase_: int = 10000 ) -> Tuple: A__ : List[str] = sum( i for i in range(1 , lowerCAmelCase__ ) if sum_of_divisors(sum_of_divisors(lowerCAmelCase__ ) ) == i and sum_of_divisors(lowerCAmelCase__ ) != i ) return total if __name__ == "__main__": print(solution(int(str(input()).strip())))
708
import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class _a (unittest.TestCase ): '''simple docstring''' def __A ( self , A__ ): for model_result in results.values(): for batch_size, sequence_length in zip(model_result["""bs"""] , model_result["""ss"""] ): A__ : str = model_result["""result"""][batch_size][sequence_length] self.assertIsNotNone(A__ ) def __A ( self ): A__ : Dict = """sshleifer/tiny-gpt2""" A__ : Tuple = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : int = PyTorchBenchmark(A__ ) A__ : List[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ): A__ : Dict = """sgugger/tiny-distilbert-classification""" A__ : Dict = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , only_pretrain_model=A__ , ) A__ : str = PyTorchBenchmark(A__ ) A__ : List[str] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ): A__ : Any = """sshleifer/tiny-gpt2""" A__ : List[Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , torchscript=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : Tuple = PyTorchBenchmark(A__ ) A__ : str = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == """cpu""" , """Cant do half precision""" ) def __A ( self ): A__ : Optional[Any] = """sshleifer/tiny-gpt2""" A__ : Optional[Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , fpaa=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : str = PyTorchBenchmark(A__ ) A__ : Any = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ): A__ : Optional[Any] = """sshleifer/tiny-gpt2""" A__ : Tuple = AutoConfig.from_pretrained(A__ ) # set architectures equal to `None` A__ : List[Any] = None A__ : str = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : List[str] = PyTorchBenchmark(A__ , configs=[config] ) A__ : Any = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ): A__ : Optional[int] = """sshleifer/tiny-gpt2""" A__ : Optional[int] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : Any = PyTorchBenchmark(A__ ) A__ : Dict = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == """cpu""" , """Can't do half precision""" ) def __A ( self ): A__ : Optional[int] = """sshleifer/tiny-gpt2""" A__ : List[str] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , fpaa=A__ , multi_process=A__ , ) A__ : Dict = PyTorchBenchmark(A__ ) A__ : Optional[int] = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __A ( self ): A__ : int = """sshleifer/tiny-gpt2""" A__ : Optional[int] = AutoConfig.from_pretrained(A__ ) A__ : str = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : int = PyTorchBenchmark(A__ , configs=[config] ) A__ : Tuple = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ): A__ : List[str] = """sshleifer/tinier_bart""" A__ : List[str] = AutoConfig.from_pretrained(A__ ) A__ : List[str] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : Union[str, Any] = PyTorchBenchmark(A__ , configs=[config] ) A__ : str = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ): A__ : Optional[int] = """sshleifer/tiny-gpt2""" A__ : Union[str, Any] = AutoConfig.from_pretrained(A__ ) A__ : Tuple = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : int = PyTorchBenchmark(A__ , configs=[config] ) A__ : Tuple = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __A ( self ): A__ : Dict = """sshleifer/tinier_bart""" A__ : int = AutoConfig.from_pretrained(A__ ) A__ : Union[str, Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : List[Any] = PyTorchBenchmark(A__ , configs=[config] ) A__ : Optional[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __A ( self ): A__ : int = """sshleifer/tiny-gpt2""" with tempfile.TemporaryDirectory() as tmp_dir: A__ : Dict = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , save_to_csv=A__ , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(A__ , """inf_time.csv""" ) , train_memory_csv_file=os.path.join(A__ , """train_mem.csv""" ) , inference_memory_csv_file=os.path.join(A__ , """inf_mem.csv""" ) , train_time_csv_file=os.path.join(A__ , """train_time.csv""" ) , env_info_csv_file=os.path.join(A__ , """env.csv""" ) , multi_process=A__ , ) A__ : Optional[Any] = PyTorchBenchmark(A__ ) benchmark.run() self.assertTrue(Path(os.path.join(A__ , """inf_time.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(A__ , """train_time.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(A__ , """inf_mem.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(A__ , """train_mem.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(A__ , """env.csv""" ) ).exists() ) def __A ( self ): A__ : Optional[int] = """sshleifer/tiny-gpt2""" def _check_summary_is_not_empty(A__ ): self.assertTrue(hasattr(A__ , """sequential""" ) ) self.assertTrue(hasattr(A__ , """cumulative""" ) ) self.assertTrue(hasattr(A__ , """current""" ) ) self.assertTrue(hasattr(A__ , """total""" ) ) with tempfile.TemporaryDirectory() as tmp_dir: A__ : Dict = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(A__ , """log.txt""" ) , log_print=A__ , trace_memory_line_by_line=A__ , multi_process=A__ , ) A__ : Dict = PyTorchBenchmark(A__ ) A__ : str = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(A__ , """log.txt""" ) ).exists() )
64
0
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable A_ : List[str] = {'configuration_gpt_neox': ['GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GPTNeoXConfig']} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Any = ['GPTNeoXTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Tuple = [ 'GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST', 'GPTNeoXForCausalLM', 'GPTNeoXForQuestionAnswering', 'GPTNeoXForSequenceClassification', 'GPTNeoXForTokenClassification', 'GPTNeoXLayer', 'GPTNeoXModel', 'GPTNeoXPreTrainedModel', ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys A_ : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
709
# tests directory-specific settings - this file is run automatically # by pytest before any tests are run import doctest import sys import warnings from os.path import abspath, dirname, join import _pytest from transformers.testing_utils import HfDoctestModule, HfDocTestParser # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. A_ : Optional[int] = abspath(join(dirname(__file__), 'src')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='ignore', category=FutureWarning) def UpperCamelCase (lowercase_: List[str] ) -> Any: config.addinivalue_line( """markers""" , """is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested""" ) config.addinivalue_line( """markers""" , """is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested""" ) config.addinivalue_line("""markers""" , """is_pipeline_test: mark test to run only when pipelines are tested""" ) config.addinivalue_line("""markers""" , """is_staging_test: mark test to run only in the staging environment""" ) config.addinivalue_line("""markers""" , """accelerate_tests: mark test that require accelerate""" ) config.addinivalue_line("""markers""" , """tool_tests: mark the tool tests that are run on their specific schedule""" ) def UpperCamelCase (lowercase_: Optional[int] ) -> Optional[Any]: from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(lowercase_ ) def UpperCamelCase (lowercase_: List[str] ) -> Optional[Any]: from transformers.testing_utils import pytest_terminal_summary_main A__ : List[Any] = terminalreporter.config.getoption("""--make-reports""" ) if make_reports: pytest_terminal_summary_main(lowercase_ , id=lowercase_ ) def UpperCamelCase (lowercase_: Union[str, Any] , lowercase_: int ) -> List[str]: # If no tests are collected, pytest exists with code 5, which makes the CI fail. if exitstatus == 5: A__ : Tuple = 0 # Doctest custom flag to ignore output. A_ : Tuple = doctest.register_optionflag('IGNORE_RESULT') A_ : Dict = doctest.OutputChecker class _a (__magic_name__ ): '''simple docstring''' def __A ( self , A__ , A__ , A__ ): if IGNORE_RESULT & optionflags: return True return OutputChecker.check_output(self , A__ , A__ , A__ ) A_ : str = CustomOutputChecker A_ : Dict = HfDoctestModule A_ : Optional[int] = HfDocTestParser
64
0
import argparse import json import os import numpy as np import PIL import requests import tensorflow.keras.applications.efficientnet as efficientnet import torch from huggingface_hub import hf_hub_download from PIL import Image from tensorflow.keras.preprocessing import image from transformers import ( EfficientNetConfig, EfficientNetForImageClassification, EfficientNetImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() A_ : Any = logging.get_logger(__name__) A_ : Tuple = { 'b0': efficientnet.EfficientNetBa, 'b1': efficientnet.EfficientNetBa, 'b2': efficientnet.EfficientNetBa, 'b3': efficientnet.EfficientNetBa, 'b4': efficientnet.EfficientNetBa, 'b5': efficientnet.EfficientNetBa, 'b6': efficientnet.EfficientNetBa, 'b7': efficientnet.EfficientNetBa, } A_ : List[Any] = { 'b0': { 'hidden_dim': 1280, 'width_coef': 1.0, 'depth_coef': 1.0, 'image_size': 224, 'dropout_rate': 0.2, 'dw_padding': [], }, 'b1': { 'hidden_dim': 1280, 'width_coef': 1.0, 'depth_coef': 1.1, 'image_size': 240, 'dropout_rate': 0.2, 'dw_padding': [16], }, 'b2': { 'hidden_dim': 1408, 'width_coef': 1.1, 'depth_coef': 1.2, 'image_size': 260, 'dropout_rate': 0.3, 'dw_padding': [5, 8, 16], }, 'b3': { 'hidden_dim': 1536, 'width_coef': 1.2, 'depth_coef': 1.4, 'image_size': 300, 'dropout_rate': 0.3, 'dw_padding': [5, 18], }, 'b4': { 'hidden_dim': 1792, 'width_coef': 1.4, 'depth_coef': 1.8, 'image_size': 380, 'dropout_rate': 0.4, 'dw_padding': [6], }, 'b5': { 'hidden_dim': 2048, 'width_coef': 1.6, 'depth_coef': 2.2, 'image_size': 456, 'dropout_rate': 0.4, 'dw_padding': [13, 27], }, 'b6': { 'hidden_dim': 2304, 'width_coef': 1.8, 'depth_coef': 2.6, 'image_size': 528, 'dropout_rate': 0.5, 'dw_padding': [31], }, 'b7': { 'hidden_dim': 2560, 'width_coef': 2.0, 'depth_coef': 3.1, 'image_size': 600, 'dropout_rate': 0.5, 'dw_padding': [18], }, } def UpperCamelCase (lowercase_: Any ) -> int: A__ : Optional[int] = EfficientNetConfig() A__ : List[Any] = CONFIG_MAP[model_name]["""hidden_dim"""] A__ : str = CONFIG_MAP[model_name]["""width_coef"""] A__ : List[Any] = CONFIG_MAP[model_name]["""depth_coef"""] A__ : Optional[int] = CONFIG_MAP[model_name]["""image_size"""] A__ : Tuple = CONFIG_MAP[model_name]["""dropout_rate"""] A__ : List[str] = CONFIG_MAP[model_name]["""dw_padding"""] A__ : Optional[Any] = """huggingface/label-files""" A__ : Tuple = """imagenet-1k-id2label.json""" A__ : Union[str, Any] = 1000 A__ : Union[str, Any] = json.load(open(hf_hub_download(lowercase_ , lowercase_ , repo_type="""dataset""" ) , """r""" ) ) A__ : Any = {int(lowercase_ ): v for k, v in idalabel.items()} A__ : Any = idalabel A__ : List[str] = {v: k for k, v in idalabel.items()} return config def UpperCamelCase () -> Tuple: A__ : str = """http://images.cocodataset.org/val2017/000000039769.jpg""" A__ : Union[str, Any] = Image.open(requests.get(lowercase_ , stream=lowercase_ ).raw ) return im def UpperCamelCase (lowercase_: str ) -> List[Any]: A__ : Any = CONFIG_MAP[model_name]["""image_size"""] A__ : Tuple = EfficientNetImageProcessor( size={"""height""": size, """width""": size} , image_mean=[0.485, 0.456, 0.406] , image_std=[0.4785_3944, 0.473_2864, 0.4743_4163] , do_center_crop=lowercase_ , ) return preprocessor def UpperCamelCase (lowercase_: int ) -> Any: A__ : Optional[int] = [v.split("""_""" )[0].split("""block""" )[1] for v in original_param_names if v.startswith("""block""" )] A__ : List[Any] = sorted(set(lowercase_ ) ) A__ : List[Any] = len(lowercase_ ) A__ : Dict = {b: str(lowercase_ ) for b, i in zip(lowercase_ , range(lowercase_ ) )} A__ : Dict = [] rename_keys.append(("""stem_conv/kernel:0""", """embeddings.convolution.weight""") ) rename_keys.append(("""stem_bn/gamma:0""", """embeddings.batchnorm.weight""") ) rename_keys.append(("""stem_bn/beta:0""", """embeddings.batchnorm.bias""") ) rename_keys.append(("""stem_bn/moving_mean:0""", """embeddings.batchnorm.running_mean""") ) rename_keys.append(("""stem_bn/moving_variance:0""", """embeddings.batchnorm.running_var""") ) for b in block_names: A__ : str = block_name_mapping[b] rename_keys.append((f"""block{b}_expand_conv/kernel:0""", f"""encoder.blocks.{hf_b}.expansion.expand_conv.weight""") ) rename_keys.append((f"""block{b}_expand_bn/gamma:0""", f"""encoder.blocks.{hf_b}.expansion.expand_bn.weight""") ) rename_keys.append((f"""block{b}_expand_bn/beta:0""", f"""encoder.blocks.{hf_b}.expansion.expand_bn.bias""") ) rename_keys.append( (f"""block{b}_expand_bn/moving_mean:0""", f"""encoder.blocks.{hf_b}.expansion.expand_bn.running_mean""") ) rename_keys.append( (f"""block{b}_expand_bn/moving_variance:0""", f"""encoder.blocks.{hf_b}.expansion.expand_bn.running_var""") ) rename_keys.append( (f"""block{b}_dwconv/depthwise_kernel:0""", f"""encoder.blocks.{hf_b}.depthwise_conv.depthwise_conv.weight""") ) rename_keys.append((f"""block{b}_bn/gamma:0""", f"""encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.weight""") ) rename_keys.append((f"""block{b}_bn/beta:0""", f"""encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.bias""") ) rename_keys.append( (f"""block{b}_bn/moving_mean:0""", f"""encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_mean""") ) rename_keys.append( (f"""block{b}_bn/moving_variance:0""", f"""encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_var""") ) rename_keys.append((f"""block{b}_se_reduce/kernel:0""", f"""encoder.blocks.{hf_b}.squeeze_excite.reduce.weight""") ) rename_keys.append((f"""block{b}_se_reduce/bias:0""", f"""encoder.blocks.{hf_b}.squeeze_excite.reduce.bias""") ) rename_keys.append((f"""block{b}_se_expand/kernel:0""", f"""encoder.blocks.{hf_b}.squeeze_excite.expand.weight""") ) rename_keys.append((f"""block{b}_se_expand/bias:0""", f"""encoder.blocks.{hf_b}.squeeze_excite.expand.bias""") ) rename_keys.append( (f"""block{b}_project_conv/kernel:0""", f"""encoder.blocks.{hf_b}.projection.project_conv.weight""") ) rename_keys.append((f"""block{b}_project_bn/gamma:0""", f"""encoder.blocks.{hf_b}.projection.project_bn.weight""") ) rename_keys.append((f"""block{b}_project_bn/beta:0""", f"""encoder.blocks.{hf_b}.projection.project_bn.bias""") ) rename_keys.append( (f"""block{b}_project_bn/moving_mean:0""", f"""encoder.blocks.{hf_b}.projection.project_bn.running_mean""") ) rename_keys.append( (f"""block{b}_project_bn/moving_variance:0""", f"""encoder.blocks.{hf_b}.projection.project_bn.running_var""") ) rename_keys.append(("""top_conv/kernel:0""", """encoder.top_conv.weight""") ) rename_keys.append(("""top_bn/gamma:0""", """encoder.top_bn.weight""") ) rename_keys.append(("""top_bn/beta:0""", """encoder.top_bn.bias""") ) rename_keys.append(("""top_bn/moving_mean:0""", """encoder.top_bn.running_mean""") ) rename_keys.append(("""top_bn/moving_variance:0""", """encoder.top_bn.running_var""") ) A__ : Optional[int] = {} for item in rename_keys: if item[0] in original_param_names: A__ : Tuple = """efficientnet.""" + item[1] A__ : Any = """classifier.weight""" A__ : str = """classifier.bias""" return key_mapping def UpperCamelCase (lowercase_: Optional[int] , lowercase_: Any , lowercase_: Dict ) -> str: for key, value in tf_params.items(): if "normalization" in key: continue A__ : Optional[int] = key_mapping[key] if "_conv" in key and "kernel" in key: A__ : Any = torch.from_numpy(lowercase_ ).permute(3 , 2 , 0 , 1 ) elif "depthwise_kernel" in key: A__ : Any = torch.from_numpy(lowercase_ ).permute(2 , 3 , 0 , 1 ) elif "kernel" in key: A__ : List[str] = torch.from_numpy(np.transpose(lowercase_ ) ) else: A__ : List[Any] = torch.from_numpy(lowercase_ ) # Replace HF parameters with original TF model parameters assert hf_params[hf_key].shape == new_hf_value.shape hf_params[hf_key].copy_(lowercase_ ) @torch.no_grad() def UpperCamelCase (lowercase_: List[Any] , lowercase_: Dict , lowercase_: int , lowercase_: Any ) -> Any: A__ : Any = model_classes[model_name]( include_top=lowercase_ , weights="""imagenet""" , input_tensor=lowercase_ , input_shape=lowercase_ , pooling=lowercase_ , classes=1000 , classifier_activation="""softmax""" , ) A__ : str = original_model.trainable_variables A__ : int = original_model.non_trainable_variables A__ : List[str] = {param.name: param.numpy() for param in tf_params} for param in tf_non_train_params: A__ : int = param.numpy() A__ : str = list(tf_params.keys() ) # Load HuggingFace model A__ : int = get_efficientnet_config(lowercase_ ) A__ : List[str] = EfficientNetForImageClassification(lowercase_ ).eval() A__ : int = hf_model.state_dict() # Create src-to-dst parameter name mapping dictionary print("""Converting parameters...""" ) A__ : str = rename_keys(lowercase_ ) replace_params(lowercase_ , lowercase_ , lowercase_ ) # Initialize preprocessor and preprocess input image A__ : str = convert_image_processor(lowercase_ ) A__ : Union[str, Any] = preprocessor(images=prepare_img() , return_tensors="""pt""" ) # HF model inference hf_model.eval() with torch.no_grad(): A__ : str = hf_model(**lowercase_ ) A__ : Union[str, Any] = outputs.logits.detach().numpy() # Original model inference A__ : str = False A__ : Optional[Any] = CONFIG_MAP[model_name]["""image_size"""] A__ : int = prepare_img().resize((image_size, image_size) , resample=PIL.Image.NEAREST ) A__ : Optional[Any] = image.img_to_array(lowercase_ ) A__ : Tuple = np.expand_dims(lowercase_ , axis=0 ) A__ : int = original_model.predict(lowercase_ ) # Check whether original and HF model outputs match -> np.allclose assert np.allclose(lowercase_ , lowercase_ , atol=1E-3 ), "The predicted logits are not the same." print("""Model outputs match!""" ) if save_model: # Create folder to save model if not os.path.isdir(lowercase_ ): os.mkdir(lowercase_ ) # Save converted model and image processor hf_model.save_pretrained(lowercase_ ) preprocessor.save_pretrained(lowercase_ ) if push_to_hub: # Push model and image processor to hub print(f"""Pushing converted {model_name} to the hub...""" ) A__ : str = f"""efficientnet-{model_name}""" preprocessor.push_to_hub(lowercase_ ) hf_model.push_to_hub(lowercase_ ) if __name__ == "__main__": A_ : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='b0', type=str, help='Version name of the EfficientNet model you want to convert, select from [b0, b1, b2, b3, b4, b5, b6, b7].', ) parser.add_argument( '--pytorch_dump_folder_path', default='hf_model', type=str, help='Path to the output PyTorch model directory.', ) parser.add_argument('--save_model', action='store_true', help='Save model to local') parser.add_argument('--push_to_hub', action='store_true', help='Push model and image processor to the hub') A_ : List[str] = parser.parse_args() convert_efficientnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.save_model, args.push_to_hub)
710
from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, 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, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class _a : '''simple docstring''' UpperCAmelCase__: List[Any] = PegasusConfig UpperCAmelCase__: Optional[int] = {} UpperCAmelCase__: List[str] = '''gelu''' def __init__( self , A__ , A__=13 , A__=7 , A__=True , A__=False , A__=99 , A__=32 , A__=2 , A__=4 , A__=37 , A__=0.1 , A__=0.1 , A__=40 , A__=2 , A__=1 , A__=0 , ): A__ : Dict = parent A__ : Dict = batch_size A__ : Any = seq_length A__ : Optional[Any] = is_training A__ : int = use_labels A__ : Any = vocab_size A__ : Union[str, Any] = hidden_size A__ : Tuple = num_hidden_layers A__ : Tuple = num_attention_heads A__ : List[Any] = intermediate_size A__ : Union[str, Any] = hidden_dropout_prob A__ : Optional[Any] = attention_probs_dropout_prob A__ : List[Any] = max_position_embeddings A__ : Any = eos_token_id A__ : List[Any] = pad_token_id A__ : List[Any] = bos_token_id def __A ( self ): A__ : str = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) A__ : Dict = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) A__ : List[Any] = tf.concat([input_ids, eos_tensor] , axis=1 ) A__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ : Tuple = 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 , ) A__ : str = prepare_pegasus_inputs_dict(A__ , A__ , A__ ) return config, inputs_dict def __A ( self , A__ , A__ ): A__ : int = TFPegasusModel(config=A__ ).get_decoder() A__ : List[Any] = inputs_dict["""input_ids"""] A__ : Any = input_ids[:1, :] A__ : Optional[Any] = inputs_dict["""attention_mask"""][:1, :] A__ : Optional[int] = inputs_dict["""head_mask"""] A__ : Any = 1 # first forward pass A__ : Tuple = model(A__ , attention_mask=A__ , head_mask=A__ , use_cache=A__ ) A__ , A__ : Dict = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids A__ : Tuple = ids_tensor((self.batch_size, 3) , config.vocab_size ) A__ : Optional[Any] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and A__ : List[Any] = tf.concat([input_ids, next_tokens] , axis=-1 ) A__ : Tuple = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) A__ : Optional[Any] = model(A__ , attention_mask=A__ )[0] A__ : Any = model(A__ , attention_mask=A__ , past_key_values=A__ )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice A__ : int = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) A__ : Any = output_from_no_past[:, -3:, random_slice_idx] A__ : Tuple = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(A__ , A__ , rtol=1e-3 ) def UpperCamelCase (lowercase_: Union[str, Any] , lowercase_: Dict , lowercase_: List[Any] , lowercase_: Dict=None , lowercase_: int=None , lowercase_: List[Any]=None , lowercase_: List[Any]=None , lowercase_: str=None , ) -> int: if attention_mask is None: A__ : List[str] = tf.cast(tf.math.not_equal(lowercase_ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: A__ : Dict = 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: A__ : Any = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: A__ : Tuple = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: A__ : List[str] = 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 (__magic_name__ , __magic_name__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: List[Any] = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () UpperCAmelCase__: Tuple = (TFPegasusForConditionalGeneration,) if is_tf_available() else () UpperCAmelCase__: Tuple = ( { '''conversational''': TFPegasusForConditionalGeneration, '''feature-extraction''': TFPegasusModel, '''summarization''': TFPegasusForConditionalGeneration, '''text2text-generation''': TFPegasusForConditionalGeneration, '''translation''': TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) UpperCAmelCase__: int = True UpperCAmelCase__: Union[str, Any] = False UpperCAmelCase__: List[str] = False def __A ( self ): A__ : Optional[Any] = TFPegasusModelTester(self ) A__ : Tuple = ConfigTester(self , config_class=A__ ) def __A ( self ): self.config_tester.run_common_tests() def __A ( self ): A__ : int = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*A__ ) @require_sentencepiece @require_tokenizers @require_tf class _a (unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: Optional[int] = [ ''' 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!" ''', ] UpperCAmelCase__: Any = [ '''California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to''' ''' reduce the risk of wildfires.''', '''N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.''', ] # differs slightly from pytorch, likely due to numerical differences in linear layers UpperCAmelCase__: List[str] = '''google/pegasus-xsum''' @cached_property def __A ( self ): return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def __A ( self ): A__ : int = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def __A ( self , **A__ ): A__ : str = self.translate_src_text(**A__ ) assert self.expected_text == generated_words def __A ( self , **A__ ): A__ : List[str] = self.tokenizer(self.src_text , **A__ , padding=A__ , return_tensors="""tf""" ) A__ : Optional[int] = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=A__ , ) A__ : Dict = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=A__ ) return generated_words @slow def __A ( self ): self._assert_generated_batch_equal_expected()
64
0
import gc import unittest from transformers import CTRLConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, ) class _a : '''simple docstring''' def __init__( self , A__ , A__=14 , A__=7 , A__=True , A__=True , A__=True , A__=True , A__=True , A__=99 , A__=32 , A__=5 , A__=4 , A__=37 , A__="gelu" , A__=0.1 , A__=0.1 , A__=512 , A__=16 , A__=2 , A__=0.0_2 , A__=3 , A__=4 , A__=None , ): A__ : int = parent A__ : Any = batch_size A__ : Any = seq_length A__ : Union[str, Any] = is_training A__ : Dict = use_token_type_ids A__ : Dict = use_input_mask A__ : Tuple = use_labels A__ : List[str] = use_mc_token_ids A__ : Union[str, Any] = vocab_size A__ : Tuple = hidden_size A__ : List[Any] = num_hidden_layers A__ : Tuple = num_attention_heads A__ : Tuple = intermediate_size A__ : Dict = hidden_act A__ : Union[str, Any] = hidden_dropout_prob A__ : Optional[int] = attention_probs_dropout_prob A__ : int = max_position_embeddings A__ : Optional[Any] = type_vocab_size A__ : Optional[int] = type_sequence_label_size A__ : List[Any] = initializer_range A__ : Union[str, Any] = num_labels A__ : Any = num_choices A__ : Tuple = scope A__ : Tuple = self.vocab_size - 1 def __A ( self ): A__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ : int = None if self.use_input_mask: A__ : List[Any] = random_attention_mask([self.batch_size, self.seq_length] ) A__ : str = None if self.use_token_type_ids: A__ : int = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) A__ : List[Any] = None if self.use_mc_token_ids: A__ : List[Any] = ids_tensor([self.batch_size, self.num_choices] , self.seq_length ) A__ : Union[str, Any] = None A__ : Optional[Any] = None A__ : List[str] = None if self.use_labels: A__ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A__ : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) A__ : Any = self.get_config() A__ : Any = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, sequence_labels, token_labels, choice_labels, ) def __A ( self ): return CTRLConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) def __A ( self , A__ , A__ , A__ , A__ , A__ , *A__ ): A__ : Optional[int] = CTRLModel(config=lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() model(lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ , head_mask=lowerCAmelCase_ ) model(lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ ) A__ : Union[str, Any] = model(lowerCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(len(result.past_key_values ) , config.n_layer ) def __A ( self , A__ , A__ , A__ , A__ , A__ , *A__ ): A__ : str = CTRLLMHeadModel(lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() A__ : str = model(lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ , labels=lowerCAmelCase_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __A ( self ): A__ : int = self.prepare_config_and_inputs() ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) : List[str] = config_and_inputs A__ : Any = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """head_mask""": head_mask} return config, inputs_dict def __A ( self , A__ , A__ , A__ , A__ , *A__ ): A__ : Optional[int] = self.num_labels A__ : Union[str, Any] = CTRLForSequenceClassification(lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() A__ : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ : Any = model(lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ , labels=lowerCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) @require_torch class _a (__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: Dict = (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else () UpperCAmelCase__: Optional[int] = (CTRLLMHeadModel,) if is_torch_available() else () UpperCAmelCase__: Union[str, Any] = ( { '''feature-extraction''': CTRLModel, '''text-classification''': CTRLForSequenceClassification, '''text-generation''': CTRLLMHeadModel, '''zero-shot''': CTRLForSequenceClassification, } if is_torch_available() else {} ) UpperCAmelCase__: Tuple = True UpperCAmelCase__: Optional[int] = False UpperCAmelCase__: Optional[int] = False def __A ( self , A__ , A__ , A__ , A__ , A__ ): if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny # config could not be created. return True return False def __A ( self ): A__ : int = CTRLModelTester(self ) A__ : Union[str, Any] = ConfigTester(self , config_class=lowerCAmelCase_ , n_embd=37 ) def __A ( self ): super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() def __A ( self ): self.config_tester.run_common_tests() def __A ( self ): A__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_ctrl_model(*lowerCAmelCase_ ) def __A ( self ): A__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*lowerCAmelCase_ ) @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def __A ( self ): pass @slow def __A ( self ): for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ : Any = CTRLModel.from_pretrained(lowerCAmelCase_ ) self.assertIsNotNone(lowerCAmelCase_ ) @unittest.skip("""The model doesn't support left padding""" ) # and it's not used enough to be worth fixing :) def __A ( self ): pass @require_torch class _a (unittest.TestCase ): '''simple docstring''' def __A ( self ): super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() @slow def __A ( self ): A__ : str = CTRLLMHeadModel.from_pretrained("""ctrl""" ) model.to(lowerCAmelCase_ ) A__ : str = torch.tensor( [[1_1859, 0, 1611, 8]] , dtype=torch.long , device=lowerCAmelCase_ ) # Legal the president is A__ : int = [ 1_1859, 0, 1611, 8, 5, 150, 2_6449, 2, 19, 348, 469, 3, 2595, 48, 2_0740, 24_6533, 24_6533, 19, 30, 5, ] # Legal the president is a good guy and I don't want to lose my job. \n \n I have a A__ : Any = model.generate(lowerCAmelCase_ , do_sample=lowerCAmelCase_ ) self.assertListEqual(output_ids[0].tolist() , lowerCAmelCase_ )
711
class _a : '''simple docstring''' def __init__( self ): A__ : str = """""" A__ : Any = """""" A__ : List[Any] = [] def __A ( self , A__ , A__ ): if m == -1: return n + 1 elif n == -1: return m + 1 elif self.dp[m][n] > -1: return self.dp[m][n] else: if self.worda[m] == self.worda[n]: A__ : Optional[Any] = self.__min_dist_top_down_dp(m - 1 , n - 1 ) else: A__ : Union[str, Any] = self.__min_dist_top_down_dp(A__ , n - 1 ) A__ : Union[str, Any] = self.__min_dist_top_down_dp(m - 1 , A__ ) A__ : Union[str, Any] = self.__min_dist_top_down_dp(m - 1 , n - 1 ) A__ : List[Any] = 1 + min(A__ , A__ , A__ ) return self.dp[m][n] def __A ( self , A__ , A__ ): A__ : Tuple = worda A__ : Dict = worda A__ : Optional[Any] = [[-1 for _ in range(len(A__ ) )] for _ in range(len(A__ ) )] return self.__min_dist_top_down_dp(len(A__ ) - 1 , len(A__ ) - 1 ) def __A ( self , A__ , A__ ): A__ : Optional[Any] = worda A__ : Dict = worda A__ : Union[str, Any] = len(A__ ) A__ : List[str] = len(A__ ) A__ : int = [[0 for _ in range(n + 1 )] for _ in range(m + 1 )] for i in range(m + 1 ): for j in range(n + 1 ): if i == 0: # first string is empty A__ : Tuple = j elif j == 0: # second string is empty A__ : Dict = i elif worda[i - 1] == worda[j - 1]: # last characters are equal A__ : str = self.dp[i - 1][j - 1] else: A__ : Union[str, Any] = self.dp[i][j - 1] A__ : str = self.dp[i - 1][j] A__ : Union[str, Any] = self.dp[i - 1][j - 1] A__ : Tuple = 1 + min(A__ , A__ , A__ ) return self.dp[m][n] if __name__ == "__main__": A_ : Union[str, Any] = EditDistance() print('****************** Testing Edit Distance DP Algorithm ******************') print() A_ : int = input('Enter the first string: ').strip() A_ : List[str] = input('Enter the second string: ').strip() print() print(f'''The minimum edit distance is: {solver.min_dist_top_down(Sa, Sa)}''') print(f'''The minimum edit distance is: {solver.min_dist_bottom_up(Sa, Sa)}''') print() print('*************** End of Testing Edit Distance DP Algorithm ***************')
64
0
import warnings 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 _a (_UpperCamelCase ): '''simple docstring''' UpperCAmelCase__: Union[str, Any] = ['''image_processor''', '''tokenizer'''] UpperCAmelCase__: Union[str, Any] = '''FlavaImageProcessor''' UpperCAmelCase__: Union[str, Any] = ('''BertTokenizer''', '''BertTokenizerFast''') def __init__( self , A__=None , A__=None , **A__ ): A__ : str = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , _UpperCAmelCase , ) A__ : Optional[Any] = kwargs.pop("""feature_extractor""" ) A__ : Tuple = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""" ) if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""" ) super().__init__(_UpperCAmelCase , _UpperCAmelCase ) A__ : Optional[Any] = self.image_processor def __call__( self , A__ = None , A__ = None , A__ = True , A__ = False , A__ = False , A__ = None , A__ = 0 , A__ = None , A__ = None , A__ = None , A__ = None , A__ = None , A__ = False , A__ = False , A__ = False , A__ = False , A__ = True , A__ = None , **A__ , ): if text is None and images is None: raise ValueError("""You have to specify either text or images. Both cannot be none.""" ) if text is not None: A__ : List[str] = self.tokenizer( text=_UpperCAmelCase , add_special_tokens=_UpperCAmelCase , padding=_UpperCAmelCase , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase , stride=_UpperCAmelCase , pad_to_multiple_of=_UpperCAmelCase , return_token_type_ids=_UpperCAmelCase , return_attention_mask=_UpperCAmelCase , return_overflowing_tokens=_UpperCAmelCase , return_special_tokens_mask=_UpperCAmelCase , return_offsets_mapping=_UpperCAmelCase , return_length=_UpperCAmelCase , verbose=_UpperCAmelCase , return_tensors=_UpperCAmelCase , **_UpperCAmelCase , ) if images is not None: A__ : Any = self.image_processor( _UpperCAmelCase , return_image_mask=_UpperCAmelCase , return_codebook_pixels=_UpperCAmelCase , return_tensors=_UpperCAmelCase , **_UpperCAmelCase , ) if text is not None and images is not None: encoding.update(_UpperCAmelCase ) return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**_UpperCAmelCase ) , tensor_type=_UpperCAmelCase ) def __A ( self , *A__ , **A__ ): return self.tokenizer.batch_decode(*_UpperCAmelCase , **_UpperCAmelCase ) def __A ( self , *A__ , **A__ ): return self.tokenizer.decode(*_UpperCAmelCase , **_UpperCAmelCase ) @property def __A ( self ): A__ : List[str] = self.tokenizer.model_input_names A__ : int = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def __A ( self ): 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 __A ( self ): warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , _UpperCAmelCase , ) return self.image_processor
712
def UpperCamelCase (lowercase_: int , lowercase_: int ) -> int: while second != 0: A__ : int = first & second first ^= second A__ : int = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() A_ : Optional[Any] = int(input('Enter the first number: ').strip()) A_ : List[str] = int(input('Enter the second number: ').strip()) print(f'''{add(first, second) = }''')
64
0
import argparse import re from pathlib import Path import requests import torch from PIL import Image from torchvision.transforms import CenterCrop, Compose, Normalize, Resize, ToTensor from transformers import ( EfficientFormerConfig, EfficientFormerForImageClassificationWithTeacher, EfficientFormerImageProcessor, ) from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling def UpperCamelCase (lowercase_: List[str] , lowercase_: Optional[int] ) -> Optional[int]: A__ : Optional[int] = old_name if "patch_embed" in old_name: A__ , A__ , A__ : Optional[int] = old_name.split(""".""" ) if layer == "0": A__ : Dict = old_name.replace("""0""" , """convolution1""" ) elif layer == "1": A__ : str = old_name.replace("""1""" , """batchnorm_before""" ) elif layer == "3": A__ : Union[str, Any] = old_name.replace("""3""" , """convolution2""" ) else: A__ : Any = old_name.replace("""4""" , """batchnorm_after""" ) if "network" in old_name and re.search(r"""\d\.\d""" , UpperCAmelCase__ ): A__ : Dict = r"""\b\d{2}\b""" if bool(re.search(UpperCAmelCase__ , UpperCAmelCase__ ) ): A__ : Dict = re.search(r"""\d\.\d\d.""" , UpperCAmelCase__ ).group() else: A__ : Optional[Any] = re.search(r"""\d\.\d.""" , UpperCAmelCase__ ).group() if int(match[0] ) < 6: A__ : Tuple = old_name.replace(UpperCAmelCase__ , """""" ) A__ : Optional[int] = trimmed_name.replace("""network""" , match[0] + """.meta4D_layers.blocks.""" + match[2:-1] ) A__ : List[str] = """intermediate_stages.""" + trimmed_name else: A__ : Union[str, Any] = old_name.replace(UpperCAmelCase__ , """""" ) if int(match[2] ) < num_meta4D_last_stage: A__ : Tuple = trimmed_name.replace("""network""" , """meta4D_layers.blocks.""" + match[2] ) else: A__ : Dict = str(int(match[2] ) - num_meta4D_last_stage ) A__ : Any = trimmed_name.replace("""network""" , """meta3D_layers.blocks.""" + layer_index ) if "norm1" in old_name: A__ : Tuple = trimmed_name.replace("""norm1""" , """layernorm1""" ) elif "norm2" in old_name: A__ : Union[str, Any] = trimmed_name.replace("""norm2""" , """layernorm2""" ) elif "fc1" in old_name: A__ : str = trimmed_name.replace("""fc1""" , """linear_in""" ) elif "fc2" in old_name: A__ : Optional[int] = trimmed_name.replace("""fc2""" , """linear_out""" ) A__ : int = """last_stage.""" + trimmed_name elif "network" in old_name and re.search(r""".\d.""" , UpperCAmelCase__ ): A__ : Dict = old_name.replace("""network""" , """intermediate_stages""" ) if "fc" in new_name: A__ : List[str] = new_name.replace("""fc""" , """convolution""" ) elif ("norm1" in new_name) and ("layernorm1" not in new_name): A__ : int = new_name.replace("""norm1""" , """batchnorm_before""" ) elif ("norm2" in new_name) and ("layernorm2" not in new_name): A__ : List[str] = new_name.replace("""norm2""" , """batchnorm_after""" ) if "proj" in new_name: A__ : Any = new_name.replace("""proj""" , """projection""" ) if "dist_head" in new_name: A__ : Tuple = new_name.replace("""dist_head""" , """distillation_classifier""" ) elif "head" in new_name: A__ : Dict = new_name.replace("""head""" , """classifier""" ) elif "patch_embed" in new_name: A__ : Dict = """efficientformer.""" + new_name elif new_name == "norm.weight" or new_name == "norm.bias": A__ : List[str] = new_name.replace("""norm""" , """layernorm""" ) A__ : Union[str, Any] = """efficientformer.""" + new_name else: A__ : Optional[Any] = """efficientformer.encoder.""" + new_name return new_name def UpperCamelCase (lowercase_: str , lowercase_: List[Any] ) -> Tuple: for key in checkpoint.copy().keys(): A__ : Optional[int] = checkpoint.pop(UpperCAmelCase__ ) A__ : Any = val return checkpoint def UpperCamelCase () -> List[str]: A__ : Tuple = """http://images.cocodataset.org/val2017/000000039769.jpg""" A__ : Optional[int] = Image.open(requests.get(UpperCAmelCase__ , stream=UpperCAmelCase__ ).raw ) return image def UpperCamelCase (lowercase_: List[str] , lowercase_: List[Any] , lowercase_: Dict , lowercase_: Tuple ) -> Tuple: A__ : int = torch.load(UpperCAmelCase__ , map_location="""cpu""" )["""model"""] A__ : Tuple = EfficientFormerConfig.from_json_file(UpperCAmelCase__ ) A__ : List[str] = EfficientFormerForImageClassificationWithTeacher(UpperCAmelCase__ ) A__ : Dict = """_""".join(checkpoint_path.split("""/""" )[-1].split(""".""" )[0].split("""_""" )[:-1] ) A__ : Optional[Any] = config.depths[-1] - config.num_metaad_blocks + 1 A__ : Any = convert_torch_checkpoint(UpperCAmelCase__ , UpperCAmelCase__ ) model.load_state_dict(UpperCAmelCase__ ) model.eval() A__ : List[str] = { """bilinear""": PILImageResampling.BILINEAR, """bicubic""": PILImageResampling.BICUBIC, """nearest""": PILImageResampling.NEAREST, } # prepare image A__ : str = prepare_img() A__ : Any = 256 A__ : Optional[int] = 224 A__ : List[Any] = EfficientFormerImageProcessor( size={"""shortest_edge""": image_size} , crop_size={"""height""": crop_size, """width""": crop_size} , resample=pillow_resamplings["""bicubic"""] , ) A__ : Optional[int] = processor(images=UpperCAmelCase__ , return_tensors="""pt""" ).pixel_values # original processing pipeline A__ : Union[str, Any] = Compose( [ Resize(UpperCAmelCase__ , interpolation=pillow_resamplings["""bicubic"""] ), CenterCrop(UpperCAmelCase__ ), ToTensor(), Normalize(UpperCAmelCase__ , UpperCAmelCase__ ), ] ) A__ : Tuple = image_transforms(UpperCAmelCase__ ).unsqueeze(0 ) assert torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ ) A__ : Union[str, Any] = model(UpperCAmelCase__ ) A__ : Optional[Any] = outputs.logits A__ : Tuple = (1, 1000) if "l1" in model_name: A__ : Union[str, Any] = torch.Tensor( [-0.1312, 0.4353, -1.0499, -0.5124, 0.4183, -0.6793, -1.3777, -0.0893, -0.7358, -2.4328] ) assert torch.allclose(logits[0, :10] , UpperCAmelCase__ , atol=1E-3 ) assert logits.shape == expected_shape elif "l3" in model_name: A__ : List[str] = torch.Tensor( [-1.3150, -1.5456, -1.2556, -0.8496, -0.7127, -0.7897, -0.9728, -0.3052, 0.3751, -0.3127] ) assert torch.allclose(logits[0, :10] , UpperCAmelCase__ , atol=1E-3 ) assert logits.shape == expected_shape elif "l7" in model_name: A__ : Optional[int] = torch.Tensor( [-1.0283, -1.4131, -0.5644, -1.3115, -0.5785, -1.2049, -0.7528, 0.1992, -0.3822, -0.0878] ) assert logits.shape == expected_shape else: raise ValueError( f"""Unknown model checkpoint: {checkpoint_path}. Supported version of efficientformer are l1, l3 and l7""" ) # Save Checkpoints Path(UpperCAmelCase__ ).mkdir(exist_ok=UpperCAmelCase__ ) model.save_pretrained(UpperCAmelCase__ ) print(f"""Checkpoint successfuly converted. Model saved at {pytorch_dump_path}""" ) processor.save_pretrained(UpperCAmelCase__ ) print(f"""Processor successfuly saved at {pytorch_dump_path}""" ) if push_to_hub: print("""Pushing model to the hub...""" ) model.push_to_hub( repo_id=f"""Bearnardd/{pytorch_dump_path}""" , commit_message="""Add model""" , use_temp_dir=UpperCAmelCase__ , ) processor.push_to_hub( repo_id=f"""Bearnardd/{pytorch_dump_path}""" , commit_message="""Add image processor""" , use_temp_dir=UpperCAmelCase__ , ) if __name__ == "__main__": A_ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( '--pytorch_model_path', default=None, type=str, required=True, help='Path to EfficientFormer pytorch checkpoint.', ) parser.add_argument( '--config_file', default=None, type=str, required=True, help='The json file for EfficientFormer model config.', ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument('--push_to_hub', action='store_true', help='Push model and image processor to the hub') parser.add_argument( '--no-push_to_hub', dest='push_to_hub', action='store_false', help='Do not push model and image processor to the hub', ) parser.set_defaults(push_to_hub=True) A_ : Optional[Any] = parser.parse_args() convert_efficientformer_checkpoint( checkpoint_path=args.pytorch_model_path, efficientformer_config_file=args.config_file, pytorch_dump_path=args.pytorch_dump_path, push_to_hub=args.push_to_hub, )
713
from __future__ import annotations from collections.abc import Callable A_ : List[Any] = list[list[float | int]] def UpperCamelCase (lowercase_: Matrix , lowercase_: Matrix ) -> Matrix: A__ : int = len(lowercase_ ) A__ : Matrix = [[0 for _ in range(size + 1 )] for _ in range(lowercase_ )] A__ : int A__ : int A__ : int A__ : int A__ : int A__ : float for row in range(lowercase_ ): for col in range(lowercase_ ): A__ : List[str] = matrix[row][col] A__ : int = vector[row][0] A__ : Optional[int] = 0 A__ : str = 0 while row < size and col < size: # pivoting A__ : int = max((abs(augmented[rowa][col] ), rowa) for rowa in range(lowercase_ , lowercase_ ) )[ 1 ] if augmented[pivot_row][col] == 0: col += 1 continue else: A__ , A__ : Union[str, Any] = augmented[pivot_row], augmented[row] for rowa in range(row + 1 , lowercase_ ): A__ : List[Any] = augmented[rowa][col] / augmented[row][col] A__ : Dict = 0 for cola in range(col + 1 , size + 1 ): augmented[rowa][cola] -= augmented[row][cola] * ratio row += 1 col += 1 # back substitution for col in range(1 , lowercase_ ): for row in range(lowercase_ ): A__ : List[str] = augmented[row][col] / augmented[col][col] for cola in range(lowercase_ , size + 1 ): augmented[row][cola] -= augmented[col][cola] * ratio # round to get rid of numbers like 2.000000000000004 return [ [round(augmented[row][size] / augmented[row][row] , 10 )] for row in range(lowercase_ ) ] def UpperCamelCase (lowercase_: list[int] ) -> Callable[[int], int]: A__ : int = len(lowercase_ ) A__ : Matrix = [[0 for _ in range(lowercase_ )] for _ in range(lowercase_ )] A__ : Matrix = [[0] for _ in range(lowercase_ )] A__ : Matrix A__ : int A__ : int A__ : int for x_val, y_val in enumerate(lowercase_ ): for col in range(lowercase_ ): A__ : Dict = (x_val + 1) ** (size - col - 1) A__ : Any = y_val A__ : Union[str, Any] = solve(lowercase_ , lowercase_ ) def interpolated_func(lowercase_: int ) -> int: return sum( round(coeffs[x_val][0] ) * (var ** (size - x_val - 1)) for x_val in range(lowercase_ ) ) return interpolated_func def UpperCamelCase (lowercase_: int ) -> int: return ( 1 - variable + variable**2 - variable**3 + variable**4 - variable**5 + variable**6 - variable**7 + variable**8 - variable**9 + variable**10 ) def UpperCamelCase (lowercase_: Callable[[int], int] = question_function , lowercase_: int = 10 ) -> int: A__ : list[int] = [func(lowercase_ ) for x_val in range(1 , order + 1 )] A__ : list[Callable[[int], int]] = [ interpolate(data_points[:max_coeff] ) for max_coeff in range(1 , order + 1 ) ] A__ : int = 0 A__ : Callable[[int], int] A__ : int for poly in polynomials: A__ : List[str] = 1 while func(lowercase_ ) == poly(lowercase_ ): x_val += 1 ret += poly(lowercase_ ) return ret if __name__ == "__main__": print(f'''{solution() = }''')
64
0
from ..utils import DummyObject, requires_backends class _a (metaclass=__magic_name__ ): '''simple docstring''' UpperCAmelCase__: Optional[int] = ['''torch''', '''scipy'''] def __init__( self , *A__ , **A__ ): requires_backends(self , ["""torch""", """scipy"""] ) @classmethod def __A ( cls , *A__ , **A__ ): requires_backends(cls , ["""torch""", """scipy"""] ) @classmethod def __A ( cls , *A__ , **A__ ): requires_backends(cls , ["""torch""", """scipy"""] )
714
from functools import lru_cache @lru_cache def UpperCamelCase (lowercase_: int ) -> int: 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()
64
0
import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand if not is_tf_available() and not is_torch_available(): raise RuntimeError('At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training') # TF training parameters A_ : str = False A_ : Optional[Any] = False def UpperCamelCase (lowercase_: Namespace ) -> List[str]: return TrainCommand(_UpperCamelCase ) class _a (__magic_name__ ): '''simple docstring''' @staticmethod def __A ( A__ ): A__ : List[str] = parser.add_parser("""train""" , help="""CLI tool to train a model on a task.""" ) train_parser.add_argument( """--train_data""" , type=A__ , required=A__ , help="""path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences.""" , ) train_parser.add_argument( """--column_label""" , type=A__ , default=0 , help="""Column of the dataset csv file with example labels.""" ) train_parser.add_argument( """--column_text""" , type=A__ , default=1 , help="""Column of the dataset csv file with example texts.""" ) train_parser.add_argument( """--column_id""" , type=A__ , default=2 , help="""Column of the dataset csv file with example ids.""" ) train_parser.add_argument( """--skip_first_row""" , action="""store_true""" , help="""Skip the first row of the csv file (headers).""" ) train_parser.add_argument("""--validation_data""" , type=A__ , default="""""" , help="""path to validation dataset.""" ) train_parser.add_argument( """--validation_split""" , type=A__ , default=0.1 , help="""if validation dataset is not provided, fraction of train dataset to use as validation dataset.""" , ) train_parser.add_argument("""--output""" , type=A__ , default="""./""" , help="""path to saved the trained model.""" ) train_parser.add_argument( """--task""" , type=A__ , default="""text_classification""" , help="""Task to train the model on.""" ) train_parser.add_argument( """--model""" , type=A__ , default="""bert-base-uncased""" , help="""Model\'s name or path to stored model.""" ) train_parser.add_argument("""--train_batch_size""" , type=A__ , default=32 , help="""Batch size for training.""" ) train_parser.add_argument("""--valid_batch_size""" , type=A__ , default=64 , help="""Batch size for validation.""" ) train_parser.add_argument("""--learning_rate""" , type=A__ , default=3e-5 , help="""Learning rate.""" ) train_parser.add_argument("""--adam_epsilon""" , type=A__ , default=1e-08 , help="""Epsilon for Adam optimizer.""" ) train_parser.set_defaults(func=A__ ) def __init__( self , A__ ): A__ : str = logging.get_logger("""transformers-cli/training""" ) A__ : str = """tf""" if is_tf_available() else """torch""" os.makedirs(args.output , exist_ok=A__ ) A__ : Union[str, Any] = args.output A__ : Union[str, Any] = args.column_label A__ : str = args.column_text A__ : List[Any] = args.column_id self.logger.info(F"""Loading {args.task} pipeline for {args.model}""" ) if args.task == "text_classification": A__ : Tuple = TextClassificationPipeline.from_pretrained(args.model ) elif args.task == "token_classification": raise NotImplementedError elif args.task == "question_answering": raise NotImplementedError self.logger.info(F"""Loading dataset from {args.train_data}""" ) A__ : int = Processor.create_from_csv( args.train_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) A__ : Optional[Any] = None if args.validation_data: self.logger.info(F"""Loading validation dataset from {args.validation_data}""" ) A__ : int = Processor.create_from_csv( args.validation_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) A__ : Optional[int] = args.validation_split A__ : Optional[int] = args.train_batch_size A__ : Optional[Any] = args.valid_batch_size A__ : Tuple = args.learning_rate A__ : Tuple = args.adam_epsilon def __A ( self ): if self.framework == "tf": return self.run_tf() return self.run_torch() def __A ( self ): raise NotImplementedError def __A ( self ): self.pipeline.fit( self.train_dataset , validation_data=self.valid_dataset , validation_split=self.validation_split , learning_rate=self.learning_rate , adam_epsilon=self.adam_epsilon , train_batch_size=self.train_batch_size , valid_batch_size=self.valid_batch_size , ) # Save trained pipeline self.pipeline.save_pretrained(self.output )
715
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import datasets import datasets.config from .utils import require_beam class _a (datasets.BeamBasedBuilder ): '''simple docstring''' def __A ( self ): return datasets.DatasetInfo( features=datasets.Features({"""content""": datasets.Value("""string""" )} ) , supervised_keys=A__ , ) def __A ( self , A__ , A__ ): return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""examples""": get_test_dummy_examples()} )] def __A ( self , A__ , A__ ): import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(A__ ) class _a (datasets.BeamBasedBuilder ): '''simple docstring''' def __A ( self ): return datasets.DatasetInfo( features=datasets.Features({"""a""": datasets.Sequence({"""b""": datasets.Value("""string""" )} )} ) , supervised_keys=A__ , ) def __A ( self , A__ , A__ ): return [ datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""examples""": get_test_nested_examples()} ) ] def __A ( self , A__ , A__ ): import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(A__ ) def UpperCamelCase () -> Dict: return [(i, {"content": content}) for i, content in enumerate(["""foo""", """bar""", """foobar"""] )] def UpperCamelCase () -> Tuple: return [(i, {"a": {"b": [content]}}) for i, content in enumerate(["""foo""", """bar""", """foobar"""] )] class _a (__magic_name__ ): '''simple docstring''' @require_beam def __A ( self ): A__ : Dict = len(get_test_dummy_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: A__ : int = DummyBeamDataset(cache_dir=A__ , beam_runner="""DirectRunner""" ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(A__ , builder.name , """default""" , """0.0.0""" , F"""{builder.name}-train.arrow""" ) ) ) self.assertDictEqual(builder.info.features , datasets.Features({"""content""": datasets.Value("""string""" )} ) ) A__ : int = builder.as_dataset() self.assertEqual(dset["""train"""].num_rows , A__ ) self.assertEqual(dset["""train"""].info.splits["""train"""].num_examples , A__ ) self.assertDictEqual(dset["""train"""][0] , get_test_dummy_examples()[0][1] ) self.assertDictEqual( dset["""train"""][expected_num_examples - 1] , get_test_dummy_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(A__ , builder.name , """default""" , """0.0.0""" , """dataset_info.json""" ) ) ) del dset @require_beam def __A ( self ): import apache_beam as beam A__ : int = beam.io.parquetio.WriteToParquet A__ : List[str] = len(get_test_dummy_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: A__ : str = DummyBeamDataset(cache_dir=A__ , beam_runner="""DirectRunner""" ) with patch("""apache_beam.io.parquetio.WriteToParquet""" ) as write_parquet_mock: A__ : Optional[Any] = partial(A__ , num_shards=2 ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join( A__ , builder.name , """default""" , """0.0.0""" , F"""{builder.name}-train-00000-of-00002.arrow""" ) ) ) self.assertTrue( os.path.exists( os.path.join( A__ , builder.name , """default""" , """0.0.0""" , F"""{builder.name}-train-00000-of-00002.arrow""" ) ) ) self.assertDictEqual(builder.info.features , datasets.Features({"""content""": datasets.Value("""string""" )} ) ) A__ : Optional[int] = builder.as_dataset() self.assertEqual(dset["""train"""].num_rows , A__ ) self.assertEqual(dset["""train"""].info.splits["""train"""].num_examples , A__ ) # Order is not preserved when sharding, so we just check that all the elements are there self.assertListEqual(sorted(dset["""train"""]["""content"""] ) , sorted(["""foo""", """bar""", """foobar"""] ) ) self.assertTrue( os.path.exists(os.path.join(A__ , builder.name , """default""" , """0.0.0""" , """dataset_info.json""" ) ) ) del dset @require_beam def __A ( self ): with tempfile.TemporaryDirectory() as tmp_cache_dir: A__ : int = DummyBeamDataset(cache_dir=A__ ) self.assertRaises(datasets.builder.MissingBeamOptions , builder.download_and_prepare ) @require_beam def __A ( self ): A__ : List[Any] = len(get_test_nested_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: A__ : Optional[int] = NestedBeamDataset(cache_dir=A__ , beam_runner="""DirectRunner""" ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(A__ , builder.name , """default""" , """0.0.0""" , F"""{builder.name}-train.arrow""" ) ) ) self.assertDictEqual( builder.info.features , datasets.Features({"""a""": datasets.Sequence({"""b""": datasets.Value("""string""" )} )} ) ) A__ : Optional[int] = builder.as_dataset() self.assertEqual(dset["""train"""].num_rows , A__ ) self.assertEqual(dset["""train"""].info.splits["""train"""].num_examples , A__ ) self.assertDictEqual(dset["""train"""][0] , get_test_nested_examples()[0][1] ) self.assertDictEqual( dset["""train"""][expected_num_examples - 1] , get_test_nested_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(A__ , builder.name , """default""" , """0.0.0""" , """dataset_info.json""" ) ) ) del dset
64
0
import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def UpperCamelCase (lowercase_: int ) -> str: return (data["data"], data["target"]) def UpperCamelCase (lowercase_: Union[str, Any] , lowercase_: Optional[int] , lowercase_: Any ) -> Dict: A__ : Tuple = XGBRegressor(verbosity=0 , random_state=42 ) xgb.fit(lowercase_ , lowercase_ ) # Predict target for test data A__ : Optional[Any] = xgb.predict(lowercase_ ) A__ : Optional[Any] = predictions.reshape(len(lowercase_ ) , 1 ) return predictions def UpperCamelCase () -> Dict: A__ : str = fetch_california_housing() A__ , A__ : Union[str, Any] = data_handling(lowercase_ ) A__ , A__ , A__ , A__ : Tuple = train_test_split( lowercase_ , lowercase_ , test_size=0.25 , random_state=1 ) A__ : Union[str, Any] = xgboost(lowercase_ , lowercase_ , lowercase_ ) # Error printing print(f"""Mean Absolute Error : {mean_absolute_error(lowercase_ , lowercase_ )}""" ) print(f"""Mean Square Error : {mean_squared_error(lowercase_ , lowercase_ )}""" ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
716
import warnings from ...utils import logging from .image_processing_poolformer import PoolFormerImageProcessor A_ : Union[str, Any] = logging.get_logger(__name__) class _a (__magic_name__ ): '''simple docstring''' def __init__( self , *A__ , **A__ ): warnings.warn( """The class PoolFormerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use PoolFormerImageProcessor instead.""" , A__ , ) super().__init__(*A__ , **A__ )
64
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A_ : Any = logging.get_logger(__name__) A_ : Any = { "andreasmadsen/efficient_mlm_m0.40": ( "https://huggingface.co/andreasmadsen/efficient_mlm_m0.40/resolve/main/config.json" ), } class _a (__lowerCAmelCase ): '''simple docstring''' UpperCAmelCase__: List[Any] = "roberta-prelayernorm" def __init__( self , A__=5_0265 , A__=768 , A__=12 , A__=12 , A__=3072 , A__="gelu" , A__=0.1 , A__=0.1 , A__=512 , A__=2 , A__=0.0_2 , A__=1e-12 , A__=1 , A__=0 , A__=2 , A__="absolute" , A__=True , A__=None , **A__ , ): super().__init__(pad_token_id=lowerCamelCase__ , bos_token_id=lowerCamelCase__ , eos_token_id=lowerCamelCase__ , **lowerCamelCase__ ) A__ : Optional[int] = vocab_size A__ : Union[str, Any] = hidden_size A__ : List[str] = num_hidden_layers A__ : Optional[int] = num_attention_heads A__ : List[str] = hidden_act A__ : Optional[int] = intermediate_size A__ : Optional[int] = hidden_dropout_prob A__ : List[str] = attention_probs_dropout_prob A__ : Optional[int] = max_position_embeddings A__ : Optional[Any] = type_vocab_size A__ : Union[str, Any] = initializer_range A__ : Dict = layer_norm_eps A__ : Union[str, Any] = position_embedding_type A__ : Optional[int] = use_cache A__ : int = classifier_dropout class _a (__lowerCAmelCase ): '''simple docstring''' @property def __A ( self ): if self.task == "multiple-choice": A__ : Dict = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: A__ : Any = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
717
import inspect import logging import os import random import shutil import tempfile import unittest import pytest import torch from torch import nn from torch.utils.data import DataLoader, TensorDataset from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_cuda from accelerate.utils import ProjectConfiguration, set_seed A_ : Any = logging.getLogger(__name__) def UpperCamelCase (lowercase_: Optional[Any]=2 , lowercase_: Union[str, Any]=3 , lowercase_: int=16 , lowercase_: int = 10 , lowercase_: int = 2 ) -> int: def get_dataset(lowercase_: Optional[int] ): A__ : Optional[Any] = torch.randn(batch_size * n_batches , 1 ) return TensorDataset(lowercase_ , a * x + b + 0.1 * torch.randn(batch_size * n_batches , 1 ) ) A__ : Dict = get_dataset(lowercase_ ) A__ : Any = get_dataset(lowercase_ ) A__ : Dict = DataLoader(lowercase_ , shuffle=lowercase_ , batch_size=lowercase_ , num_workers=4 ) A__ : Optional[Any] = DataLoader(lowercase_ , shuffle=lowercase_ , batch_size=lowercase_ , num_workers=4 ) return (train_dataloader, valid_dataloader) def UpperCamelCase (lowercase_: Optional[Any] , lowercase_: List[str] , lowercase_: int , lowercase_: int , lowercase_: List[str] , lowercase_: Dict=None ) -> List[Any]: A__ : List[Any] = [] for epoch in range(lowercase_ ): # Train quickly model.train() for batch in dataloader: A__ , A__ : Any = batch A__ : Any = model(lowercase_ ) A__ : Any = torch.nn.functional.mse_loss(lowercase_ , lowercase_ ) accelerator.backward(lowercase_ ) optimizer.step() optimizer.zero_grad() rands.append(random.random() ) # Introduce some randomness if scheduler is not None: scheduler.step() return rands class _a (nn.Module ): '''simple docstring''' def __init__( self ): super().__init__() A__ : str = nn.Parameter(torch.randn(1 ) ) A__ : Any = nn.Parameter(torch.randn(1 ) ) def __A ( self , A__ ): return x * self.a + self.b class _a (unittest.TestCase ): '''simple docstring''' def __A ( self ): with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) A__ : Optional[Any] = DummyModel() A__ : Optional[Any] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) A__ , A__ : str = dummy_dataloaders() A__ : Dict = ProjectConfiguration(total_limit=1 , project_dir=A__ , automatic_checkpoint_naming=A__ ) # Train baseline A__ : List[str] = Accelerator(project_config=A__ ) A__ , A__ , A__ , A__ : Any = accelerator.prepare( A__ , A__ , A__ , A__ ) # Save initial accelerator.save_state() # Save second state accelerator.save_state() self.assertEqual(len(os.listdir(accelerator.project_dir ) ) , 1 ) def __A ( self ): with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) A__ : str = DummyModel() A__ : Optional[int] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) A__ , A__ : int = dummy_dataloaders() # Train baseline A__ : str = Accelerator() A__ , A__ , A__ , A__ : List[str] = accelerator.prepare( A__ , A__ , A__ , A__ ) # Save initial A__ : List[Any] = os.path.join(A__ , """initial""" ) accelerator.save_state(A__ ) ((A__) , (A__)) : str = model.a.item(), model.b.item() A__ : Dict = optimizer.state_dict() A__ : List[str] = train(3 , A__ , A__ , A__ , A__ ) ((A__) , (A__)) : str = model.a.item(), model.b.item() A__ : Any = optimizer.state_dict() # Train partially set_seed(42 ) A__ : Optional[int] = DummyModel() A__ : Dict = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) A__ , A__ : Dict = dummy_dataloaders() A__ : List[str] = Accelerator() A__ , A__ , A__ , A__ : Optional[Any] = accelerator.prepare( A__ , A__ , A__ , A__ ) accelerator.load_state(A__ ) ((A__) , (A__)) : Tuple = model.a.item(), model.b.item() A__ : Union[str, Any] = optimizer.state_dict() self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) A__ : List[str] = train(2 , A__ , A__ , A__ , A__ ) # Save everything A__ : Optional[int] = os.path.join(A__ , """checkpoint""" ) accelerator.save_state(A__ ) # Load everything back in and make sure all states work accelerator.load_state(A__ ) test_rands += train(1 , A__ , A__ , A__ , A__ ) ((A__) , (A__)) : Union[str, Any] = model.a.item(), model.b.item() A__ : Optional[int] = optimizer.state_dict() self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) def __A ( self ): with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) A__ : int = DummyModel() A__ : Optional[int] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) A__ , A__ : List[str] = dummy_dataloaders() A__ : str = ProjectConfiguration(automatic_checkpoint_naming=A__ ) # Train baseline A__ : Any = Accelerator(project_dir=A__ , project_config=A__ ) A__ , A__ , A__ , A__ : str = accelerator.prepare( A__ , A__ , A__ , A__ ) # Save initial accelerator.save_state() ((A__) , (A__)) : Tuple = model.a.item(), model.b.item() A__ : int = optimizer.state_dict() A__ : int = train(3 , A__ , A__ , A__ , A__ ) ((A__) , (A__)) : Optional[Any] = model.a.item(), model.b.item() A__ : Any = optimizer.state_dict() # Train partially set_seed(42 ) A__ : Dict = DummyModel() A__ : List[Any] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) A__ , A__ : Union[str, Any] = dummy_dataloaders() A__ : List[Any] = ProjectConfiguration(iteration=1 , automatic_checkpoint_naming=A__ ) A__ : Dict = Accelerator(project_dir=A__ , project_config=A__ ) A__ , A__ , A__ , A__ : Union[str, Any] = accelerator.prepare( A__ , A__ , A__ , A__ ) accelerator.load_state(os.path.join(A__ , """checkpoints""" , """checkpoint_0""" ) ) ((A__) , (A__)) : Optional[int] = model.a.item(), model.b.item() A__ : Tuple = optimizer.state_dict() self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) A__ : str = train(2 , A__ , A__ , A__ , A__ ) # Save everything accelerator.save_state() # Load everything back in and make sure all states work accelerator.load_state(os.path.join(A__ , """checkpoints""" , """checkpoint_1""" ) ) test_rands += train(1 , A__ , A__ , A__ , A__ ) ((A__) , (A__)) : Optional[int] = model.a.item(), model.b.item() A__ : List[Any] = optimizer.state_dict() self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) self.assertEqual(A__ , A__ ) def __A ( self ): A__ : Union[str, Any] = torch.tensor([1, 2, 3] ) A__ : int = torch.tensor([2, 3, 4] ) A__ : List[Any] = DummyModel() A__ : List[Any] = torch.optim.Adam(net.parameters() ) A__ : Tuple = Accelerator() with self.assertRaises(A__ ) as ve: accelerator.register_for_checkpointing(A__ , A__ , A__ , A__ ) A__ : Any = str(ve.exception ) self.assertTrue("""Item at index 0""" in message ) self.assertTrue("""Item at index 1""" in message ) self.assertFalse("""Item at index 2""" in message ) self.assertFalse("""Item at index 3""" in message ) def __A ( self ): with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) A__ : Any = DummyModel() A__ : Union[str, Any] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) A__ : Dict = torch.optim.lr_scheduler.StepLR(A__ , step_size=1 , gamma=0.9_9 ) A__ , A__ : List[Any] = dummy_dataloaders() A__ : Tuple = ProjectConfiguration(automatic_checkpoint_naming=A__ ) # Train baseline A__ : Optional[Any] = Accelerator(project_dir=A__ , project_config=A__ ) A__ , A__ , A__ , A__ , A__ : Union[str, Any] = accelerator.prepare( A__ , A__ , A__ , A__ , A__ ) # Save initial accelerator.save_state() A__ : Tuple = scheduler.state_dict() train(3 , A__ , A__ , A__ , A__ , A__ ) self.assertNotEqual(A__ , scheduler.state_dict() ) # Load everything back in and make sure all states work accelerator.load_state(os.path.join(A__ , """checkpoints""" , """checkpoint_0""" ) ) self.assertEqual(A__ , scheduler.state_dict() ) def __A ( self ): with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) A__ : Optional[Any] = DummyModel() A__ : int = ProjectConfiguration(automatic_checkpoint_naming=A__ , total_limit=2 ) # Train baseline A__ : List[str] = Accelerator(project_dir=A__ , project_config=A__ ) A__ : Union[str, Any] = accelerator.prepare(A__ ) # Save 3 states: for _ in range(11 ): accelerator.save_state() self.assertTrue(not os.path.exists(os.path.join(A__ , """checkpoints""" , """checkpoint_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(A__ , """checkpoints""" , """checkpoint_9""" ) ) ) self.assertTrue(os.path.exists(os.path.join(A__ , """checkpoints""" , """checkpoint_10""" ) ) ) @require_cuda def __A ( self ): A__ : Dict = ["""torchrun""", F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__ )] execute_subprocess_async(A__ , env=os.environ.copy() ) if __name__ == "__main__": A_ : List[str] = '/tmp/accelerate/state_checkpointing' A_ : Optional[Any] = DummyModel() A_ : Union[str, Any] = torch.optim.Adam(params=model.parameters(), lr=1E-3) A_ : str = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99) A_ , A_ : List[Any] = dummy_dataloaders() A_ : int = ProjectConfiguration(automatic_checkpoint_naming=True) # Train baseline A_ : List[str] = Accelerator(project_dir=savedir, project_config=project_config, mixed_precision='no') if accelerator.process_index == 0: if os.path.exists(savedir): shutil.rmtree(savedir) os.makedirs(savedir) A_ , A_ , A_ , A_ , A_ : List[Any] = accelerator.prepare( model, optimizer, train_dataloader, valid_dataloader, scheduler ) A_ , A_ : Dict = accelerator.prepare(model, optimizer) train(3, model, train_dataloader, optimizer, accelerator, scheduler) # Check that the intial optimizer is loaded on the GPU for group in optimizer.param_groups: A_ : str = group['params'][0].device break assert param_device.type == accelerator.device.type A_ : Optional[Any] = model.cpu() accelerator.wait_for_everyone() accelerator.save_state() accelerator.wait_for_everyone() # Check CPU state accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='cpu') for group in optimizer.param_groups: A_ : str = group['params'][0].device break assert ( param_device.type == torch.device('cpu').type ), f"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}" # Check device state model.to(accelerator.device) accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='on_device') for group in optimizer.param_groups: A_ : Tuple = group['params'][0].device break assert ( param_device.type == accelerator.device.type ), f"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}" # Check error with pytest.raises(TypeError, match='Unsupported optimizer map location passed'): accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='invalid') accelerator.wait_for_everyone() if accelerator.process_index == 0: shutil.rmtree(savedir) accelerator.wait_for_everyone()
64
0
import logging import os import sys from dataclasses import dataclass, field from typing import Optional import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor from torchvision.transforms.functional import InterpolationMode import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, ViTImageProcessor, ViTMAEConfig, ViTMAEForPreTraining, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version A_ : int = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('4.31.0') require_version('datasets>=1.8.0', 'To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt') @dataclass class _a : '''simple docstring''' UpperCAmelCase__: Tuple = field( default='''cifar10''' , metadata={'''help''': '''Name of a dataset from the datasets package'''} ) UpperCAmelCase__: Union[str, Any] = field( default=UpperCamelCase_ , metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) UpperCAmelCase__: Any = field( default=UpperCamelCase_ , metadata={'''help''': '''The column name of the images in the files.'''} ) UpperCAmelCase__: List[Any] = field(default=UpperCamelCase_ , metadata={'''help''': '''A folder containing the training data.'''} ) UpperCAmelCase__: int = field(default=UpperCamelCase_ , metadata={'''help''': '''A folder containing the validation data.'''} ) UpperCAmelCase__: Optional[Any] = field( default=0.15 , metadata={'''help''': '''Percent to split off of train for validation.'''} ) UpperCAmelCase__: int = field( default=UpperCamelCase_ , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } , ) UpperCAmelCase__: Dict = field( default=UpperCamelCase_ , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } , ) def __A ( self ): A__ : Optional[Any] = {} if self.train_dir is not None: A__ : List[str] = self.train_dir if self.validation_dir is not None: A__ : str = self.validation_dir A__ : Union[str, Any] = data_files if data_files else None @dataclass class _a : '''simple docstring''' UpperCAmelCase__: List[Any] = field( default=UpperCamelCase_ , metadata={ '''help''': ( '''The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.''' ) } , ) UpperCAmelCase__: List[str] = field( default=UpperCamelCase_ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name_or_path'''} ) UpperCAmelCase__: Union[str, Any] = field( default=UpperCamelCase_ , metadata={ '''help''': ( '''Override some existing default config settings when a model is trained from scratch. Example: ''' '''n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index''' ) } , ) UpperCAmelCase__: Dict = field( default=UpperCamelCase_ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from s3'''} ) UpperCAmelCase__: Optional[Any] = field( default='''main''' , metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} , ) UpperCAmelCase__: Tuple = field(default=UpperCamelCase_ , metadata={'''help''': '''Name or path of preprocessor config.'''} ) UpperCAmelCase__: str = field( default=UpperCamelCase_ , metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } , ) UpperCAmelCase__: Dict = field( default=0.75 , metadata={'''help''': '''The ratio of the number of masked tokens in the input sequence.'''} ) UpperCAmelCase__: List[Any] = field( default=UpperCamelCase_ , metadata={'''help''': '''Whether or not to train with normalized pixel values as target.'''} ) @dataclass class _a (UpperCamelCase_ ): '''simple docstring''' UpperCAmelCase__: Optional[int] = field( default=1E-3 , metadata={'''help''': '''Base learning rate: absolute_lr = base_lr * total_batch_size / 256.'''} ) def UpperCamelCase (lowercase_: int ) -> Any: A__ : Optional[int] = torch.stack([example["""pixel_values"""] for example in examples] ) return {"pixel_values": pixel_values} def UpperCamelCase () -> Dict: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. A__ : List[Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(""".json""" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. A__ : Optional[int] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: A__ : Dict = 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_mae""" , snake_case_ , snake_case_ ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() A__ : Optional[Any] = training_args.get_process_log_level() logger.setLevel(snake_case_ ) transformers.utils.logging.set_verbosity(snake_case_ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + f"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(f"""Training/evaluation parameters {training_args}""" ) # Detecting last checkpoint. A__ : List[str] = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: A__ : Tuple = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. """ """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Initialize our dataset. A__ : str = load_dataset( data_args.dataset_name , data_args.dataset_config_name , data_files=data_args.data_files , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # If we don't have a validation split, split off a percentage of train as validation. A__ : Any = None if '''validation''' in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , snake_case_ ) and data_args.train_val_split > 0.0: A__ : List[Any] = ds['''train'''].train_test_split(data_args.train_val_split ) A__ : int = split['''train'''] A__ : Optional[int] = split['''test'''] # Load pretrained model and image processor # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. A__ : Optional[int] = { '''cache_dir''': model_args.cache_dir, '''revision''': model_args.model_revision, '''use_auth_token''': True if model_args.use_auth_token else None, } if model_args.config_name: A__ : Dict = ViTMAEConfig.from_pretrained(model_args.config_name , **snake_case_ ) elif model_args.model_name_or_path: A__ : Any = ViTMAEConfig.from_pretrained(model_args.model_name_or_path , **snake_case_ ) else: A__ : Any = ViTMAEConfig() logger.warning("""You are instantiating a new config instance from scratch.""" ) if model_args.config_overrides is not None: logger.info(f"""Overriding config: {model_args.config_overrides}""" ) config.update_from_string(model_args.config_overrides ) logger.info(f"""New config: {config}""" ) # adapt config config.update( { """mask_ratio""": model_args.mask_ratio, """norm_pix_loss""": model_args.norm_pix_loss, } ) # create image processor if model_args.image_processor_name: A__ : List[str] = ViTImageProcessor.from_pretrained(model_args.image_processor_name , **snake_case_ ) elif model_args.model_name_or_path: A__ : Optional[Any] = ViTImageProcessor.from_pretrained(model_args.model_name_or_path , **snake_case_ ) else: A__ : Any = ViTImageProcessor() # create model if model_args.model_name_or_path: A__ : int = ViTMAEForPreTraining.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=snake_case_ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info("""Training new model from scratch""" ) A__ : Union[str, Any] = ViTMAEForPreTraining(snake_case_ ) if training_args.do_train: A__ : int = ds['''train'''].column_names else: A__ : Optional[Any] = ds['''validation'''].column_names if data_args.image_column_name is not None: A__ : Optional[int] = data_args.image_column_name elif "image" in column_names: A__ : List[Any] = '''image''' elif "img" in column_names: A__ : Dict = '''img''' else: A__ : List[str] = column_names[0] # transformations as done in original MAE paper # source: https://github.com/facebookresearch/mae/blob/main/main_pretrain.py if "shortest_edge" in image_processor.size: A__ : Optional[int] = image_processor.size['''shortest_edge'''] else: A__ : Union[str, Any] = (image_processor.size['''height'''], image_processor.size['''width''']) A__ : Union[str, Any] = Compose( [ Lambda(lambda lowercase_ : img.convert("""RGB""" ) if img.mode != "RGB" else img ), RandomResizedCrop(snake_case_ , scale=(0.2, 1.0) , interpolation=InterpolationMode.BICUBIC ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) def preprocess_images(lowercase_: List[Any] ): A__ : Any = [transforms(snake_case_ ) for image in examples[image_column_name]] return examples if training_args.do_train: if "train" not in ds: raise ValueError("""--do_train requires a train dataset""" ) if data_args.max_train_samples is not None: A__ : Any = ds['''train'''].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(snake_case_ ) if training_args.do_eval: if "validation" not in ds: raise ValueError("""--do_eval requires a validation dataset""" ) if data_args.max_eval_samples is not None: A__ : Union[str, Any] = ( ds['''validation'''].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(snake_case_ ) # Compute absolute learning rate A__ : Dict = ( training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size ) if training_args.base_learning_rate is not None: A__ : int = training_args.base_learning_rate * total_train_batch_size / 256 # Initialize our trainer A__ : Dict = Trainer( model=snake_case_ , args=snake_case_ , train_dataset=ds["""train"""] if training_args.do_train else None , eval_dataset=ds["""validation"""] if training_args.do_eval else None , tokenizer=snake_case_ , data_collator=snake_case_ , ) # Training if training_args.do_train: A__ : Optional[Any] = None if training_args.resume_from_checkpoint is not None: A__ : List[str] = training_args.resume_from_checkpoint elif last_checkpoint is not None: A__ : List[str] = last_checkpoint A__ : Any = trainer.train(resume_from_checkpoint=snake_case_ ) trainer.save_model() trainer.log_metrics("""train""" , train_result.metrics ) trainer.save_metrics("""train""" , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: A__ : Dict = trainer.evaluate() trainer.log_metrics("""eval""" , snake_case_ ) trainer.save_metrics("""eval""" , snake_case_ ) # Write model card and (optionally) push to hub A__ : int = { '''tasks''': '''masked-auto-encoding''', '''dataset''': data_args.dataset_name, '''tags''': ['''masked-auto-encoding'''], } if training_args.push_to_hub: trainer.push_to_hub(**snake_case_ ) else: trainer.create_model_card(**snake_case_ ) def UpperCamelCase (lowercase_: Tuple ) -> Dict: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
718
def UpperCamelCase (lowercase_: str , lowercase_: str ) -> bool: A__ : Union[str, Any] = len(lowercase_ ) A__ : List[Any] = len(lowercase_ ) A__ : List[Any] = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] A__ : str = True for i in range(lowercase_ ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: A__ : int = True if a[i].islower(): A__ : Dict = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
64
0
import argparse import os import torch from transformers.utils import WEIGHTS_NAME A_ : Union[str, Any] = ["""small""", """medium""", """large"""] A_ : List[Any] = """lm_head.decoder.weight""" A_ : Union[str, Any] = """lm_head.weight""" def UpperCamelCase (lowercase_: int , lowercase_: Tuple ) -> Union[str, Any]: A__ : str = torch.load(UpperCamelCase__ ) A__ : int = d.pop(UpperCamelCase__ ) os.makedirs(UpperCamelCase__ , exist_ok=UpperCamelCase__ ) torch.save(UpperCamelCase__ , os.path.join(UpperCamelCase__ , UpperCamelCase__ ) ) if __name__ == "__main__": A_ : Tuple = argparse.ArgumentParser() parser.add_argument('--dialogpt_path', default='.', type=str) A_ : Dict = parser.parse_args() for MODEL in DIALOGPT_MODELS: A_ : Optional[Any] = os.path.join(args.dialogpt_path, f'''{MODEL}_ft.pkl''') A_ : Dict = f'''./DialoGPT-{MODEL}''' convert_dialogpt_checkpoint( checkpoint_path, pytorch_dump_folder_path, )
719
import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin A_ : Dict = random.Random() if is_torch_available(): import torch def UpperCamelCase (lowercase_: Tuple , lowercase_: Tuple=1.0 , lowercase_: Dict=None , lowercase_: int=None ) -> str: if rng is None: A__ : Optional[Any] = global_rng A__ : List[str] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class _a (unittest.TestCase ): '''simple docstring''' def __init__( self , A__ , A__=7 , A__=400 , A__=2000 , A__=1 , A__=0.0 , A__=1_6000 , A__=True , A__=True , ): A__ : Any = parent A__ : Optional[int] = batch_size A__ : Union[str, Any] = min_seq_length A__ : Dict = max_seq_length A__ : Tuple = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) A__ : str = feature_size A__ : Optional[int] = padding_value A__ : List[str] = sampling_rate A__ : List[str] = return_attention_mask A__ : int = do_normalize def __A ( self ): return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def __A ( self , A__=False , A__=False ): def _flatten(A__ ): return list(itertools.chain(*A__ ) ) if equal_length: A__ : Dict = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size A__ : Union[str, Any] = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: A__ : Optional[int] = [np.asarray(A__ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class _a (__magic_name__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: int = ASTFeatureExtractor def __A ( self ): A__ : Optional[Any] = ASTFeatureExtractionTester(self ) def __A ( self ): # Tests that all call wrap to encode_plus and batch_encode_plus A__ : Optional[int] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 A__ : List[Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] A__ : Optional[Any] = [np.asarray(A__ ) for speech_input in speech_inputs] # Test not batched input A__ : Tuple = feat_extract(speech_inputs[0] , return_tensors="""np""" ).input_values A__ : Tuple = feat_extract(np_speech_inputs[0] , return_tensors="""np""" ).input_values self.assertTrue(np.allclose(A__ , A__ , atol=1e-3 ) ) # Test batched A__ : Tuple = feat_extract(A__ , padding=A__ , return_tensors="""np""" ).input_values A__ : Tuple = feat_extract(A__ , padding=A__ , return_tensors="""np""" ).input_values for enc_seq_a, enc_seq_a in zip(A__ , A__ ): self.assertTrue(np.allclose(A__ , A__ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. A__ : int = [floats_list((1, x) )[0] for x in (800, 800, 800)] A__ : List[str] = np.asarray(A__ ) A__ : Union[str, Any] = feat_extract(A__ , return_tensors="""np""" ).input_values A__ : Optional[Any] = feat_extract(A__ , return_tensors="""np""" ).input_values for enc_seq_a, enc_seq_a in zip(A__ , A__ ): self.assertTrue(np.allclose(A__ , A__ , atol=1e-3 ) ) @require_torch def __A ( self ): import torch A__ : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) A__ : Tuple = np.random.rand(100 ).astype(np.floataa ) A__ : Tuple = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: A__ : List[str] = feature_extractor.pad([{"""input_values""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) A__ : Any = feature_extractor.pad([{"""input_values""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def __A ( self , A__ ): from datasets import load_dataset A__ : str = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech A__ : str = ds.sort("""id""" ).select(range(A__ ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] @require_torch def __A ( self ): # fmt: off A__ : Optional[Any] = torch.tensor( [-0.9_8_9_4, -1.2_7_7_6, -0.9_0_6_6, -1.2_7_7_6, -0.9_3_4_9, -1.2_6_0_9, -1.0_3_8_6, -1.2_7_7_6, -1.1_5_6_1, -1.2_7_7_6, -1.2_0_5_2, -1.2_7_2_3, -1.2_1_9_0, -1.2_1_3_2, -1.2_7_7_6, -1.1_1_3_3, -1.1_9_5_3, -1.1_3_4_3, -1.1_5_8_4, -1.2_2_0_3, -1.1_7_7_0, -1.2_4_7_4, -1.2_3_8_1, -1.1_9_3_6, -0.9_2_7_0, -0.8_3_1_7, -0.8_0_4_9, -0.7_7_0_6, -0.7_5_6_5, -0.7_8_6_9] ) # fmt: on A__ : Any = self._load_datasamples(1 ) A__ : Tuple = ASTFeatureExtractor() A__ : Dict = feature_extractor(A__ , return_tensors="""pt""" ).input_values self.assertEquals(input_values.shape , (1, 1024, 128) ) self.assertTrue(torch.allclose(input_values[0, 0, :30] , A__ , atol=1e-4 ) )
64
0
import collections import json import os import re from typing import TYPE_CHECKING, List, Optional, Tuple import numpy as np from ...tokenization_utils_fast import PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation A_ : Any = logging.get_logger(__name__) A_ : Tuple = {'vocab_file': 'vocab.txt', 'emoji_file': 'emoji.json'} A_ : List[str] = { 'vocab_file': { 'abeja/gpt-neox-japanese-2.7b': 'https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/vocab.txt', }, 'emoji_file': { 'abeja/gpt-neox-japanese-2.7b': 'https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/emoji.json', }, } A_ : Optional[Any] = { 'abeja/gpt-neox-japanese-2.7b': 2048, } def UpperCamelCase (lowercase_: Tuple , lowercase_: Union[str, Any] ) -> str: with open(lowerCamelCase__ , """r""" , encoding="""utf-8""" ) as f: A__ : Tuple = json.loads(f.read() ) A__ : Dict = collections.OrderedDict() A__ : List[str] = collections.OrderedDict() A__ : Union[str, Any] = collections.OrderedDict() with open(lowerCamelCase__ , """r""" , encoding="""utf-8""" ) as f: A__ : Union[str, Any] = f.readlines() A__ : Union[str, Any] = [[t.rstrip("""\n""" )] if (t == """,""" or """,""" not in t) else t.rstrip("""\n""" ).split(""",""" ) for t in token] for idx, b in enumerate(lowerCamelCase__ ): A__ : int = b A__ : Any = idx for wd in b: A__ : Tuple = idx return vocab, raw_vocab, ids_to_tokens, emoji class _a (__magic_name__ ): '''simple docstring''' UpperCAmelCase__: Optional[int] = VOCAB_FILES_NAMES UpperCAmelCase__: Any = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__: Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__: str = ["""input_ids""", """attention_mask"""] def __init__( self , A__ , A__ , A__="<|endoftext|>" , A__="<|endoftext|>" , A__="<|startoftext|>" , A__="<|endoftext|>" , A__=False , **A__ , ): super().__init__( unk_token=A__ , pad_token=A__ , bos_token=A__ , eos_token=A__ , do_clean_text=A__ , **A__ , ) if not os.path.isfile(A__ ): raise ValueError( F"""Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained""" """ model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`""" ) if not os.path.isfile(A__ ): raise ValueError( F"""Can't find a emoji file at path '{emoji_file}'. To load the emoji information from a Google""" """ pretrained model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`""" ) A__ : int = do_clean_text A__ , A__ , A__ , A__ : Union[str, Any] = load_vocab_and_emoji(A__ , A__ ) A__ : Optional[Any] = SubWordJapaneseTokenizer( vocab=self.vocab , ids_to_tokens=self.ids_to_tokens , emoji=self.emoji ) @property def __A ( self ): return len(self.raw_vocab ) def __A ( self ): return dict(self.raw_vocab , **self.added_tokens_encoder ) def __A ( self , A__ ): return self.subword_tokenizer.tokenize(A__ , clean=self.do_clean_text ) def __A ( self , A__ ): return self.vocab.get(A__ , self.vocab.get(self.unk_token ) ) def __A ( self , A__ ): return self.subword_tokenizer.convert_id_to_token(A__ ) def __A ( self , A__ ): A__ : Union[str, Any] = """""".join(A__ ).strip() return out_string def __A ( self , A__ ): A__ : Tuple = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(A__ , add_special_tokens=A__ ) + [self.eos_token_id] ) if len(A__ ) > self.model_max_length: A__ : Union[str, Any] = input_ids[-self.model_max_length :] return input_ids def __A ( self , A__ , A__ = None ): A__ : Union[str, Any] = 0 if os.path.isdir(A__ ): A__ : Union[str, Any] = os.path.join( A__ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) A__ : Tuple = os.path.join( A__ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""emoji_file"""] ) else: A__ : int = ( (filename_prefix + """-""" if filename_prefix else """""") + save_directory + VOCAB_FILES_NAMES["""vocab_file"""] ) A__ : int = ( (filename_prefix + """-""" if filename_prefix else """""") + save_directory + VOCAB_FILES_NAMES["""emoji_file"""] ) with open(A__ , """w""" , encoding="""utf-8""" ) as writer: for token_index, token in self.ids_to_tokens.items(): if index != token_index: logger.warning( F"""Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.""" """ Please check that the vocabulary is not corrupted!""" ) A__ : Dict = token_index writer.write(""",""".join(A__ ) + """\n""" ) index += 1 with open(A__ , """w""" , encoding="""utf-8""" ) as writer: json.dump(self.emoji , A__ ) return vocab_file, emoji_file class _a (__magic_name__ ): '''simple docstring''' def __init__( self , A__ , A__ , A__ ): A__ : str = vocab # same as swe A__ : Tuple = ids_to_tokens # same as bpe A__ : Any = emoji A__ : str = np.max([len(A__ ) for w in self.vocab.keys()] ) A__ : Dict = re.compile(r"""(https?|ftp)(:\/\/[-_\.!~*\'()a-zA-Z0-9;\/?:\@&=\+$,%#]+)""" ) A__ : Any = re.compile(r"""[A-Za-z0-9\._+]*@[\-_0-9A-Za-z]+(\.[A-Za-z]+)*""" ) A__ : Optional[Any] = re.compile(r"""[\(]{0,1}[0-9]{2,4}[\)\-\(]{0,1}[0-9]{2,4}[\)\-]{0,1}[0-9]{3,4}""" ) A__ : Dict = re.compile( r"""([12]\d{3}[/\-年])*(0?[1-9]|1[0-2])[/\-月]((0?[1-9]|[12][0-9]|3[01])日?)*(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*""" ) A__ : Union[str, Any] = re.compile( r"""(明治|大正|昭和|平成|令和|㍾|㍽|㍼|㍻|\u32ff)\d{1,2}年(0?[1-9]|1[0-2])月(0?[1-9]|[12][0-9]|3[01])日(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*""" ) A__ : Union[str, Any] = re.compile( r"""((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*億)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*万)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*千)*(0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*(千円|万円|千万円|円|千ドル|万ドル|千万ドル|ドル|千ユーロ|万ユーロ|千万ユーロ|ユーロ)+(\(税込\)|\(税抜\)|\+tax)*""" ) A__ : Dict = """─━│┃┄┅┆┇┈┉┊┋┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛├┝┞┟┠┡┢┣┤┥┦┧┨┩┪┫┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿""" A__ : List[Any] = """▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟""" A__ : Union[str, Any] = str.maketrans({k: """<BLOCK>""" for k in keisen + blocks} ) def __len__( self ): return len(self.ids_to_tokens ) def __A ( self , A__ ): A__ : Optional[Any] = self.content_repattera.sub("""<URL>""" , A__ ) A__ : Optional[int] = self.content_repattera.sub("""<EMAIL>""" , A__ ) A__ : Optional[Any] = self.content_repattera.sub("""<TEL>""" , A__ ) A__ : Union[str, Any] = self.content_repattera.sub("""<DATE>""" , A__ ) A__ : Union[str, Any] = self.content_repattera.sub("""<DATE>""" , A__ ) A__ : Optional[Any] = self.content_repattera.sub("""<PRICE>""" , A__ ) A__ : Tuple = content.translate(self.content_transa ) while "<BLOCK><BLOCK>" in content: A__ : Union[str, Any] = content.replace("""<BLOCK><BLOCK>""" , """<BLOCK>""" ) return content def __A ( self , A__ , A__=False ): A__ : str = text.replace(""" """ , """<SP>""" ) A__ : Dict = text.replace(""" """ , """<SP>""" ) A__ : str = text.replace("""\r\n""" , """<BR>""" ) A__ : Dict = text.replace("""\n""" , """<BR>""" ) A__ : str = text.replace("""\r""" , """<BR>""" ) A__ : Optional[int] = text.replace("""\t""" , """<TAB>""" ) A__ : List[str] = text.replace("""—""" , """ー""" ) A__ : str = text.replace("""−""" , """ー""" ) for k, v in self.emoji["emoji"].items(): if k in text: A__ : Any = text.replace(A__ , A__ ) if clean: A__ : Optional[Any] = self.clean_text(A__ ) def check_simbol(A__ ): A__ : Dict = x.encode() if len(A__ ) == 1 and len(A__ ) == 2: A__ : Optional[Any] = (int(e[0] ) << 8) + int(e[1] ) if ( (c >= 0xC_2A1 and c <= 0xC_2BF) or (c >= 0xC_780 and c <= 0xC_783) or (c >= 0xC_AB9 and c <= 0xC_BBF) or (c >= 0xC_C80 and c <= 0xC_DA2) ): return True return False def checkuae(A__ ): A__ : Tuple = x.encode() if len(A__ ) == 1 and len(A__ ) == 3: A__ : Union[str, Any] = (int(e[0] ) << 16) + (int(e[1] ) << 8) + int(e[2] ) if c >= 0xE28_080 and c <= 0xE2B_07F: return True return False A__ : List[str] = 0 A__ : Dict = [] while pos < len(A__ ): A__ : Dict = min(len(A__ ) , pos + self.maxlen + 1 ) if text[pos] == """<""" else pos + 3 A__ : str = [] # (token_id, token, pos) for e in range(A__ , A__ , -1 ): A__ : Union[str, Any] = text[pos:e] if wd in self.vocab: if wd[0] == "<" and len(A__ ) > 2: A__ : List[Any] = [(self.vocab[wd], wd, e)] break else: candidates.append((self.vocab[wd], wd, e) ) if len(A__ ) > 0: # the smallest token_id is adopted A__ , A__ , A__ : Any = sorted(A__ , key=lambda A__ : x[0] )[0] result.append(A__ ) A__ : Dict = e else: A__ : Optional[Any] = pos + 1 A__ : str = text[pos:end] if check_simbol(A__ ): result.append("""<KIGOU>""" ) elif checkuae(A__ ): result.append("""<U2000U2BFF>""" ) else: for i in wd.encode("""utf-8""" ): result.append("""<|byte%d|>""" % i ) A__ : int = end return result def __A ( self , A__ , A__="\n" ): A__ : List[str] = [] A__ : Any = [] A__ : str = self.ids_to_tokens[index][0] if word[:6] == "<|byte" and word[-2:] == "|>": byte_tokens.append(int(word[6:-2] ) ) else: if len(A__ ) > 0: words.append(bytearray(A__ ).decode("""utf-8""" , errors="""replace""" ) ) A__ : List[Any] = [] if word[:7] == "<|emoji" and word[-2:] == "|>": words.append(self.emoji["""emoji_inv"""][word] ) elif word == "<SP>": words.append(""" """ ) elif word == "<BR>": words.append(A__ ) elif word == "<TAB>": words.append("""\t""" ) elif word == "<BLOCK>": words.append("""▀""" ) elif word == "<KIGOU>": words.append("""ǀ""" ) elif word == "<U2000U2BFF>": words.append("""‖""" ) else: words.append(A__ ) if len(A__ ) > 0: words.append(bytearray(A__ ).decode("""utf-8""" , errors="""replace""" ) ) A__ : Optional[Any] = """""".join(A__ ) return text
720
from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class _a (__magic_name__ , __magic_name__ , __magic_name__ ): '''simple docstring''' UpperCAmelCase__: str = [r'''h\.\d+\.attn\.bias''', r'''h\.\d+\.attn\.masked_bias'''] @register_to_config def __init__( self , A__ , A__ , A__ = None , A__ = 5_0257 , A__ = 1024 , A__ = 768 , A__ = 12 , A__ = 12 , A__ = None , A__ = "gelu_new" , A__ = 0.1 , A__ = 0.1 , A__ = 0.1 , A__ = 1e-5 , A__ = 0.0_2 , A__ = True , A__ = True , A__ = False , A__ = False , ): super().__init__() A__ : Union[str, Any] = prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( F"""`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and""" F""" `n_embd`: {n_embd} are not equal.""" ) A__ : str = prefix_inner_dim A__ : Optional[Any] = prefix_hidden_dim A__ : Tuple = ( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) A__ : int = ( nn.Linear(self.prefix_hidden_dim , A__ ) if self.prefix_hidden_dim is not None else nn.Identity() ) A__ : Tuple = GPTaConfig( vocab_size=A__ , n_positions=A__ , n_embd=A__ , n_layer=A__ , n_head=A__ , n_inner=A__ , activation_function=A__ , resid_pdrop=A__ , embd_pdrop=A__ , attn_pdrop=A__ , layer_norm_epsilon=A__ , initializer_range=A__ , scale_attn_weights=A__ , use_cache=A__ , scale_attn_by_inverse_layer_idx=A__ , reorder_and_upcast_attn=A__ , ) A__ : int = GPTaLMHeadModel(A__ ) def __A ( self , A__ , A__ , A__ = None , A__ = None , ): A__ : List[str] = self.transformer.transformer.wte(A__ ) A__ : int = self.encode_prefix(A__ ) A__ : int = self.decode_prefix(A__ ) A__ : Optional[Any] = torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: A__ : Any = self.get_dummy_token(input_ids.shape[0] , input_ids.device ) A__ : List[Any] = torch.cat((dummy_token, input_ids) , dim=1 ) A__ : List[str] = self.transformer(inputs_embeds=A__ , labels=A__ , attention_mask=A__ ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def __A ( self , A__ , A__ ): return torch.zeros(A__ , self.prefix_length , dtype=torch.intaa , device=A__ ) def __A ( self , A__ ): return self.encode_prefix(A__ ) @torch.no_grad() def __A ( self , A__ , A__ , A__ ): A__ : List[Any] = torch.split(A__ , 1 , dim=0 ) A__ : Optional[int] = [] A__ : str = [] for feature in features: A__ : Dict = self.decode_prefix(feature.to(A__ ) ) # back to the clip feature # Only support beam search for now A__ , A__ : Union[str, Any] = self.generate_beam( input_embeds=A__ , device=A__ , eos_token_id=A__ ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) A__ : int = torch.stack(A__ ) A__ : List[Any] = torch.stack(A__ ) return generated_tokens, generated_seq_lengths @torch.no_grad() def __A ( self , A__=None , A__=None , A__=None , A__ = 5 , A__ = 67 , A__ = 1.0 , A__ = None , ): A__ : Any = eos_token_id A__ : Any = None A__ : Optional[int] = None A__ : Optional[Any] = torch.ones(A__ , device=A__ , dtype=torch.int ) A__ : Any = torch.zeros(A__ , device=A__ , dtype=torch.bool ) if input_embeds is not None: A__ : Dict = input_embeds else: A__ : str = self.transformer.transformer.wte(A__ ) for i in range(A__ ): A__ : Dict = self.transformer(inputs_embeds=A__ ) A__ : str = outputs.logits A__ : Union[str, Any] = logits[:, -1, :] / (temperature if temperature > 0 else 1.0) A__ : Any = logits.softmax(-1 ).log() if scores is None: A__ , A__ : Optional[int] = logits.topk(A__ , -1 ) A__ : List[Any] = generated.expand(A__ , *generated.shape[1:] ) A__ , A__ : List[Any] = next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: A__ : Optional[Any] = next_tokens else: A__ : List[Any] = tokens.expand(A__ , *tokens.shape[1:] ) A__ : int = torch.cat((tokens, next_tokens) , dim=1 ) else: A__ : Optional[int] = -float(np.inf ) A__ : List[Any] = 0 A__ : str = scores[:, None] + logits seq_lengths[~is_stopped] += 1 A__ : Dict = scores_sum / seq_lengths[:, None] A__ , A__ : List[Any] = scores_sum_average.view(-1 ).topk(A__ , -1 ) A__ : Tuple = next_tokens // scores_sum.shape[1] A__ : Optional[Any] = seq_lengths[next_tokens_source] A__ : List[str] = next_tokens % scores_sum.shape[1] A__ : Optional[int] = next_tokens.unsqueeze(1 ) A__ : int = tokens[next_tokens_source] A__ : List[Any] = torch.cat((tokens, next_tokens) , dim=1 ) A__ : str = generated[next_tokens_source] A__ : Optional[Any] = scores_sum_average * seq_lengths A__ : Union[str, Any] = is_stopped[next_tokens_source] A__ : str = self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) A__ : Optional[int] = torch.cat((generated, next_token_embed) , dim=1 ) A__ : List[str] = is_stopped + next_tokens.eq(A__ ).squeeze() if is_stopped.all(): break A__ : Dict = scores / seq_lengths A__ : Dict = scores.argsort(descending=A__ ) # tokens tensors are already padded to max_seq_length A__ : Union[str, Any] = [tokens[i] for i in order] A__ : Any = torch.stack(A__ , dim=0 ) A__ : Dict = torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
64
0
from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_VISION_2_SEQ_MAPPING if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING A_ = logging.get_logger(__name__) @add_end_docstrings(snake_case__ ) class _a (snake_case__ ): '''simple docstring''' def __init__( self , *A__ , **A__ ): super().__init__(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) requires_backends(self , """vision""" ) self.check_model_type( TF_MODEL_FOR_VISION_2_SEQ_MAPPING if self.framework == """tf""" else MODEL_FOR_VISION_2_SEQ_MAPPING ) def __A ( self , A__=None , A__=None , A__=None ): A__ : List[str] = {} A__ : Dict = {} if prompt is not None: A__ : Optional[int] = prompt if generate_kwargs is not None: A__ : int = generate_kwargs if max_new_tokens is not None: if "generate_kwargs" not in forward_kwargs: A__ : List[str] = {} if "max_new_tokens" in forward_kwargs["generate_kwargs"]: raise ValueError( """\'max_new_tokens\' is defined twice, once in \'generate_kwargs\' and once as a direct parameter,""" """ please use only one""" ) A__ : Dict = max_new_tokens return preprocess_params, forward_kwargs, {} def __call__( self , A__ , **A__ ): return super().__call__(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def __A ( self , A__ , A__=None ): A__ : Dict = load_image(_SCREAMING_SNAKE_CASE ) if prompt is not None: if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise ValueError( F"""Received an invalid text input, got - {type(_SCREAMING_SNAKE_CASE )} - but expected a single string. """ """Note also that one single text can be provided for conditional image to text generation.""" ) A__ : str = self.model.config.model_type if model_type == "git": A__ : Tuple = self.image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) A__ : Optional[Any] = self.tokenizer(text=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ).input_ids A__ : Dict = [self.tokenizer.cls_token_id] + input_ids A__ : Tuple = torch.tensor(_SCREAMING_SNAKE_CASE ).unsqueeze(0 ) model_inputs.update({"""input_ids""": input_ids} ) elif model_type == "pix2struct": A__ : Tuple = self.image_processor(images=_SCREAMING_SNAKE_CASE , header_text=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) elif model_type != "vision-encoder-decoder": # vision-encoder-decoder does not support conditional generation A__ : Optional[int] = self.image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) A__ : Union[str, Any] = self.tokenizer(_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) model_inputs.update(_SCREAMING_SNAKE_CASE ) else: raise ValueError(F"""Model type {model_type} does not support conditional text generation""" ) else: A__ : int = self.image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) if self.model.config.model_type == "git" and prompt is None: A__ : List[str] = None return model_inputs def __A ( self , A__ , A__=None ): # Git model sets `model_inputs["input_ids"] = None` in `preprocess` (when `prompt=None`). In batch model, the # pipeline will group them into a list of `None`, which fail `_forward`. Avoid this by checking it first. if ( "input_ids" in model_inputs and isinstance(model_inputs["""input_ids"""] , _SCREAMING_SNAKE_CASE ) and all(x is None for x in model_inputs["""input_ids"""] ) ): A__ : Dict = None if generate_kwargs is None: A__ : Any = {} # FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py` # parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas # the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name` # in the `_prepare_model_inputs` method. A__ : List[str] = model_inputs.pop(self.model.main_input_name ) A__ : Optional[int] = self.model.generate(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) return model_outputs def __A ( self , A__ ): A__ : Optional[int] = [] for output_ids in model_outputs: A__ : Union[str, Any] = { """generated_text""": self.tokenizer.decode( _SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE , ) } records.append(_SCREAMING_SNAKE_CASE ) return records
721
import io import itertools import json from dataclasses import dataclass from typing import Optional import pyarrow as pa import pyarrow.json as paj import datasets from datasets.table import table_cast from datasets.utils.file_utils import readline A_ : Tuple = datasets.utils.logging.get_logger(__name__) @dataclass class _a (datasets.BuilderConfig ): '''simple docstring''' UpperCAmelCase__: Optional[datasets.Features] = None UpperCAmelCase__: str = "utf-8" UpperCAmelCase__: Optional[str] = None UpperCAmelCase__: Optional[str] = None UpperCAmelCase__: bool = True # deprecated UpperCAmelCase__: Optional[int] = None # deprecated UpperCAmelCase__: int = 10 << 20 # 10MB UpperCAmelCase__: Optional[bool] = None class _a (datasets.ArrowBasedBuilder ): '''simple docstring''' UpperCAmelCase__: List[str] = JsonConfig def __A ( self ): if self.config.block_size is not None: logger.warning("""The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead""" ) A__ : Union[str, Any] = self.config.block_size if self.config.use_threads is not True: logger.warning( """The JSON loader parameter `use_threads` is deprecated and doesn't have any effect anymore.""" ) if self.config.newlines_in_values is not None: raise ValueError("""The JSON loader parameter `newlines_in_values` is no longer supported""" ) return datasets.DatasetInfo(features=self.config.features ) def __A ( self , A__ ): if not self.config.data_files: raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}""" ) A__ : int = dl_manager.download_and_extract(self.config.data_files ) if isinstance(A__ , (str, list, tuple) ): A__ : Optional[Any] = data_files if isinstance(A__ , A__ ): A__ : List[str] = [files] A__ : int = [dl_manager.iter_files(A__ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""files""": files} )] A__ : List[str] = [] for split_name, files in data_files.items(): if isinstance(A__ , A__ ): A__ : Optional[int] = [files] A__ : Optional[int] = [dl_manager.iter_files(A__ ) for file in files] splits.append(datasets.SplitGenerator(name=A__ , gen_kwargs={"""files""": files} ) ) return splits def __A ( self , A__ ): if self.config.features is not None: # adding missing columns for column_name in set(self.config.features ) - set(pa_table.column_names ): A__ : Optional[Any] = self.config.features.arrow_schema.field(A__ ).type A__ : str = pa_table.append_column(A__ , pa.array([None] * len(A__ ) , type=A__ ) ) # more expensive cast to support nested structures with keys in a different order # allows str <-> int/float or str to Audio for example A__ : Optional[int] = table_cast(A__ , self.config.features.arrow_schema ) return pa_table def __A ( self , A__ ): for file_idx, file in enumerate(itertools.chain.from_iterable(A__ ) ): # If the file is one json object and if we need to look at the list of items in one specific field if self.config.field is not None: with open(A__ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: A__ : Optional[Any] = json.load(A__ ) # We keep only the field we are interested in A__ : Optional[int] = dataset[self.config.field] # We accept two format: a list of dicts or a dict of lists if isinstance(A__ , (list, tuple) ): A__ : Union[str, Any] = set().union(*[row.keys() for row in dataset] ) A__ : Any = {col: [row.get(A__ ) for row in dataset] for col in keys} else: A__ : Any = dataset A__ : Any = pa.Table.from_pydict(A__ ) yield file_idx, self._cast_table(A__ ) # If the file has one json object per line else: with open(A__ , """rb""" ) as f: A__ : List[str] = 0 # Use block_size equal to the chunk size divided by 32 to leverage multithreading # Set a default minimum value of 16kB if the chunk size is really small A__ : List[str] = max(self.config.chunksize // 32 , 16 << 10 ) A__ : Any = ( self.config.encoding_errors if self.config.encoding_errors is not None else """strict""" ) while True: A__ : Dict = f.read(self.config.chunksize ) if not batch: break # Finish current line try: batch += f.readline() except (AttributeError, io.UnsupportedOperation): batch += readline(A__ ) # PyArrow only accepts utf-8 encoded bytes if self.config.encoding != "utf-8": A__ : List[Any] = batch.decode(self.config.encoding , errors=A__ ).encode("""utf-8""" ) try: while True: try: A__ : str = paj.read_json( io.BytesIO(A__ ) , read_options=paj.ReadOptions(block_size=A__ ) ) break except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e: if ( isinstance(A__ , pa.ArrowInvalid ) and "straddling" not in str(A__ ) or block_size > len(A__ ) ): raise else: # Increase the block size in case it was too small. # The block size will be reset for the next file. logger.debug( F"""Batch of {len(A__ )} bytes couldn't be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.""" ) block_size *= 2 except pa.ArrowInvalid as e: try: with open( A__ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: A__ : Optional[Any] = json.load(A__ ) except json.JSONDecodeError: logger.error(F"""Failed to read file '{file}' with error {type(A__ )}: {e}""" ) raise e # If possible, parse the file as a list of json objects and exit the loop if isinstance(A__ , A__ ): # list is the only sequence type supported in JSON try: A__ : str = set().union(*[row.keys() for row in dataset] ) A__ : List[str] = {col: [row.get(A__ ) for row in dataset] for col in keys} A__ : int = pa.Table.from_pydict(A__ ) except (pa.ArrowInvalid, AttributeError) as e: logger.error(F"""Failed to read file '{file}' with error {type(A__ )}: {e}""" ) raise ValueError(F"""Not able to read records in the JSON file at {file}.""" ) from None yield file_idx, self._cast_table(A__ ) break else: logger.error(F"""Failed to read file '{file}' with error {type(A__ )}: {e}""" ) raise ValueError( F"""Not able to read records in the JSON file at {file}. """ F"""You should probably indicate the field of the JSON file containing your records. """ F"""This JSON file contain the following fields: {str(list(dataset.keys() ) )}. """ F"""Select the correct one and provide it as `field='XXX'` to the dataset loading method. """ ) from None # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(A__ ) batch_idx += 1
64
0
from __future__ import annotations class _a : '''simple docstring''' def __init__( self , A__ = 0 ): A__ : Union[str, Any] = key def __A ( self , A__ , A__ ): assert isinstance(A__ , A__ ) and isinstance(A__ , A__ ) A__ : Union[str, Any] = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(A__ ) ^ key ) for ch in content] def __A ( self , A__ , A__ ): assert isinstance(A__ , A__ ) and isinstance(A__ , A__ ) A__ : str = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(A__ ) ^ key ) for ch in content] def __A ( self , A__ , A__ = 0 ): assert isinstance(A__ , A__ ) and isinstance(A__ , A__ ) A__ : Optional[Any] = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned A__ : List[str] = """""" for ch in content: ans += chr(ord(A__ ) ^ key ) return ans def __A ( self , A__ , A__ = 0 ): assert isinstance(A__ , A__ ) and isinstance(A__ , A__ ) A__ : Optional[Any] = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned A__ : List[Any] = """""" for ch in content: ans += chr(ord(A__ ) ^ key ) return ans def __A ( self , A__ , A__ = 0 ): assert isinstance(A__ , A__ ) and isinstance(A__ , A__ ) try: with open(A__ ) as fin, open("""encrypt.out""" , """w+""" ) as fout: # actual encrypt-process for line in fin: fout.write(self.encrypt_string(A__ , A__ ) ) except OSError: return False return True def __A ( self , A__ , A__ ): assert isinstance(A__ , A__ ) and isinstance(A__ , A__ ) try: with open(A__ ) as fin, open("""decrypt.out""" , """w+""" ) as fout: # actual encrypt-process for line in fin: fout.write(self.decrypt_string(A__ , A__ ) ) except OSError: return False return True # Tests # crypt = XORCipher() # key = 67 # # test encrypt # print(crypt.encrypt("hallo welt",key)) # # test decrypt # print(crypt.decrypt(crypt.encrypt("hallo welt",key), key)) # # test encrypt_string # print(crypt.encrypt_string("hallo welt",key)) # # test decrypt_string # print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key)) # if (crypt.encrypt_file("test.txt",key)): # print("encrypt successful") # else: # print("encrypt unsuccessful") # if (crypt.decrypt_file("encrypt.out",key)): # print("decrypt successful") # else: # print("decrypt unsuccessful")
700
import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore A_ : Dict = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" A_ : Optional[Any] = [file for file in filepaths if file != file.lower()] if upper_files: print(f'''{len(upper_files)} files contain uppercase characters:''') print('\n'.join(upper_files) + '\n') A_ : Tuple = [file for file in filepaths if ' ' in file] if space_files: print(f'''{len(space_files)} files contain space characters:''') print('\n'.join(space_files) + '\n') A_ : Any = [file for file in filepaths if '-' in file] if hyphen_files: print(f'''{len(hyphen_files)} files contain hyphen characters:''') print('\n'.join(hyphen_files) + '\n') A_ : List[str] = [file for file in filepaths if os.sep not in file] if nodir_files: print(f'''{len(nodir_files)} files are not in a directory:''') print('\n'.join(nodir_files) + '\n') A_ : Any = len(upper_files + space_files + hyphen_files + nodir_files) if bad_files: import sys sys.exit(bad_files)
64
0
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class _a (unittest.TestCase ): '''simple docstring''' def __A ( self ): A__ : int = inspect.getfile(accelerate.test_utils ) A__ : str = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_script.py"""] ) A__ : List[Any] = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_distributed_data_loop.py"""] ) A__ : Dict = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_ops.py"""] ) @require_multi_gpu def __A ( self ): print(F"""Found {torch.cuda.device_count()} devices.""" ) A__ : Optional[int] = ["""torchrun""", F"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(A__ , env=os.environ.copy() ) @require_multi_gpu def __A ( self ): print(F"""Found {torch.cuda.device_count()} devices.""" ) A__ : Any = ["""torchrun""", F"""--nproc_per_node={torch.cuda.device_count()}""", self.operation_file_path] print(F"""Command: {cmd}""" ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(A__ , env=os.environ.copy() ) @require_multi_gpu def __A ( self ): A__ : List[Any] = ["""torchrun""", F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(A__ , env=os.environ.copy() ) @require_multi_gpu def __A ( self ): print(F"""Found {torch.cuda.device_count()} devices, using 2 devices only""" ) A__ : Optional[int] = ["""torchrun""", F"""--nproc_per_node={torch.cuda.device_count()}""", self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices="""0,1""" ): execute_subprocess_async(A__ , env=os.environ.copy() ) if __name__ == "__main__": A_ : Optional[Any] = Accelerator() A_ : Tuple = (accelerator.state.process_index + 2, 10) A_ : Any = torch.randint(0, 10, shape).to(accelerator.device) A_ : Any = '' A_ : List[str] = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." A_ : Tuple = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." A_ : List[str] = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
701
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def UpperCamelCase (*lowercase_: Optional[int] , lowercase_: Optional[Union[Dict, Any]] = None , lowercase_: Dict=True , lowercase_: Tuple=2 ) -> Dict: from .. import __version__ A__ : Dict = take_from A__ : str = () if not isinstance(args[0] , lowercase_ ): A__ : int = (args,) for attribute, version_name, message in args: if version.parse(version.parse(lowercase_ ).base_version ) >= version.parse(lowercase_ ): raise ValueError( f"""The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers'""" f""" version {__version__} is >= {version_name}""" ) A__ : Any = None if isinstance(lowercase_ , lowercase_ ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(lowercase_ ),) A__ : List[str] = f"""The `{attribute}` argument is deprecated and will be removed in version {version_name}.""" elif hasattr(lowercase_ , lowercase_ ): values += (getattr(lowercase_ , lowercase_ ),) A__ : Optional[Any] = f"""The `{attribute}` attribute is deprecated and will be removed in version {version_name}.""" elif deprecated_kwargs is None: A__ : int = f"""`{attribute}` is deprecated and will be removed in version {version_name}.""" if warning is not None: A__ : int = warning + """ """ if standard_warn else """""" warnings.warn(warning + message , lowercase_ , stacklevel=lowercase_ ) if isinstance(lowercase_ , lowercase_ ) and len(lowercase_ ) > 0: A__ : Union[str, Any] = inspect.getouterframes(inspect.currentframe() )[1] A__ : Optional[Any] = call_frame.filename A__ : Optional[int] = call_frame.lineno A__ : Any = call_frame.function A__ , A__ : List[str] = next(iter(deprecated_kwargs.items() ) ) raise TypeError(f"""{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`""" ) if len(lowercase_ ) == 0: return elif len(lowercase_ ) == 1: return values[0] return values
64
0
from math import factorial def UpperCamelCase (lowercase_: int , lowercase_: int ) -> int: # If either of the conditions are true, the function is being asked # to calculate a factorial of a negative number, which is not possible if n < k or k < 0: raise ValueError("""Please enter positive integers for n and k where n >= k""" ) return factorial(lowercase_ ) // (factorial(lowercase_ ) * factorial(n - k )) if __name__ == "__main__": print( 'The number of five-card hands possible from a standard', f'''fifty-two card deck is: {combinations(52, 5)}\n''', ) print( 'If a class of 40 students must be arranged into groups of', f'''4 for group projects, there are {combinations(40, 4)} ways''', 'to arrange them.\n', ) print( 'If 10 teams are competing in a Formula One race, there', f'''are {combinations(10, 3)} ways that first, second and''', 'third place can be awarded.', )
702
import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import ( rename_keys, ) from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME from transformers.utils.hub import convert_file_size_to_int def UpperCamelCase (lowercase_: List[str] , lowercase_: str ) -> Optional[Any]: if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer A__ : Union[str, Any] = flax_key_tuple[:-1] + ("""weight""",) A__ : Optional[int] = torch.permute(lowercase_ , (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(lowercase_ ): # linear layer A__ : Optional[Any] = flax_key_tuple[:-1] + ("""weight""",) A__ : int = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: A__ : Optional[int] = flax_key_tuple[:-1] + ("""weight""",) return flax_key_tuple, flax_tensor def UpperCamelCase (lowercase_: Tuple , lowercase_: Optional[int] , lowercase_: str ) -> Union[str, Any]: if "metadata" in layer: A__ : Tuple = layer.split("""metadata""" ) A__ : Optional[Any] = """""".join(split_layer[0] )[:-1] A__ : Optional[Any] = [tuple(("""metadata""" + split_layer[1]).split("""/""" ) )] elif "kvstore" in layer: A__ : str = layer.split("""kvstore""" ) A__ : int = """""".join(split_layer[0] )[:-1] A__ : Optional[int] = [tuple(("""kvstore""" + split_layer[1]).split("""/""" ) )] else: A__ : Any = layer.split("""/""" ) A__ : int = """/""".join(split_layer[:-1] ) A__ : str = (split_layer[-1],) if "kvstore/path" in layer: A__ : Dict = f"""{switch_checkpoint_path}/{checkpoint_info[layer]}""" elif "kvstore/driver" in layer: A__ : Optional[int] = """file""" else: A__ : str = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def UpperCamelCase (lowercase_: str , lowercase_: List[Any] ) -> int: A__ : int = rename_keys(lowercase_ ) A__ : Any = {} for k, v in current_block.items(): A__ : Dict = v A__ : str = new_current_block torch.save(lowercase_ , lowercase_ ) def UpperCamelCase (lowercase_: Dict , lowercase_: Optional[Any] , lowercase_: Optional[Any] , lowercase_: Optional[int] , lowercase_: str = WEIGHTS_NAME ) -> Tuple: A__ : Optional[int] = convert_file_size_to_int(lowercase_ ) A__ : List[Any] = [] A__ : int = {} A__ : List[str] = 0 A__ : Any = 0 os.makedirs(lowercase_ , exist_ok=lowercase_ ) with gfile.GFile(switch_checkpoint_path + """/checkpoint""" , """rb""" ) as fp: A__ : Optional[Any] = serialization.msgpack_restore(fp.read() )["""optimizer"""]["""target"""] A__ : Dict = flatten_dict(lowercase_ , sep="""/""" ) A__ : Any = {} for layer in checkpoint_info.keys(): A__ , A__ , A__ : Union[str, Any] = get_key_and_tensorstore_dict( lowercase_ , lowercase_ , lowercase_ ) if curr_real_layer_name in all_layers: A__ : Optional[int] = content else: A__ : List[Any] = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file A__ : Optional[Any] = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() A__ : List[Any] = torch.tensor(lowercase_ ) A__ : List[Any] = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts A__ , A__ : Any = rename_base_flax_keys(tuple(key.split("""/""" ) ) , lowercase_ ) A__ : Any = """/""".join(lowercase_ ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: A__ : List[Any] = os.path.join( lowercase_ , weights_name.replace(""".bin""" , f"""-{len(lowercase_ )+1:05d}-of-???.bin""" ) ) rename_and_save_block(lowercase_ , lowercase_ ) sharded_state_dicts.append(current_block.keys() ) del current_block A__ : Any = {} A__ : str = 0 A__ : List[str] = raw_weights.to(getattr(lowercase_ , lowercase_ ) ) current_block_size += weight_size total_size += weight_size # Add the last block A__ : Union[str, Any] = os.path.join(lowercase_ , weights_name.replace(""".bin""" , f"""-{len(lowercase_ )+1:05d}-of-???.bin""" ) ) rename_and_save_block(lowercase_ , lowercase_ ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(lowercase_ ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index A__ : str = {} A__ : Any = {} for idx, shard in enumerate(lowercase_ ): A__ : Any = weights_name.replace( """.bin""" , f"""-{idx+1:05d}-of-{len(lowercase_ ):05d}.bin""" ) # len(sharded_state_dicts):05d} A__ : Dict = os.path.join(lowercase_ , weights_name.replace(""".bin""" , f"""-{idx+1:05d}-of-???.bin""" ) ) os.rename(lowercase_ , os.path.join(lowercase_ , lowercase_ ) ) A__ : str = shard for key in shard: A__ : Any = shard_file # Add the metadata A__ : Tuple = {"""total_size""": total_size} A__ : Union[str, Any] = {"""metadata""": metadata, """weight_map""": weight_map} with open(os.path.join(lowercase_ , lowercase_ ) , """w""" , encoding="""utf-8""" ) as f: A__ : Dict = json.dumps(lowercase_ , indent=2 , sort_keys=lowercase_ ) + """\n""" f.write(lowercase_ ) return metadata, index if __name__ == "__main__": A_ : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--switch_t5x_checkpoint_path', default='/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600', type=str, required=False, help='Path to a directory containing a folder per layer. Follows the original Google format.', ) parser.add_argument('--max_shard_size', default='10GB', required=False, help='Max shard size') parser.add_argument('--dtype', default='bfloat16', type=str, required=False, help='dtype of the saved model') parser.add_argument( '--pytorch_dump_folder_path', default='/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted', type=str, required=False, help='Path to the output pytorch model.', ) A_ : Dict = parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def UpperCamelCase () -> int: from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer A__ : str = SwitchTransformersConfig.from_pretrained("""google/switch-base-8""" ) config.save_pretrained("""/home/arthur_huggingface_co/transformers/switch_converted""" ) A__ : str = SwitchTransformersForConditionalGeneration.from_pretrained( """/home/arthur_huggingface_co/transformers/switch_converted""" , device_map="""auto""" ) A__ : Tuple = TaTokenizer.from_pretrained("""t5-small""" ) A__ : Dict = """A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.""" A__ : Union[str, Any] = tokenizer(lowercase_ , return_tensors="""pt""" ).input_ids A__ : Tuple = model.generate(lowercase_ , decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
64
0
import argparse import re from typing import Dict import torch from datasets import Audio, Dataset, load_dataset, load_metric from transformers import AutoFeatureExtractor, pipeline def UpperCamelCase (lowercase_: Dataset , lowercase_: Dict[str, str] ) -> List[str]: A__ : int = args.log_outputs A__ : str = """_""".join(args.dataset.split("""/""" ) + [args.config, args.split] ) # load metric A__ : str = load_metric("""wer""" ) A__ : Optional[int] = load_metric("""cer""" ) # compute metrics A__ : Dict = wer.compute(references=result["""target"""] , predictions=result["""prediction"""] ) A__ : Union[str, Any] = cer.compute(references=result["""target"""] , predictions=result["""prediction"""] ) # print & log results A__ : Union[str, Any] = f"""WER: {wer_result}\nCER: {cer_result}""" print(lowercase_ ) with open(f"""{dataset_id}_eval_results.txt""" , """w""" ) as f: f.write(lowercase_ ) # log all results in text file. Possibly interesting for analysis if log_outputs is not None: A__ : int = f"""log_{dataset_id}_predictions.txt""" A__ : List[str] = f"""log_{dataset_id}_targets.txt""" with open(lowercase_ , """w""" ) as p, open(lowercase_ , """w""" ) as t: # mapping function to write output def write_to_file(lowercase_: List[Any] , lowercase_: List[Any] ): p.write(f"""{i}""" + """\n""" ) p.write(batch["""prediction"""] + """\n""" ) t.write(f"""{i}""" + """\n""" ) t.write(batch["""target"""] + """\n""" ) result.map(lowercase_ , with_indices=lowercase_ ) def UpperCamelCase (lowercase_: str ) -> str: A__ : Optional[int] = """[,?.!\-\;\:\"“%‘”�—’…–]""" # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training A__ : int = re.sub(lowercase_ , """""" , text.lower() ) # In addition, we can normalize the target text, e.g. removing new lines characters etc... # note that order is important here! A__ : Optional[Any] = ["""\n\n""", """\n""", """ """, """ """] for t in token_sequences_to_ignore: A__ : Optional[Any] = """ """.join(text.split(lowercase_ ) ) return text def UpperCamelCase (lowercase_: Dict ) -> Any: # load dataset A__ : Any = load_dataset(args.dataset , args.config , split=args.split , use_auth_token=lowercase_ ) # for testing: only process the first two examples as a test # dataset = dataset.select(range(10)) # load processor A__ : Tuple = AutoFeatureExtractor.from_pretrained(args.model_id ) A__ : List[Any] = feature_extractor.sampling_rate # resample audio A__ : List[str] = dataset.cast_column("""audio""" , Audio(sampling_rate=lowercase_ ) ) # load eval pipeline if args.device is None: A__ : List[Any] = 0 if torch.cuda.is_available() else -1 A__ : Optional[Any] = pipeline("""automatic-speech-recognition""" , model=args.model_id , device=args.device ) # map function to decode audio def map_to_pred(lowercase_: str ): A__ : Optional[Any] = asr( batch["""audio"""]["""array"""] , chunk_length_s=args.chunk_length_s , stride_length_s=args.stride_length_s ) A__ : str = prediction["""text"""] A__ : Dict = normalize_text(batch["""sentence"""] ) return batch # run inference on all examples A__ : int = dataset.map(lowercase_ , remove_columns=dataset.column_names ) # compute and log_results # do not change function below log_results(lowercase_ , lowercase_ ) if __name__ == "__main__": A_ : List[Any] = argparse.ArgumentParser() parser.add_argument( '--model_id', type=str, required=True, help='Model identifier. Should be loadable with 🤗 Transformers' ) parser.add_argument( '--dataset', type=str, required=True, help='Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets', ) parser.add_argument( '--config', type=str, required=True, help='Config of the dataset. *E.g.* `\'en\'` for Common Voice' ) parser.add_argument('--split', type=str, required=True, help='Split of the dataset. *E.g.* `\'test\'`') parser.add_argument( '--chunk_length_s', type=float, default=None, help='Chunk length in seconds. Defaults to 5 seconds.' ) parser.add_argument( '--stride_length_s', type=float, default=None, help='Stride of the audio chunks. Defaults to 1 second.' ) parser.add_argument( '--log_outputs', action='store_true', help='If defined, write outputs to log file for analysis.' ) parser.add_argument( '--device', type=int, default=None, help='The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.', ) A_ : List[Any] = parser.parse_args() main(args)
703
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available A_ : Optional[Any] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : str = ['BartphoTokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bartpho import BartphoTokenizer else: import sys A_ : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
64
0
def UpperCamelCase (lowercase_: int ) -> "list[int]": if upper_limit < 0: raise ValueError("""Limit for the Catalan sequence must be ≥ 0""" ) A__ : str = [0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 A__ : Dict = 1 if upper_limit > 0: A__ : str = 1 # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i for i in range(2 , upper_limit + 1 ): for j in range(lowercase_ ): catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1] return catalan_list if __name__ == "__main__": print('\n********* Catalan Numbers Using Dynamic Programming ************\n') print('\n*** Enter -1 at any time to quit ***') print('\nEnter the upper limit (≥ 0) for the Catalan number sequence: ', end='') try: while True: A_ : List[Any] = 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()
704
import argparse import hashlib import os import urllib import warnings import torch from torch import nn from tqdm import tqdm from transformers import WhisperConfig, WhisperForConditionalGeneration A_ : Dict = { 'tiny.en': 'https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt', 'tiny': 'https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt', 'base.en': 'https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt', 'base': 'https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt', 'small.en': 'https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt', 'small': 'https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt', 'medium.en': 'https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt', 'medium': 'https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt', 'large': 'https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt', 'large-v2': 'https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt', } def UpperCamelCase (lowercase_: Optional[Any] ) -> Optional[int]: A__ : List[Any] = ["""layers""", """blocks"""] for k in ignore_keys: state_dict.pop(lowercase_ , lowercase_ ) A_ : Any = { 'blocks': 'layers', 'mlp.0': 'fc1', 'mlp.2': 'fc2', 'mlp_ln': 'final_layer_norm', '.attn.query': '.self_attn.q_proj', '.attn.key': '.self_attn.k_proj', '.attn.value': '.self_attn.v_proj', '.attn_ln': '.self_attn_layer_norm', '.attn.out': '.self_attn.out_proj', '.cross_attn.query': '.encoder_attn.q_proj', '.cross_attn.key': '.encoder_attn.k_proj', '.cross_attn.value': '.encoder_attn.v_proj', '.cross_attn_ln': '.encoder_attn_layer_norm', '.cross_attn.out': '.encoder_attn.out_proj', 'decoder.ln.': 'decoder.layer_norm.', 'encoder.ln.': 'encoder.layer_norm.', 'token_embedding': 'embed_tokens', 'encoder.positional_embedding': 'encoder.embed_positions.weight', 'decoder.positional_embedding': 'decoder.embed_positions.weight', 'ln_post': 'layer_norm', } def UpperCamelCase (lowercase_: str ) -> Any: A__ : Dict = list(s_dict.keys() ) for key in keys: A__ : List[str] = key for k, v in WHISPER_MAPPING.items(): if k in key: A__ : List[Any] = new_key.replace(lowercase_ , lowercase_ ) print(f"""{key} -> {new_key}""" ) A__ : Tuple = s_dict.pop(lowercase_ ) return s_dict def UpperCamelCase (lowercase_: Tuple ) -> Optional[int]: A__ , A__ : Any = emb.weight.shape A__ : str = nn.Linear(lowercase_ , lowercase_ , bias=lowercase_ ) A__ : Union[str, Any] = emb.weight.data return lin_layer def UpperCamelCase (lowercase_: str , lowercase_: str ) -> bytes: os.makedirs(lowercase_ , exist_ok=lowercase_ ) A__ : Tuple = os.path.basename(lowercase_ ) A__ : int = url.split("""/""" )[-2] A__ : Dict = os.path.join(lowercase_ , lowercase_ ) if os.path.exists(lowercase_ ) and not os.path.isfile(lowercase_ ): raise RuntimeError(f"""{download_target} exists and is not a regular file""" ) if os.path.isfile(lowercase_ ): A__ : Optional[Any] = open(lowercase_ , """rb""" ).read() if hashlib.shaaaa(lowercase_ ).hexdigest() == expected_shaaaa: return model_bytes else: warnings.warn(f"""{download_target} exists, but the SHA256 checksum does not match; re-downloading the file""" ) with urllib.request.urlopen(lowercase_ ) as source, open(lowercase_ , """wb""" ) as output: with tqdm( total=int(source.info().get("""Content-Length""" ) ) , ncols=80 , unit="""iB""" , unit_scale=lowercase_ , unit_divisor=1024 ) as loop: while True: A__ : Any = source.read(8192 ) if not buffer: break output.write(lowercase_ ) loop.update(len(lowercase_ ) ) A__ : Dict = open(lowercase_ , """rb""" ).read() if hashlib.shaaaa(lowercase_ ).hexdigest() != expected_shaaaa: raise RuntimeError( """Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model.""" ) return model_bytes def UpperCamelCase (lowercase_: List[Any] , lowercase_: Tuple ) -> Optional[Any]: if ".pt" not in checkpoint_path: A__ : Tuple = _download(_MODELS[checkpoint_path] ) else: A__ : Optional[int] = torch.load(lowercase_ , map_location="""cpu""" ) A__ : str = original_checkpoint["""dims"""] A__ : List[Any] = original_checkpoint["""model_state_dict"""] A__ : Optional[Any] = state_dict["""decoder.token_embedding.weight"""] remove_ignore_keys_(lowercase_ ) rename_keys(lowercase_ ) A__ : List[str] = True A__ : Optional[Any] = state_dict["""decoder.layers.0.fc1.weight"""].shape[0] A__ : List[Any] = WhisperConfig( vocab_size=dimensions["""n_vocab"""] , encoder_ffn_dim=lowercase_ , decoder_ffn_dim=lowercase_ , num_mel_bins=dimensions["""n_mels"""] , d_model=dimensions["""n_audio_state"""] , max_target_positions=dimensions["""n_text_ctx"""] , encoder_layers=dimensions["""n_audio_layer"""] , encoder_attention_heads=dimensions["""n_audio_head"""] , decoder_layers=dimensions["""n_text_layer"""] , decoder_attention_heads=dimensions["""n_text_state"""] , max_source_positions=dimensions["""n_audio_ctx"""] , ) A__ : Optional[Any] = WhisperForConditionalGeneration(lowercase_ ) A__ , A__ : List[Any] = model.model.load_state_dict(lowercase_ , strict=lowercase_ ) if len(lowercase_ ) > 0 and not set(lowercase_ ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( """Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,""" f""" but all the following weights are missing {missing}""" ) if tie_embeds: A__ : Any = make_linear_from_emb(model.model.decoder.embed_tokens ) else: A__ : str = proj_out_weights model.save_pretrained(lowercase_ ) if __name__ == "__main__": A_ : Any = argparse.ArgumentParser() # # Required parameters parser.add_argument('--checkpoint_path', type=str, help='Patht to the downloaded checkpoints') parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') A_ : Tuple = parser.parse_args() convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)
64
0
from typing import Dict, Iterable, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format, to_pil_image 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_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract A_ : str = logging.get_logger(__name__) def UpperCamelCase (lowercase_: Dict , lowercase_: Any , lowercase_: Optional[Any] ) -> Optional[Any]: return [ int(1000 * (box[0] / width) ), int(1000 * (box[1] / height) ), int(1000 * (box[2] / width) ), int(1000 * (box[3] / height) ), ] def UpperCamelCase (lowercase_: np.ndarray , lowercase_: Optional[str] , lowercase_: Optional[str] ) -> List[Any]: A__ : Tuple = to_pil_image(lowercase_ ) A__ : int = pil_image.size A__ : Dict = pytesseract.image_to_data(lowercase_ , lang=lowercase_ , output_type="""dict""" , config=lowercase_ ) A__ : Dict = data["""text"""], data["""left"""], data["""top"""], data["""width"""], data["""height"""] # filter empty words and corresponding coordinates A__ : List[Any] = [idx for idx, word in enumerate(lowercase_ ) if not word.strip()] A__ : Union[str, Any] = [word for idx, word in enumerate(lowercase_ ) if idx not in irrelevant_indices] A__ : Union[str, Any] = [coord for idx, coord in enumerate(lowercase_ ) if idx not in irrelevant_indices] A__ : Dict = [coord for idx, coord in enumerate(lowercase_ ) if idx not in irrelevant_indices] A__ : Any = [coord for idx, coord in enumerate(lowercase_ ) if idx not in irrelevant_indices] A__ : List[str] = [coord for idx, coord in enumerate(lowercase_ ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format A__ : int = [] for x, y, w, h in zip(lowercase_ , lowercase_ , lowercase_ , lowercase_ ): A__ : Optional[Any] = [x, y, x + w, y + h] actual_boxes.append(lowercase_ ) # finally, normalize the bounding boxes A__ : Union[str, Any] = [] for box in actual_boxes: normalized_boxes.append(normalize_box(lowercase_ , lowercase_ , lowercase_ ) ) assert len(lowercase_ ) == len(lowercase_ ), "Not as many words as there are bounding boxes" return words, normalized_boxes class _a (__magic_name__ ): '''simple docstring''' UpperCAmelCase__: List[Any] = ['''pixel_values'''] def __init__( self , A__ = True , A__ = None , A__ = PILImageResampling.BILINEAR , A__ = True , A__ = 1 / 255 , A__ = True , A__ = None , A__ = None , A__ = True , A__ = None , A__ = "" , **A__ , ): super().__init__(**A__ ) A__ : Union[str, Any] = size if size is not None else {"""height""": 224, """width""": 224} A__ : Tuple = get_size_dict(A__ ) A__ : int = do_resize A__ : Union[str, Any] = size A__ : List[str] = resample A__ : List[str] = do_rescale A__ : Optional[int] = rescale_value A__ : Union[str, Any] = do_normalize A__ : List[Any] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN A__ : Dict = image_std if image_std is not None else IMAGENET_STANDARD_STD A__ : List[str] = apply_ocr A__ : Optional[int] = ocr_lang A__ : int = tesseract_config def __A ( self , A__ , A__ , A__ = PILImageResampling.BILINEAR , A__ = None , **A__ , ): A__ : Dict = get_size_dict(A__ ) if "height" not in size or "width" not in size: raise ValueError(F"""The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}""" ) A__ : Tuple = (size["""height"""], size["""width"""]) return resize(A__ , size=A__ , resample=A__ , data_format=A__ , **A__ ) def __A ( self , A__ , A__ , A__ = None , **A__ , ): return rescale(A__ , scale=A__ , data_format=A__ , **A__ ) def __A ( self , A__ , A__ , A__ , A__ = None , **A__ , ): return normalize(A__ , mean=A__ , std=A__ , data_format=A__ , **A__ ) def __A ( self , A__ , A__ = None , A__ = None , A__=None , A__ = None , A__ = None , A__ = None , A__ = None , A__ = None , A__ = None , A__ = None , A__ = None , A__ = None , A__ = ChannelDimension.FIRST , **A__ , ): A__ : Tuple = do_resize if do_resize is not None else self.do_resize A__ : Any = size if size is not None else self.size A__ : Tuple = get_size_dict(A__ ) A__ : str = resample if resample is not None else self.resample A__ : Union[str, Any] = do_rescale if do_rescale is not None else self.do_rescale A__ : Optional[int] = rescale_factor if rescale_factor is not None else self.rescale_factor A__ : int = do_normalize if do_normalize is not None else self.do_normalize A__ : str = image_mean if image_mean is not None else self.image_mean A__ : List[Any] = image_std if image_std is not None else self.image_std A__ : Tuple = apply_ocr if apply_ocr is not None else self.apply_ocr A__ : List[str] = ocr_lang if ocr_lang is not None else self.ocr_lang A__ : Union[str, Any] = tesseract_config if tesseract_config is not None else self.tesseract_config A__ : Optional[int] = make_list_of_images(A__ ) if not valid_images(A__ ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) if do_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("""If do_normalize is True, image_mean and image_std must be specified.""" ) # All transformations expect numpy arrays. A__ : List[Any] = [to_numpy_array(A__ ) for image in images] # Tesseract OCR to get words + normalized bounding boxes if apply_ocr: requires_backends(self , """pytesseract""" ) A__ : List[Any] = [] A__ : int = [] for image in images: A__ : List[Any] = apply_tesseract(A__ , A__ , A__ ) words_batch.append(A__ ) boxes_batch.append(A__ ) if do_resize: A__ : int = [self.resize(image=A__ , size=A__ , resample=A__ ) for image in images] if do_rescale: A__ : Dict = [self.rescale(image=A__ , scale=A__ ) for image in images] if do_normalize: A__ : List[Any] = [self.normalize(image=A__ , mean=A__ , std=A__ ) for image in images] A__ : str = [to_channel_dimension_format(A__ , A__ ) for image in images] A__ : Optional[int] = BatchFeature(data={"""pixel_values""": images} , tensor_type=A__ ) if apply_ocr: A__ : str = words_batch A__ : Any = boxes_batch return data
705
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DPMSolverMultistepScheduler, TextToVideoSDPipeline, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class _a (__magic_name__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: Any = TextToVideoSDPipeline UpperCAmelCase__: Any = TEXT_TO_IMAGE_PARAMS UpperCAmelCase__: Optional[Any] = TEXT_TO_IMAGE_BATCH_PARAMS # No `output_type`. UpperCAmelCase__: Optional[int] = frozenset( [ '''num_inference_steps''', '''generator''', '''latents''', '''return_dict''', '''callback''', '''callback_steps''', ] ) def __A ( self ): torch.manual_seed(0 ) A__ : Optional[int] = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """DownBlock3D""") , up_block_types=("""UpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""") , cross_attention_dim=32 , attention_head_dim=4 , ) A__ : Optional[int] = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule="""scaled_linear""" , clip_sample=A__ , set_alpha_to_one=A__ , ) torch.manual_seed(0 ) A__ : Union[str, Any] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) A__ : Union[str, Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act="""gelu""" , projection_dim=512 , ) A__ : Union[str, Any] = CLIPTextModel(A__ ) A__ : Tuple = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) A__ : Dict = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, } return components def __A ( self , A__ , A__=0 ): if str(A__ ).startswith("""mps""" ): A__ : Tuple = torch.manual_seed(A__ ) else: A__ : List[str] = torch.Generator(device=A__ ).manual_seed(A__ ) A__ : List[str] = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """pt""", } return inputs def __A ( self ): A__ : List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator A__ : Union[str, Any] = self.get_dummy_components() A__ : Union[str, Any] = TextToVideoSDPipeline(**A__ ) A__ : int = sd_pipe.to(A__ ) sd_pipe.set_progress_bar_config(disable=A__ ) A__ : int = self.get_dummy_inputs(A__ ) A__ : int = """np""" A__ : Any = sd_pipe(**A__ ).frames A__ : Dict = frames[0][-3:, -3:, -1] assert frames[0].shape == (64, 64, 3) A__ : Optional[Any] = np.array([1_5_8.0, 1_6_0.0, 1_5_3.0, 1_2_5.0, 1_0_0.0, 1_2_1.0, 1_1_1.0, 9_3.0, 1_1_3.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __A ( self ): self._test_attention_slicing_forward_pass(test_mean_pixel_difference=A__ , expected_max_diff=3e-3 ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def __A ( self ): self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=A__ , expected_max_diff=1e-2 ) @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def __A ( self ): pass @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def __A ( self ): pass @unittest.skip(reason="""`num_images_per_prompt` argument is not supported for this pipeline.""" ) def __A ( self ): pass def __A ( self ): return super().test_progress_bar() @slow @skip_mps class _a (unittest.TestCase ): '''simple docstring''' def __A ( self ): A__ : Union[str, Any] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy""" ) A__ : Tuple = TextToVideoSDPipeline.from_pretrained("""damo-vilab/text-to-video-ms-1.7b""" ) A__ : Any = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) A__ : int = pipe.to("""cuda""" ) A__ : Optional[Any] = """Spiderman is surfing""" A__ : List[str] = torch.Generator(device="""cpu""" ).manual_seed(0 ) A__ : Optional[Any] = pipe(A__ , generator=A__ , num_inference_steps=25 , output_type="""pt""" ).frames A__ : Dict = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5e-2 def __A ( self ): A__ : List[Any] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy""" ) A__ : Optional[int] = TextToVideoSDPipeline.from_pretrained("""damo-vilab/text-to-video-ms-1.7b""" ) A__ : List[str] = pipe.to("""cuda""" ) A__ : Dict = """Spiderman is surfing""" A__ : Union[str, Any] = torch.Generator(device="""cpu""" ).manual_seed(0 ) A__ : Optional[int] = pipe(A__ , generator=A__ , num_inference_steps=2 , output_type="""pt""" ).frames A__ : Optional[int] = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5e-2
64
0
def UpperCamelCase ( lowercase_: str , lowercase_: str ) -> bool: A__ : Union[str, Any] = len(lowercase_ ) A__ : List[Any] = len(lowercase_ ) A__ : List[Any] = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] A__ : str = True for i in range(lowercase_ ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: A__ : int = True if a[i].islower(): A__ : Dict = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
706
def UpperCamelCase (lowercase_: int ) -> int: if not isinstance(lowercase_ , lowercase_ ): raise TypeError("""Input value must be an 'int' type""" ) A__ : int = 0 while number: position += 1 number >>= 1 return position if __name__ == "__main__": import doctest doctest.testmod()
64
0
from ...configuration_utils import PretrainedConfig from ...utils import logging A_ : int = logging.get_logger(__name__) A_ : Optional[Any] = { 'facebook/vit-mae-base': 'https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json', # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class _a (__magic_name__ ): '''simple docstring''' UpperCAmelCase__: List[Any] = '''vit_mae''' def __init__( self , A__=768 , A__=12 , A__=12 , A__=3072 , A__="gelu" , A__=0.0 , A__=0.0 , A__=0.0_2 , A__=1e-12 , A__=224 , A__=16 , A__=3 , A__=True , A__=16 , A__=512 , A__=8 , A__=2048 , A__=0.7_5 , A__=False , **A__ , ): super().__init__(**A__ ) A__ : Dict = hidden_size A__ : Optional[Any] = num_hidden_layers A__ : List[str] = num_attention_heads A__ : Any = intermediate_size A__ : Union[str, Any] = hidden_act A__ : List[str] = hidden_dropout_prob A__ : Union[str, Any] = attention_probs_dropout_prob A__ : Optional[int] = initializer_range A__ : Optional[Any] = layer_norm_eps A__ : Tuple = image_size A__ : Dict = patch_size A__ : Optional[int] = num_channels A__ : List[str] = qkv_bias A__ : Tuple = decoder_num_attention_heads A__ : Any = decoder_hidden_size A__ : Optional[int] = decoder_num_hidden_layers A__ : Tuple = decoder_intermediate_size A__ : int = mask_ratio A__ : Union[str, Any] = norm_pix_loss
707
from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def UpperCamelCase (lowercase_: np.ndarray , lowercase_: np.ndarray , lowercase_: np.ndarray , lowercase_: int , lowercase_: int ) -> np.ndarray: A__ : Any = cva.getAffineTransform(lowercase_ , lowercase_ ) return cva.warpAffine(lowercase_ , lowercase_ , (rows, cols) ) if __name__ == "__main__": # read original image A_ : List[Any] = cva.imread( str(Path(__file__).resolve().parent.parent / 'image_data' / 'lena.jpg') ) # turn image in gray scale value A_ : List[Any] = cva.cvtColor(image, cva.COLOR_BGR2GRAY) # get image shape A_ , A_ : Optional[Any] = gray_img.shape # set different points to rotate image A_ : str = np.array([[50, 50], [200, 50], [50, 200]], np.floataa) A_ : Dict = np.array([[10, 100], [200, 50], [100, 250]], np.floataa) A_ : Optional[int] = np.array([[50, 50], [150, 50], [120, 200]], np.floataa) A_ : Optional[int] = np.array([[10, 100], [80, 50], [180, 250]], np.floataa) # add all rotated images in a list A_ : Dict = [ 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_ : Union[str, Any] = plt.figure(1) A_ : Union[str, Any] = ['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()
64
0
import tempfile import torch from diffusers import IPNDMScheduler from .test_schedulers import SchedulerCommonTest class _a (__magic_name__ ): '''simple docstring''' UpperCAmelCase__: str = (IPNDMScheduler,) UpperCAmelCase__: Union[str, Any] = (('''num_inference_steps''', 50),) def __A ( self , **A__ ): A__ : str = {"""num_train_timesteps""": 1000} config.update(**A__ ) return config def __A ( self , A__=0 , **A__ ): A__ : Optional[Any] = dict(self.forward_default_kwargs ) A__ : str = kwargs.pop("""num_inference_steps""" , A__ ) A__ : Optional[int] = self.dummy_sample A__ : List[str] = 0.1 * sample A__ : Tuple = [residual + 0.2, residual + 0.1_5, residual + 0.1, residual + 0.0_5] for scheduler_class in self.scheduler_classes: A__ : Union[str, Any] = self.get_scheduler_config(**A__ ) A__ : Optional[Any] = scheduler_class(**A__ ) scheduler.set_timesteps(A__ ) # copy over dummy past residuals A__ : Dict = dummy_past_residuals[:] if time_step is None: A__ : Dict = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(A__ ) A__ : Dict = scheduler_class.from_pretrained(A__ ) new_scheduler.set_timesteps(A__ ) # copy over dummy past residuals A__ : List[Any] = dummy_past_residuals[:] A__ : Dict = scheduler.step(A__ , A__ , A__ , **A__ ).prev_sample A__ : int = new_scheduler.step(A__ , A__ , A__ , **A__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" A__ : Optional[Any] = scheduler.step(A__ , A__ , A__ , **A__ ).prev_sample A__ : Tuple = new_scheduler.step(A__ , A__ , A__ , **A__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def __A ( self ): pass def __A ( self , A__=0 , **A__ ): A__ : Union[str, Any] = dict(self.forward_default_kwargs ) A__ : int = kwargs.pop("""num_inference_steps""" , A__ ) A__ : Optional[int] = self.dummy_sample A__ : str = 0.1 * sample A__ : Optional[Any] = [residual + 0.2, residual + 0.1_5, residual + 0.1, residual + 0.0_5] for scheduler_class in self.scheduler_classes: A__ : str = self.get_scheduler_config() A__ : List[Any] = scheduler_class(**A__ ) scheduler.set_timesteps(A__ ) # copy over dummy past residuals (must be after setting timesteps) A__ : Union[str, Any] = dummy_past_residuals[:] if time_step is None: A__ : Any = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(A__ ) A__ : List[str] = scheduler_class.from_pretrained(A__ ) # copy over dummy past residuals new_scheduler.set_timesteps(A__ ) # copy over dummy past residual (must be after setting timesteps) A__ : Any = dummy_past_residuals[:] A__ : Dict = scheduler.step(A__ , A__ , A__ , **A__ ).prev_sample A__ : List[str] = new_scheduler.step(A__ , A__ , A__ , **A__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" A__ : Dict = scheduler.step(A__ , A__ , A__ , **A__ ).prev_sample A__ : Union[str, Any] = new_scheduler.step(A__ , A__ , A__ , **A__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def __A ( self , **A__ ): A__ : Any = self.scheduler_classes[0] A__ : List[Any] = self.get_scheduler_config(**A__ ) A__ : Optional[Any] = scheduler_class(**A__ ) A__ : Union[str, Any] = 10 A__ : int = self.dummy_model() A__ : Tuple = self.dummy_sample_deter scheduler.set_timesteps(A__ ) for i, t in enumerate(scheduler.timesteps ): A__ : Union[str, Any] = model(A__ , A__ ) A__ : Any = scheduler.step(A__ , A__ , A__ ).prev_sample for i, t in enumerate(scheduler.timesteps ): A__ : Tuple = model(A__ , A__ ) A__ : Optional[int] = scheduler.step(A__ , A__ , A__ ).prev_sample return sample def __A ( self ): A__ : Optional[Any] = dict(self.forward_default_kwargs ) A__ : Any = kwargs.pop("""num_inference_steps""" , A__ ) for scheduler_class in self.scheduler_classes: A__ : Dict = self.get_scheduler_config() A__ : Union[str, Any] = scheduler_class(**A__ ) A__ : str = self.dummy_sample A__ : int = 0.1 * sample if num_inference_steps is not None and hasattr(A__ , """set_timesteps""" ): scheduler.set_timesteps(A__ ) elif num_inference_steps is not None and not hasattr(A__ , """set_timesteps""" ): A__ : int = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) A__ : int = [residual + 0.2, residual + 0.1_5, residual + 0.1, residual + 0.0_5] A__ : int = dummy_past_residuals[:] A__ : str = scheduler.timesteps[5] A__ : List[str] = scheduler.timesteps[6] A__ : List[str] = scheduler.step(A__ , A__ , A__ , **A__ ).prev_sample A__ : Union[str, Any] = scheduler.step(A__ , A__ , A__ , **A__ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) A__ : str = scheduler.step(A__ , A__ , A__ , **A__ ).prev_sample A__ : Dict = scheduler.step(A__ , A__ , A__ , **A__ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def __A ( self ): for timesteps in [100, 1000]: self.check_over_configs(num_train_timesteps=A__ , time_step=A__ ) def __A ( self ): for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 100] ): self.check_over_forward(num_inference_steps=A__ , time_step=A__ ) def __A ( self ): A__ : Any = self.full_loop() A__ : int = torch.mean(torch.abs(A__ ) ) assert abs(result_mean.item() - 254_0529 ) < 10
708
import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class _a (unittest.TestCase ): '''simple docstring''' def __A ( self , A__ ): for model_result in results.values(): for batch_size, sequence_length in zip(model_result["""bs"""] , model_result["""ss"""] ): A__ : str = model_result["""result"""][batch_size][sequence_length] self.assertIsNotNone(A__ ) def __A ( self ): A__ : Dict = """sshleifer/tiny-gpt2""" A__ : Tuple = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : int = PyTorchBenchmark(A__ ) A__ : List[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ): A__ : Dict = """sgugger/tiny-distilbert-classification""" A__ : Dict = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , only_pretrain_model=A__ , ) A__ : str = PyTorchBenchmark(A__ ) A__ : List[str] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ): A__ : Any = """sshleifer/tiny-gpt2""" A__ : List[Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , torchscript=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : Tuple = PyTorchBenchmark(A__ ) A__ : str = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == """cpu""" , """Cant do half precision""" ) def __A ( self ): A__ : Optional[Any] = """sshleifer/tiny-gpt2""" A__ : Optional[Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , fpaa=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : str = PyTorchBenchmark(A__ ) A__ : Any = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ): A__ : Optional[Any] = """sshleifer/tiny-gpt2""" A__ : Tuple = AutoConfig.from_pretrained(A__ ) # set architectures equal to `None` A__ : List[Any] = None A__ : str = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : List[str] = PyTorchBenchmark(A__ , configs=[config] ) A__ : Any = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ): A__ : Optional[int] = """sshleifer/tiny-gpt2""" A__ : Optional[int] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : Any = PyTorchBenchmark(A__ ) A__ : Dict = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == """cpu""" , """Can't do half precision""" ) def __A ( self ): A__ : Optional[int] = """sshleifer/tiny-gpt2""" A__ : List[str] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , fpaa=A__ , multi_process=A__ , ) A__ : Dict = PyTorchBenchmark(A__ ) A__ : Optional[int] = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __A ( self ): A__ : int = """sshleifer/tiny-gpt2""" A__ : Optional[int] = AutoConfig.from_pretrained(A__ ) A__ : str = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : int = PyTorchBenchmark(A__ , configs=[config] ) A__ : Tuple = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ): A__ : List[str] = """sshleifer/tinier_bart""" A__ : List[str] = AutoConfig.from_pretrained(A__ ) A__ : List[str] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : Union[str, Any] = PyTorchBenchmark(A__ , configs=[config] ) A__ : str = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ): A__ : Optional[int] = """sshleifer/tiny-gpt2""" A__ : Union[str, Any] = AutoConfig.from_pretrained(A__ ) A__ : Tuple = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : int = PyTorchBenchmark(A__ , configs=[config] ) A__ : Tuple = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __A ( self ): A__ : Dict = """sshleifer/tinier_bart""" A__ : int = AutoConfig.from_pretrained(A__ ) A__ : Union[str, Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A__ , ) A__ : List[Any] = PyTorchBenchmark(A__ , configs=[config] ) A__ : Optional[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __A ( self ): A__ : int = """sshleifer/tiny-gpt2""" with tempfile.TemporaryDirectory() as tmp_dir: A__ : Dict = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , save_to_csv=A__ , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(A__ , """inf_time.csv""" ) , train_memory_csv_file=os.path.join(A__ , """train_mem.csv""" ) , inference_memory_csv_file=os.path.join(A__ , """inf_mem.csv""" ) , train_time_csv_file=os.path.join(A__ , """train_time.csv""" ) , env_info_csv_file=os.path.join(A__ , """env.csv""" ) , multi_process=A__ , ) A__ : Optional[Any] = PyTorchBenchmark(A__ ) benchmark.run() self.assertTrue(Path(os.path.join(A__ , """inf_time.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(A__ , """train_time.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(A__ , """inf_mem.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(A__ , """train_mem.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(A__ , """env.csv""" ) ).exists() ) def __A ( self ): A__ : Optional[int] = """sshleifer/tiny-gpt2""" def _check_summary_is_not_empty(A__ ): self.assertTrue(hasattr(A__ , """sequential""" ) ) self.assertTrue(hasattr(A__ , """cumulative""" ) ) self.assertTrue(hasattr(A__ , """current""" ) ) self.assertTrue(hasattr(A__ , """total""" ) ) with tempfile.TemporaryDirectory() as tmp_dir: A__ : Dict = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A__ , inference=A__ , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(A__ , """log.txt""" ) , log_print=A__ , trace_memory_line_by_line=A__ , multi_process=A__ , ) A__ : Dict = PyTorchBenchmark(A__ ) A__ : str = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(A__ , """log.txt""" ) ).exists() )
64
0
# coding=utf-8 # Copyright 2023 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # this script dumps information about the environment import os import platform import sys A_ : int = '3' print('Python version:', sys.version) print('OS platform:', platform.platform()) print('OS architecture:', platform.machine()) try: import torch print('Torch version:', torch.__version__) print('Cuda available:', torch.cuda.is_available()) print('Cuda version:', torch.version.cuda) print('CuDNN version:', torch.backends.cudnn.version()) print('Number of GPUs available:', torch.cuda.device_count()) except ImportError: print('Torch version:', None) try: import transformers print('transformers version:', transformers.__version__) except ImportError: print('transformers version:', None)
709
# tests directory-specific settings - this file is run automatically # by pytest before any tests are run import doctest import sys import warnings from os.path import abspath, dirname, join import _pytest from transformers.testing_utils import HfDoctestModule, HfDocTestParser # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. A_ : Optional[int] = abspath(join(dirname(__file__), 'src')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='ignore', category=FutureWarning) def UpperCamelCase (lowercase_: List[str] ) -> Any: config.addinivalue_line( """markers""" , """is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested""" ) config.addinivalue_line( """markers""" , """is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested""" ) config.addinivalue_line("""markers""" , """is_pipeline_test: mark test to run only when pipelines are tested""" ) config.addinivalue_line("""markers""" , """is_staging_test: mark test to run only in the staging environment""" ) config.addinivalue_line("""markers""" , """accelerate_tests: mark test that require accelerate""" ) config.addinivalue_line("""markers""" , """tool_tests: mark the tool tests that are run on their specific schedule""" ) def UpperCamelCase (lowercase_: Optional[int] ) -> Optional[Any]: from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(lowercase_ ) def UpperCamelCase (lowercase_: List[str] ) -> Optional[Any]: from transformers.testing_utils import pytest_terminal_summary_main A__ : List[Any] = terminalreporter.config.getoption("""--make-reports""" ) if make_reports: pytest_terminal_summary_main(lowercase_ , id=lowercase_ ) def UpperCamelCase (lowercase_: Union[str, Any] , lowercase_: int ) -> List[str]: # If no tests are collected, pytest exists with code 5, which makes the CI fail. if exitstatus == 5: A__ : Tuple = 0 # Doctest custom flag to ignore output. A_ : Tuple = doctest.register_optionflag('IGNORE_RESULT') A_ : Dict = doctest.OutputChecker class _a (__magic_name__ ): '''simple docstring''' def __A ( self , A__ , A__ , A__ ): if IGNORE_RESULT & optionflags: return True return OutputChecker.check_output(self , A__ , A__ , A__ ) A_ : str = CustomOutputChecker A_ : Dict = HfDoctestModule A_ : Optional[int] = HfDocTestParser
64
0
from datetime import datetime import matplotlib.pyplot as plt import torch def UpperCamelCase (lowercase_: Optional[int] ) -> List[str]: for param in module.parameters(): A__ : Union[str, Any] = False def UpperCamelCase () -> List[str]: A__ : Tuple = """cuda""" if torch.cuda.is_available() else """cpu""" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): A__ : Any = """mps""" if device == "mps": print( """WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch""" """ errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues""" """ with generations.""" ) return device def UpperCamelCase (lowercase_: Any ) -> List[str]: A__ : Tuple = plt.imshow(lowercase_ ) fig.axes.get_xaxis().set_visible(lowercase_ ) fig.axes.get_yaxis().set_visible(lowercase_ ) plt.show() def UpperCamelCase () -> Optional[Any]: A__ : Optional[int] = datetime.now() A__ : Union[str, Any] = current_time.strftime("""%H:%M:%S""" ) return timestamp
710
from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, 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, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class _a : '''simple docstring''' UpperCAmelCase__: List[Any] = PegasusConfig UpperCAmelCase__: Optional[int] = {} UpperCAmelCase__: List[str] = '''gelu''' def __init__( self , A__ , A__=13 , A__=7 , A__=True , A__=False , A__=99 , A__=32 , A__=2 , A__=4 , A__=37 , A__=0.1 , A__=0.1 , A__=40 , A__=2 , A__=1 , A__=0 , ): A__ : Dict = parent A__ : Dict = batch_size A__ : Any = seq_length A__ : Optional[Any] = is_training A__ : int = use_labels A__ : Any = vocab_size A__ : Union[str, Any] = hidden_size A__ : Tuple = num_hidden_layers A__ : Tuple = num_attention_heads A__ : List[Any] = intermediate_size A__ : Union[str, Any] = hidden_dropout_prob A__ : Optional[Any] = attention_probs_dropout_prob A__ : List[Any] = max_position_embeddings A__ : Any = eos_token_id A__ : List[Any] = pad_token_id A__ : List[Any] = bos_token_id def __A ( self ): A__ : str = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) A__ : Dict = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) A__ : List[Any] = tf.concat([input_ids, eos_tensor] , axis=1 ) A__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ : Tuple = 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 , ) A__ : str = prepare_pegasus_inputs_dict(A__ , A__ , A__ ) return config, inputs_dict def __A ( self , A__ , A__ ): A__ : int = TFPegasusModel(config=A__ ).get_decoder() A__ : List[Any] = inputs_dict["""input_ids"""] A__ : Any = input_ids[:1, :] A__ : Optional[Any] = inputs_dict["""attention_mask"""][:1, :] A__ : Optional[int] = inputs_dict["""head_mask"""] A__ : Any = 1 # first forward pass A__ : Tuple = model(A__ , attention_mask=A__ , head_mask=A__ , use_cache=A__ ) A__ , A__ : Dict = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids A__ : Tuple = ids_tensor((self.batch_size, 3) , config.vocab_size ) A__ : Optional[Any] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and A__ : List[Any] = tf.concat([input_ids, next_tokens] , axis=-1 ) A__ : Tuple = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) A__ : Optional[Any] = model(A__ , attention_mask=A__ )[0] A__ : Any = model(A__ , attention_mask=A__ , past_key_values=A__ )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice A__ : int = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) A__ : Any = output_from_no_past[:, -3:, random_slice_idx] A__ : Tuple = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(A__ , A__ , rtol=1e-3 ) def UpperCamelCase (lowercase_: Union[str, Any] , lowercase_: Dict , lowercase_: List[Any] , lowercase_: Dict=None , lowercase_: int=None , lowercase_: List[Any]=None , lowercase_: List[Any]=None , lowercase_: str=None , ) -> int: if attention_mask is None: A__ : List[str] = tf.cast(tf.math.not_equal(lowercase_ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: A__ : Dict = 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: A__ : Any = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: A__ : Tuple = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: A__ : List[str] = 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 (__magic_name__ , __magic_name__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: List[Any] = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () UpperCAmelCase__: Tuple = (TFPegasusForConditionalGeneration,) if is_tf_available() else () UpperCAmelCase__: Tuple = ( { '''conversational''': TFPegasusForConditionalGeneration, '''feature-extraction''': TFPegasusModel, '''summarization''': TFPegasusForConditionalGeneration, '''text2text-generation''': TFPegasusForConditionalGeneration, '''translation''': TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) UpperCAmelCase__: int = True UpperCAmelCase__: Union[str, Any] = False UpperCAmelCase__: List[str] = False def __A ( self ): A__ : Optional[Any] = TFPegasusModelTester(self ) A__ : Tuple = ConfigTester(self , config_class=A__ ) def __A ( self ): self.config_tester.run_common_tests() def __A ( self ): A__ : int = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*A__ ) @require_sentencepiece @require_tokenizers @require_tf class _a (unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: Optional[int] = [ ''' 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!" ''', ] UpperCAmelCase__: Any = [ '''California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to''' ''' reduce the risk of wildfires.''', '''N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.''', ] # differs slightly from pytorch, likely due to numerical differences in linear layers UpperCAmelCase__: List[str] = '''google/pegasus-xsum''' @cached_property def __A ( self ): return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def __A ( self ): A__ : int = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def __A ( self , **A__ ): A__ : str = self.translate_src_text(**A__ ) assert self.expected_text == generated_words def __A ( self , **A__ ): A__ : List[str] = self.tokenizer(self.src_text , **A__ , padding=A__ , return_tensors="""tf""" ) A__ : Optional[int] = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=A__ , ) A__ : Dict = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=A__ ) return generated_words @slow def __A ( self ): self._assert_generated_batch_equal_expected()
64
0