code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) UpperCamelCase = {'configuration_deit': ['DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DeiTConfig', 'DeiTOnnxConfig']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['DeiTFeatureExtractor'] UpperCamelCase = ['DeiTImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ 'DEIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'DeiTForImageClassification', 'DeiTForImageClassificationWithTeacher', 'DeiTForMaskedImageModeling', 'DeiTModel', 'DeiTPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ 'TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFDeiTForImageClassification', 'TFDeiTForImageClassificationWithTeacher', 'TFDeiTForMaskedImageModeling', 'TFDeiTModel', 'TFDeiTPreTrainedModel', ] if TYPE_CHECKING: from .configuration_deit import DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, DeiTConfig, DeiTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_deit import DeiTFeatureExtractor from .image_processing_deit import DeiTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deit import ( DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, DeiTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deit import ( TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, TFDeiTPreTrainedModel, ) else: import sys UpperCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
61
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { 'sayakpaul/vit-msn-base': 'https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json', # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "vit_msn" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple=768 , SCREAMING_SNAKE_CASE__ : Optional[Any]=12 , SCREAMING_SNAKE_CASE__ : List[str]=12 , SCREAMING_SNAKE_CASE__ : Dict=3_072 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.0 , SCREAMING_SNAKE_CASE__ : int=0.0 , SCREAMING_SNAKE_CASE__ : List[str]=0.02 , SCREAMING_SNAKE_CASE__ : List[str]=1e-0_6 , SCREAMING_SNAKE_CASE__ : Dict=224 , SCREAMING_SNAKE_CASE__ : Optional[int]=16 , SCREAMING_SNAKE_CASE__ : Dict=3 , SCREAMING_SNAKE_CASE__ : Dict=True , **SCREAMING_SNAKE_CASE__ : Tuple , ) -> int: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = initializer_range lowerCAmelCase__ = layer_norm_eps lowerCAmelCase__ = image_size lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = qkv_bias
61
1
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _A ( ): """simple docstring""" lowerCAmelCase__ = ArgumentParser( description=( "PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes" ) ) # Optional arguments for the launch helper parser.add_argument("--num_cores" , type=lowerCAmelCase_ , default=1 , help="Number of TPU cores to use (1 or 8)." ) # positional parser.add_argument( "training_script" , type=lowerCAmelCase_ , help=( "The full path to the single TPU training " "program/script to be launched in parallel, " "followed by all the arguments for the " "training script" ) , ) # rest from the training program parser.add_argument("training_script_args" , nargs=lowerCAmelCase_ ) return parser.parse_args() def _A ( ): """simple docstring""" lowerCAmelCase__ = parse_args() # Import training_script as a module. lowerCAmelCase__ = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) lowerCAmelCase__ = script_fpath.stem lowerCAmelCase__ = importlib.import_module(lowerCAmelCase_ ) # Patch sys.argv lowerCAmelCase__ = [args.training_script] + args.training_script_args + ["--tpu_num_cores", str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
61
import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def __init__( self : List[Any] , *SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> None: warnings.warn( "The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use FlavaImageProcessor instead." , SCREAMING_SNAKE_CASE__ , ) super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
61
1
from __future__ import annotations def _A ( lowerCAmelCase_ : int ): """simple docstring""" lowerCAmelCase__ = 2 lowerCAmelCase__ = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(lowerCAmelCase_ ) if n > 1: factors.append(lowerCAmelCase_ ) return factors if __name__ == "__main__": import doctest doctest.testmod()
61
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import ( BaseOutput, OptionalDependencyNotAvailable, is_flax_available, is_k_diffusion_available, is_k_diffusion_version, is_onnx_available, is_torch_available, is_transformers_available, is_transformers_version, ) @dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_cycle_diffusion import CycleDiffusionPipeline from .pipeline_stable_diffusion import StableDiffusionPipeline from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from .pipeline_stable_unclip import StableUnCLIPPipeline from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline from .safety_checker import StableDiffusionSafetyChecker from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.25.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline else: from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.26.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionPixaPixZeroPipeline, ) else: from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline try: if not ( is_torch_available() and is_transformers_available() and is_k_diffusion_available() and is_k_diffusion_version('>=', '0.0.12') ): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline try: if not (is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_onnx_objects import * # noqa F403 else: from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline if is_transformers_available() and is_flax_available(): import flax @flax.struct.dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline from .safety_checker_flax import FlaxStableDiffusionSafetyChecker
61
1
def _A ( lowerCAmelCase_ : int , lowerCAmelCase_ : int ): """simple docstring""" if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive" ) lowerCAmelCase__ = str(bin(lowerCAmelCase_ ) )[2:] # remove the leading "0b" lowerCAmelCase__ = str(bin(lowerCAmelCase_ ) )[2:] # remove the leading "0b" lowerCAmelCase__ = max(len(lowerCAmelCase_ ) , len(lowerCAmelCase_ ) ) return "0b" + "".join( str(int(char_a == "1" and char_b == "1" ) ) for char_a, char_b in zip(a_binary.zfill(lowerCAmelCase_ ) , b_binary.zfill(lowerCAmelCase_ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
61
def _A ( lowerCAmelCase_ : int ): """simple docstring""" if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("'float' object cannot be interpreted as an integer" ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("'str' object cannot be interpreted as an integer" ) if num == 0: return "0b0" lowerCAmelCase__ = False if num < 0: lowerCAmelCase__ = True lowerCAmelCase__ = -num lowerCAmelCase__ = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(lowerCAmelCase_ ) for e in binary ) return "0b" + "".join(str(lowerCAmelCase_ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
61
1
# tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. UpperCamelCase = abspath(join(dirname(dirname(__file__)), 'src')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='ignore', category=FutureWarning) def _A ( lowerCAmelCase_ : Optional[int] ): """simple docstring""" from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(lowerCAmelCase_ ) def _A ( lowerCAmelCase_ : List[Any] ): """simple docstring""" from diffusers.utils.testing_utils import pytest_terminal_summary_main lowerCAmelCase__ = terminalreporter.config.getoption("--make-reports" ) if make_reports: pytest_terminal_summary_main(lowerCAmelCase_ , id=lowerCAmelCase_ )
61
from __future__ import annotations UpperCamelCase = '#' class __lowerCamelCase : """simple docstring""" def __init__( self : Dict ) -> None: lowerCAmelCase__ = {} def a ( self : Any , SCREAMING_SNAKE_CASE__ : str ) -> None: lowerCAmelCase__ = self._trie for char in text: if char not in trie: lowerCAmelCase__ = {} lowerCAmelCase__ = trie[char] lowerCAmelCase__ = True def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : str ) -> tuple | list: lowerCAmelCase__ = self._trie for char in prefix: if char in trie: lowerCAmelCase__ = trie[char] else: return [] return self._elements(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : dict ) -> tuple: lowerCAmelCase__ = [] for c, v in d.items(): lowerCAmelCase__ = [" "] if c == END else [(c + s) for s in self._elements(SCREAMING_SNAKE_CASE__ )] result.extend(SCREAMING_SNAKE_CASE__ ) return tuple(SCREAMING_SNAKE_CASE__ ) UpperCamelCase = Trie() UpperCamelCase = ('depart', 'detergent', 'daring', 'dog', 'deer', 'deal') for word in words: trie.insert_word(word) def _A ( lowerCAmelCase_ : str ): """simple docstring""" lowerCAmelCase__ = trie.find_word(lowerCAmelCase_ ) return tuple(string + word for word in suffixes ) def _A ( ): """simple docstring""" print(autocomplete_using_trie("de" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
61
1
from __future__ import annotations import math import random from typing import Any class __lowerCamelCase : """simple docstring""" def __init__( self : Dict ) -> None: lowerCAmelCase__ = [] lowerCAmelCase__ = 0 lowerCAmelCase__ = 0 def a ( self : List[str] ) -> bool: return self.head == self.tail def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any ) -> None: self.data.append(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.tail + 1 def a ( self : str ) -> Any: lowerCAmelCase__ = self.data[self.head] lowerCAmelCase__ = self.head + 1 return ret def a ( self : Optional[int] ) -> int: return self.tail - self.head def a ( self : Any ) -> None: print(self.data ) print("**************" ) print(self.data[self.head : self.tail] ) class __lowerCamelCase : """simple docstring""" def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Any ) -> None: lowerCAmelCase__ = data lowerCAmelCase__ = None lowerCAmelCase__ = None lowerCAmelCase__ = 1 def a ( self : Dict ) -> Any: return self.data def a ( self : Tuple ) -> MyNode | None: return self.left def a ( self : Dict ) -> MyNode | None: return self.right def a ( self : Any ) -> int: return self.height def a ( self : int , SCREAMING_SNAKE_CASE__ : Any ) -> None: lowerCAmelCase__ = data def a ( self : int , SCREAMING_SNAKE_CASE__ : MyNode | None ) -> None: lowerCAmelCase__ = node def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : MyNode | None ) -> None: lowerCAmelCase__ = node def a ( self : int , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = height def _A ( lowerCAmelCase_ : MyNode | None ): """simple docstring""" if node is None: return 0 return node.get_height() def _A ( lowerCAmelCase_ : int , lowerCAmelCase_ : int ): """simple docstring""" if a > b: return a return b def _A ( lowerCAmelCase_ : MyNode ): """simple docstring""" print("left rotation node:" , node.get_data() ) lowerCAmelCase__ = node.get_left() assert ret is not None node.set_left(ret.get_right() ) ret.set_right(lowerCAmelCase_ ) lowerCAmelCase__ = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowerCAmelCase_ ) lowerCAmelCase__ = my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(lowerCAmelCase_ ) return ret def _A ( lowerCAmelCase_ : MyNode ): """simple docstring""" print("right rotation node:" , node.get_data() ) lowerCAmelCase__ = node.get_right() assert ret is not None node.set_right(ret.get_left() ) ret.set_left(lowerCAmelCase_ ) lowerCAmelCase__ = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowerCAmelCase_ ) lowerCAmelCase__ = my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(lowerCAmelCase_ ) return ret def _A ( lowerCAmelCase_ : MyNode ): """simple docstring""" lowerCAmelCase__ = node.get_left() assert left_child is not None node.set_left(left_rotation(lowerCAmelCase_ ) ) return right_rotation(lowerCAmelCase_ ) def _A ( lowerCAmelCase_ : MyNode ): """simple docstring""" lowerCAmelCase__ = node.get_right() assert right_child is not None node.set_right(right_rotation(lowerCAmelCase_ ) ) return left_rotation(lowerCAmelCase_ ) def _A ( lowerCAmelCase_ : MyNode | None , lowerCAmelCase_ : Any ): """simple docstring""" if node is None: return MyNode(lowerCAmelCase_ ) if data < node.get_data(): node.set_left(insert_node(node.get_left() , lowerCAmelCase_ ) ) if ( get_height(node.get_left() ) - get_height(node.get_right() ) == 2 ): # an unbalance detected lowerCAmelCase__ = 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 lowerCAmelCase__ = right_rotation(lowerCAmelCase_ ) else: lowerCAmelCase__ = lr_rotation(lowerCAmelCase_ ) else: node.set_right(insert_node(node.get_right() , lowerCAmelCase_ ) ) if get_height(node.get_right() ) - get_height(node.get_left() ) == 2: lowerCAmelCase__ = node.get_right() assert right_child is not None if data < right_child.get_data(): lowerCAmelCase__ = rl_rotation(lowerCAmelCase_ ) else: lowerCAmelCase__ = left_rotation(lowerCAmelCase_ ) lowerCAmelCase__ = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowerCAmelCase_ ) return node def _A ( lowerCAmelCase_ : MyNode ): """simple docstring""" while True: lowerCAmelCase__ = root.get_right() if right_child is None: break lowerCAmelCase__ = right_child return root.get_data() def _A ( lowerCAmelCase_ : MyNode ): """simple docstring""" while True: lowerCAmelCase__ = root.get_left() if left_child is None: break lowerCAmelCase__ = left_child return root.get_data() def _A ( lowerCAmelCase_ : MyNode , lowerCAmelCase_ : Any ): """simple docstring""" lowerCAmelCase__ = root.get_left() lowerCAmelCase__ = root.get_right() if root.get_data() == data: if left_child is not None and right_child is not None: lowerCAmelCase__ = get_left_most(lowerCAmelCase_ ) root.set_data(lowerCAmelCase_ ) root.set_right(del_node(lowerCAmelCase_ , lowerCAmelCase_ ) ) elif left_child is not None: lowerCAmelCase__ = left_child elif right_child is not None: lowerCAmelCase__ = 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(lowerCAmelCase_ , lowerCAmelCase_ ) ) else: # root.get_data() < data if right_child is None: return root else: root.set_right(del_node(lowerCAmelCase_ , lowerCAmelCase_ ) ) if get_height(lowerCAmelCase_ ) - get_height(lowerCAmelCase_ ) == 2: assert right_child is not None if get_height(right_child.get_right() ) > get_height(right_child.get_left() ): lowerCAmelCase__ = left_rotation(lowerCAmelCase_ ) else: lowerCAmelCase__ = rl_rotation(lowerCAmelCase_ ) elif get_height(lowerCAmelCase_ ) - get_height(lowerCAmelCase_ ) == -2: assert left_child is not None if get_height(left_child.get_left() ) > get_height(left_child.get_right() ): lowerCAmelCase__ = right_rotation(lowerCAmelCase_ ) else: lowerCAmelCase__ = lr_rotation(lowerCAmelCase_ ) lowerCAmelCase__ = my_max(get_height(root.get_right() ) , get_height(root.get_left() ) ) + 1 root.set_height(lowerCAmelCase_ ) return root class __lowerCamelCase : """simple docstring""" def __init__( self : Union[str, Any] ) -> None: lowerCAmelCase__ = None def a ( self : Optional[int] ) -> int: return get_height(self.root ) def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : Any ) -> None: print("insert:" + str(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = insert_node(self.root , SCREAMING_SNAKE_CASE__ ) def a ( self : str , SCREAMING_SNAKE_CASE__ : Any ) -> None: print("delete:" + str(SCREAMING_SNAKE_CASE__ ) ) if self.root is None: print("Tree is empty!" ) return lowerCAmelCase__ = del_node(self.root , SCREAMING_SNAKE_CASE__ ) def __str__( self : List[Any] , ) -> str: # a level traversale, gives a more intuitive look on the tree lowerCAmelCase__ = "" lowerCAmelCase__ = MyQueue() q.push(self.root ) lowerCAmelCase__ = self.get_height() if layer == 0: return output lowerCAmelCase__ = 0 while not q.is_empty(): lowerCAmelCase__ = q.pop() lowerCAmelCase__ = " " * int(math.pow(2 , layer - 1 ) ) output += space if node is None: output += "*" q.push(SCREAMING_SNAKE_CASE__ ) q.push(SCREAMING_SNAKE_CASE__ ) else: output += str(node.get_data() ) q.push(node.get_left() ) q.push(node.get_right() ) output += space lowerCAmelCase__ = cnt + 1 for i in range(100 ): if cnt == math.pow(2 , SCREAMING_SNAKE_CASE__ ) - 1: lowerCAmelCase__ = layer - 1 if layer == 0: output += "\n*************************************" return output output += "\n" break output += "\n*************************************" return output def _A ( ): """simple docstring""" import doctest doctest.testmod() if __name__ == "__main__": _test() UpperCamelCase = AVLtree() UpperCamelCase = 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))
61
import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, TimesformerForVideoClassification, TimesformerModel, ) from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class __lowerCamelCase : """simple docstring""" def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple=13 , SCREAMING_SNAKE_CASE__ : Optional[Any]=10 , SCREAMING_SNAKE_CASE__ : Optional[int]=3 , SCREAMING_SNAKE_CASE__ : List[str]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=2 , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : Optional[int]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : List[Any]=37 , SCREAMING_SNAKE_CASE__ : int="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Any=10 , SCREAMING_SNAKE_CASE__ : int=0.02 , SCREAMING_SNAKE_CASE__ : Tuple="divided_space_time" , SCREAMING_SNAKE_CASE__ : Optional[int]=None , ) -> List[str]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = image_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_frames lowerCAmelCase__ = is_training lowerCAmelCase__ = use_labels lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = attention_type lowerCAmelCase__ = initializer_range lowerCAmelCase__ = scope lowerCAmelCase__ = num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token lowerCAmelCase__ = (image_size // patch_size) ** 2 lowerCAmelCase__ = (num_frames) * self.num_patches_per_frame + 1 def a ( self : int ) -> Tuple: lowerCAmelCase__ = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase__ = None if self.use_labels: lowerCAmelCase__ = ids_tensor([self.batch_size] , self.num_labels ) lowerCAmelCase__ = self.get_config() return config, pixel_values, labels def a ( self : List[Any] ) -> Any: lowerCAmelCase__ = TimesformerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , initializer_range=self.initializer_range , attention_type=self.attention_type , ) lowerCAmelCase__ = self.num_labels return config def a ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: lowerCAmelCase__ = TimesformerModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple ) -> Tuple: lowerCAmelCase__ = TimesformerForVideoClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) # verify the logits shape lowerCAmelCase__ = torch.Size((self.batch_size, self.num_labels) ) self.parent.assertEqual(result.logits.shape , SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> Dict: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else () snake_case__ = ( {"feature-extraction": TimesformerModel, "video-classification": TimesformerForVideoClassification} if is_torch_available() else {} ) snake_case__ = False snake_case__ = False snake_case__ = False snake_case__ = False def a ( self : List[str] ) -> List[Any]: lowerCAmelCase__ = TimesformerModelTester(self ) lowerCAmelCase__ = ConfigTester( self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ , hidden_size=37 ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple=False ) -> str: lowerCAmelCase__ = copy.deepcopy(SCREAMING_SNAKE_CASE__ ) if return_labels: if model_class in get_values(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) return inputs_dict def a ( self : Optional[Any] ) -> List[str]: self.config_tester.run_common_tests() @unittest.skip(reason="TimeSformer does not use inputs_embeds" ) def a ( self : Union[str, Any] ) -> Tuple: pass def a ( self : Dict ) -> List[str]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowerCAmelCase__ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__ , nn.Linear ) ) def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase__ = [*signature.parameters.keys()] lowerCAmelCase__ = ["pixel_values"] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] ) -> Tuple: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*SCREAMING_SNAKE_CASE__ ) @slow def a ( self : str ) -> Tuple: for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase__ = TimesformerModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Dict: if not self.has_attentions: pass else: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ = True for model_class in self.all_model_classes: lowerCAmelCase__ = self.model_tester.seq_length lowerCAmelCase__ = self.model_tester.num_frames lowerCAmelCase__ = True lowerCAmelCase__ = False lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) lowerCAmelCase__ = len(SCREAMING_SNAKE_CASE__ ) # Check attention is always last and order is fine lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(out_len + 1 , len(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) def a ( self : List[str] ) -> Any: def check_hidden_states_output(SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] ): lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.hidden_states lowerCAmelCase__ = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _A ( ): """simple docstring""" lowerCAmelCase__ = hf_hub_download( repo_id="hf-internal-testing/spaghetti-video" , filename="eating_spaghetti.npy" , repo_type="dataset" ) lowerCAmelCase__ = np.load(lowerCAmelCase_ ) return list(lowerCAmelCase_ ) @require_torch @require_vision class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @cached_property def a ( self : Optional[Any] ) -> Union[str, Any]: # logits were tested with a different mean and std, so we use the same here return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) if is_vision_available() else None ) @slow def a ( self : Optional[Any] ) -> str: lowerCAmelCase__ = TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400" ).to( SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.default_image_processor lowerCAmelCase__ = prepare_video() lowerCAmelCase__ = image_processor(video[:8] , return_tensors="pt" ).to(SCREAMING_SNAKE_CASE__ ) # forward pass with torch.no_grad(): lowerCAmelCase__ = model(**SCREAMING_SNAKE_CASE__ ) # verify the logits lowerCAmelCase__ = torch.Size((1, 400) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = torch.tensor([-0.3_016, -0.7_713, -0.4_205] ).to(SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
1
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from dataclasses import dataclass from typing import Optional, Tuple, Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin, SchedulerOutput @dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 class __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" snake_case__ = 1 @register_to_config def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : int = 2_000 , SCREAMING_SNAKE_CASE__ : float = 0.15 , SCREAMING_SNAKE_CASE__ : float = 0.01 , SCREAMING_SNAKE_CASE__ : float = 1_348.0 , SCREAMING_SNAKE_CASE__ : float = 1e-5 , SCREAMING_SNAKE_CASE__ : int = 1 , ) -> Optional[Any]: # standard deviation of the initial noise distribution lowerCAmelCase__ = sigma_max # setable values lowerCAmelCase__ = None self.set_sigmas(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : torch.FloatTensor , SCREAMING_SNAKE_CASE__ : Optional[int] = None ) -> torch.FloatTensor: return sample def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : Union[str, torch.device] = None ) -> Union[str, Any]: lowerCAmelCase__ = sampling_eps if sampling_eps is not None else self.config.sampling_eps lowerCAmelCase__ = torch.linspace(1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ ) def a ( self : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : float = None ) -> Optional[Any]: lowerCAmelCase__ = sigma_min if sigma_min is not None else self.config.sigma_min lowerCAmelCase__ = sigma_max if sigma_max is not None else self.config.sigma_max lowerCAmelCase__ = sampling_eps if sampling_eps is not None else self.config.sampling_eps if self.timesteps is None: self.set_timesteps(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = sigma_min * (sigma_max / sigma_min) ** (self.timesteps / sampling_eps) lowerCAmelCase__ = torch.exp(torch.linspace(math.log(SCREAMING_SNAKE_CASE__ ) , math.log(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = torch.tensor([sigma_min * (sigma_max / sigma_min) ** t for t in self.timesteps] ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any ) -> int: return torch.where( timesteps == 0 , torch.zeros_like(t.to(timesteps.device ) ) , self.discrete_sigmas[timesteps - 1].to(timesteps.device ) , ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : torch.FloatTensor , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : torch.FloatTensor , SCREAMING_SNAKE_CASE__ : Optional[torch.Generator] = None , SCREAMING_SNAKE_CASE__ : bool = True , ) -> Union[SdeVeOutput, Tuple]: if self.timesteps is None: raise ValueError( "`self.timesteps` is not set, you need to run 'set_timesteps' after creating the scheduler" ) lowerCAmelCase__ = timestep * torch.ones( sample.shape[0] , device=sample.device ) # torch.repeat_interleave(timestep, sample.shape[0]) lowerCAmelCase__ = (timestep * (len(self.timesteps ) - 1)).long() # mps requires indices to be in the same device, so we use cpu as is the default with cuda lowerCAmelCase__ = timesteps.to(self.discrete_sigmas.device ) lowerCAmelCase__ = self.discrete_sigmas[timesteps].to(sample.device ) lowerCAmelCase__ = self.get_adjacent_sigma(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).to(sample.device ) lowerCAmelCase__ = torch.zeros_like(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = (sigma**2 - adjacent_sigma**2) ** 0.5 # equation 6 in the paper: the model_output modeled by the network is grad_x log pt(x) # also equation 47 shows the analog from SDE models to ancestral sampling methods lowerCAmelCase__ = diffusion.flatten() while len(diffusion.shape ) < len(sample.shape ): lowerCAmelCase__ = diffusion.unsqueeze(-1 ) lowerCAmelCase__ = drift - diffusion**2 * model_output # equation 6: sample noise for the diffusion term of lowerCAmelCase__ = randn_tensor( sample.shape , layout=sample.layout , generator=SCREAMING_SNAKE_CASE__ , device=sample.device , dtype=sample.dtype ) lowerCAmelCase__ = sample - drift # subtract because `dt` is a small negative timestep # TODO is the variable diffusion the correct scaling term for the noise? lowerCAmelCase__ = prev_sample_mean + diffusion * noise # add impact of diffusion field g if not return_dict: return (prev_sample, prev_sample_mean) return SdeVeOutput(prev_sample=SCREAMING_SNAKE_CASE__ , prev_sample_mean=SCREAMING_SNAKE_CASE__ ) def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : torch.FloatTensor , SCREAMING_SNAKE_CASE__ : torch.FloatTensor , SCREAMING_SNAKE_CASE__ : Optional[torch.Generator] = None , SCREAMING_SNAKE_CASE__ : bool = True , ) -> Union[SchedulerOutput, Tuple]: if self.timesteps is None: raise ValueError( "`self.timesteps` is not set, you need to run 'set_timesteps' after creating the scheduler" ) # For small batch sizes, the paper "suggest replacing norm(z) with sqrt(d), where d is the dim. of z" # sample noise for correction lowerCAmelCase__ = randn_tensor(sample.shape , layout=sample.layout , generator=SCREAMING_SNAKE_CASE__ ).to(sample.device ) # compute step size from the model_output, the noise, and the snr lowerCAmelCase__ = torch.norm(model_output.reshape(model_output.shape[0] , -1 ) , dim=-1 ).mean() lowerCAmelCase__ = torch.norm(noise.reshape(noise.shape[0] , -1 ) , dim=-1 ).mean() lowerCAmelCase__ = (self.config.snr * noise_norm / grad_norm) ** 2 * 2 lowerCAmelCase__ = step_size * torch.ones(sample.shape[0] ).to(sample.device ) # self.repeat_scalar(step_size, sample.shape[0]) # compute corrected sample: model_output term and noise term lowerCAmelCase__ = step_size.flatten() while len(step_size.shape ) < len(sample.shape ): lowerCAmelCase__ = step_size.unsqueeze(-1 ) lowerCAmelCase__ = sample + step_size * model_output lowerCAmelCase__ = prev_sample_mean + ((step_size * 2) ** 0.5) * noise if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : torch.FloatTensor , SCREAMING_SNAKE_CASE__ : torch.FloatTensor , SCREAMING_SNAKE_CASE__ : torch.FloatTensor , ) -> torch.FloatTensor: # Make sure sigmas and timesteps have the same device and dtype as original_samples lowerCAmelCase__ = timesteps.to(original_samples.device ) lowerCAmelCase__ = self.discrete_sigmas.to(original_samples.device )[timesteps] lowerCAmelCase__ = ( noise * sigmas[:, None, None, None] if noise is not None else torch.randn_like(SCREAMING_SNAKE_CASE__ ) * sigmas[:, None, None, None] ) lowerCAmelCase__ = noise + original_samples return noisy_samples def __len__( self : Optional[Any] ) -> List[Any]: return self.config.num_train_timesteps
61
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _A ( ): """simple docstring""" lowerCAmelCase__ = ArgumentParser( description=( "PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes" ) ) # Optional arguments for the launch helper parser.add_argument("--num_cores" , type=lowerCAmelCase_ , default=1 , help="Number of TPU cores to use (1 or 8)." ) # positional parser.add_argument( "training_script" , type=lowerCAmelCase_ , help=( "The full path to the single TPU training " "program/script to be launched in parallel, " "followed by all the arguments for the " "training script" ) , ) # rest from the training program parser.add_argument("training_script_args" , nargs=lowerCAmelCase_ ) return parser.parse_args() def _A ( ): """simple docstring""" lowerCAmelCase__ = parse_args() # Import training_script as a module. lowerCAmelCase__ = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) lowerCAmelCase__ = script_fpath.stem lowerCAmelCase__ = importlib.import_module(lowerCAmelCase_ ) # Patch sys.argv lowerCAmelCase__ = [args.training_script] + args.training_script_args + ["--tpu_num_cores", str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
61
1
def _A ( lowerCAmelCase_ : str , lowerCAmelCase_ : str ): """simple docstring""" if len(lowerCAmelCase_ ) != len(lowerCAmelCase_ ): raise ValueError("String lengths must match!" ) lowerCAmelCase__ = 0 for chara, chara in zip(lowerCAmelCase_ , lowerCAmelCase_ ): if chara != chara: count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
61
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool UpperCamelCase = { 'Acehnese Arabic': 'ace_Arab', 'Acehnese Latin': 'ace_Latn', 'Mesopotamian Arabic': 'acm_Arab', 'Ta\'izzi-Adeni Arabic': 'acq_Arab', 'Tunisian Arabic': 'aeb_Arab', 'Afrikaans': 'afr_Latn', 'South Levantine Arabic': 'ajp_Arab', 'Akan': 'aka_Latn', 'Amharic': 'amh_Ethi', 'North Levantine Arabic': 'apc_Arab', 'Modern Standard Arabic': 'arb_Arab', 'Modern Standard Arabic Romanized': 'arb_Latn', 'Najdi Arabic': 'ars_Arab', 'Moroccan Arabic': 'ary_Arab', 'Egyptian Arabic': 'arz_Arab', 'Assamese': 'asm_Beng', 'Asturian': 'ast_Latn', 'Awadhi': 'awa_Deva', 'Central Aymara': 'ayr_Latn', 'South Azerbaijani': 'azb_Arab', 'North Azerbaijani': 'azj_Latn', 'Bashkir': 'bak_Cyrl', 'Bambara': 'bam_Latn', 'Balinese': 'ban_Latn', 'Belarusian': 'bel_Cyrl', 'Bemba': 'bem_Latn', 'Bengali': 'ben_Beng', 'Bhojpuri': 'bho_Deva', 'Banjar Arabic': 'bjn_Arab', 'Banjar Latin': 'bjn_Latn', 'Standard Tibetan': 'bod_Tibt', 'Bosnian': 'bos_Latn', 'Buginese': 'bug_Latn', 'Bulgarian': 'bul_Cyrl', 'Catalan': 'cat_Latn', 'Cebuano': 'ceb_Latn', 'Czech': 'ces_Latn', 'Chokwe': 'cjk_Latn', 'Central Kurdish': 'ckb_Arab', 'Crimean Tatar': 'crh_Latn', 'Welsh': 'cym_Latn', 'Danish': 'dan_Latn', 'German': 'deu_Latn', 'Southwestern Dinka': 'dik_Latn', 'Dyula': 'dyu_Latn', 'Dzongkha': 'dzo_Tibt', 'Greek': 'ell_Grek', 'English': 'eng_Latn', 'Esperanto': 'epo_Latn', 'Estonian': 'est_Latn', 'Basque': 'eus_Latn', 'Ewe': 'ewe_Latn', 'Faroese': 'fao_Latn', 'Fijian': 'fij_Latn', 'Finnish': 'fin_Latn', 'Fon': 'fon_Latn', 'French': 'fra_Latn', 'Friulian': 'fur_Latn', 'Nigerian Fulfulde': 'fuv_Latn', 'Scottish Gaelic': 'gla_Latn', 'Irish': 'gle_Latn', 'Galician': 'glg_Latn', 'Guarani': 'grn_Latn', 'Gujarati': 'guj_Gujr', 'Haitian Creole': 'hat_Latn', 'Hausa': 'hau_Latn', 'Hebrew': 'heb_Hebr', 'Hindi': 'hin_Deva', 'Chhattisgarhi': 'hne_Deva', 'Croatian': 'hrv_Latn', 'Hungarian': 'hun_Latn', 'Armenian': 'hye_Armn', 'Igbo': 'ibo_Latn', 'Ilocano': 'ilo_Latn', 'Indonesian': 'ind_Latn', 'Icelandic': 'isl_Latn', 'Italian': 'ita_Latn', 'Javanese': 'jav_Latn', 'Japanese': 'jpn_Jpan', 'Kabyle': 'kab_Latn', 'Jingpho': 'kac_Latn', 'Kamba': 'kam_Latn', 'Kannada': 'kan_Knda', 'Kashmiri Arabic': 'kas_Arab', 'Kashmiri Devanagari': 'kas_Deva', 'Georgian': 'kat_Geor', 'Central Kanuri Arabic': 'knc_Arab', 'Central Kanuri Latin': 'knc_Latn', 'Kazakh': 'kaz_Cyrl', 'Kabiyè': 'kbp_Latn', 'Kabuverdianu': 'kea_Latn', 'Khmer': 'khm_Khmr', 'Kikuyu': 'kik_Latn', 'Kinyarwanda': 'kin_Latn', 'Kyrgyz': 'kir_Cyrl', 'Kimbundu': 'kmb_Latn', 'Northern Kurdish': 'kmr_Latn', 'Kikongo': 'kon_Latn', 'Korean': 'kor_Hang', 'Lao': 'lao_Laoo', 'Ligurian': 'lij_Latn', 'Limburgish': 'lim_Latn', 'Lingala': 'lin_Latn', 'Lithuanian': 'lit_Latn', 'Lombard': 'lmo_Latn', 'Latgalian': 'ltg_Latn', 'Luxembourgish': 'ltz_Latn', 'Luba-Kasai': 'lua_Latn', 'Ganda': 'lug_Latn', 'Luo': 'luo_Latn', 'Mizo': 'lus_Latn', 'Standard Latvian': 'lvs_Latn', 'Magahi': 'mag_Deva', 'Maithili': 'mai_Deva', 'Malayalam': 'mal_Mlym', 'Marathi': 'mar_Deva', 'Minangkabau Arabic ': 'min_Arab', 'Minangkabau Latin': 'min_Latn', 'Macedonian': 'mkd_Cyrl', 'Plateau Malagasy': 'plt_Latn', 'Maltese': 'mlt_Latn', 'Meitei Bengali': 'mni_Beng', 'Halh Mongolian': 'khk_Cyrl', 'Mossi': 'mos_Latn', 'Maori': 'mri_Latn', 'Burmese': 'mya_Mymr', 'Dutch': 'nld_Latn', 'Norwegian Nynorsk': 'nno_Latn', 'Norwegian Bokmål': 'nob_Latn', 'Nepali': 'npi_Deva', 'Northern Sotho': 'nso_Latn', 'Nuer': 'nus_Latn', 'Nyanja': 'nya_Latn', 'Occitan': 'oci_Latn', 'West Central Oromo': 'gaz_Latn', 'Odia': 'ory_Orya', 'Pangasinan': 'pag_Latn', 'Eastern Panjabi': 'pan_Guru', 'Papiamento': 'pap_Latn', 'Western Persian': 'pes_Arab', 'Polish': 'pol_Latn', 'Portuguese': 'por_Latn', 'Dari': 'prs_Arab', 'Southern Pashto': 'pbt_Arab', 'Ayacucho Quechua': 'quy_Latn', 'Romanian': 'ron_Latn', 'Rundi': 'run_Latn', 'Russian': 'rus_Cyrl', 'Sango': 'sag_Latn', 'Sanskrit': 'san_Deva', 'Santali': 'sat_Olck', 'Sicilian': 'scn_Latn', 'Shan': 'shn_Mymr', 'Sinhala': 'sin_Sinh', 'Slovak': 'slk_Latn', 'Slovenian': 'slv_Latn', 'Samoan': 'smo_Latn', 'Shona': 'sna_Latn', 'Sindhi': 'snd_Arab', 'Somali': 'som_Latn', 'Southern Sotho': 'sot_Latn', 'Spanish': 'spa_Latn', 'Tosk Albanian': 'als_Latn', 'Sardinian': 'srd_Latn', 'Serbian': 'srp_Cyrl', 'Swati': 'ssw_Latn', 'Sundanese': 'sun_Latn', 'Swedish': 'swe_Latn', 'Swahili': 'swh_Latn', 'Silesian': 'szl_Latn', 'Tamil': 'tam_Taml', 'Tatar': 'tat_Cyrl', 'Telugu': 'tel_Telu', 'Tajik': 'tgk_Cyrl', 'Tagalog': 'tgl_Latn', 'Thai': 'tha_Thai', 'Tigrinya': 'tir_Ethi', 'Tamasheq Latin': 'taq_Latn', 'Tamasheq Tifinagh': 'taq_Tfng', 'Tok Pisin': 'tpi_Latn', 'Tswana': 'tsn_Latn', 'Tsonga': 'tso_Latn', 'Turkmen': 'tuk_Latn', 'Tumbuka': 'tum_Latn', 'Turkish': 'tur_Latn', 'Twi': 'twi_Latn', 'Central Atlas Tamazight': 'tzm_Tfng', 'Uyghur': 'uig_Arab', 'Ukrainian': 'ukr_Cyrl', 'Umbundu': 'umb_Latn', 'Urdu': 'urd_Arab', 'Northern Uzbek': 'uzn_Latn', 'Venetian': 'vec_Latn', 'Vietnamese': 'vie_Latn', 'Waray': 'war_Latn', 'Wolof': 'wol_Latn', 'Xhosa': 'xho_Latn', 'Eastern Yiddish': 'ydd_Hebr', 'Yoruba': 'yor_Latn', 'Yue Chinese': 'yue_Hant', 'Chinese Simplified': 'zho_Hans', 'Chinese Traditional': 'zho_Hant', 'Standard Malay': 'zsm_Latn', 'Zulu': 'zul_Latn', } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "facebook/nllb-200-distilled-600M" snake_case__ = ( "This is a tool that translates text from a language to another. It takes three inputs: `text`, which should " "be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, " "which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in " "plain English, such as 'Romanian', or 'Albanian'. It returns the text translated in `tgt_lang`." ) snake_case__ = "translator" snake_case__ = AutoTokenizer snake_case__ = AutoModelForSeqaSeqLM snake_case__ = LANGUAGE_CODES snake_case__ = ["text", "text", "text"] snake_case__ = ["text"] def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: if src_lang not in self.lang_to_code: raise ValueError(f'{src_lang} is not a supported language.' ) if tgt_lang not in self.lang_to_code: raise ValueError(f'{tgt_lang} is not a supported language.' ) lowerCAmelCase__ = self.lang_to_code[src_lang] lowerCAmelCase__ = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( SCREAMING_SNAKE_CASE__ , return_tensors="pt" , src_lang=SCREAMING_SNAKE_CASE__ , tgt_lang=SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: return self.model.generate(**SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[str]: return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=SCREAMING_SNAKE_CASE__ )
61
1
def _A ( lowerCAmelCase_ : int , lowerCAmelCase_ : int ): """simple docstring""" while second != 0: lowerCAmelCase__ = first & second first ^= second lowerCAmelCase__ = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() UpperCamelCase = int(input('Enter the first number: ').strip()) UpperCamelCase = int(input('Enter the second number: ').strip()) print(F"""{add(first, second) = }""")
61
import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = VideoToVideoSDPipeline snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"video"} ) - {"image", "width", "height"} snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"video"} ) - {"image"} snake_case__ = PipelineTesterMixin.required_optional_params - {"latents"} snake_case__ = False # No `output_type`. snake_case__ = frozenset( [ "num_inference_steps", "generator", "latents", "return_dict", "callback", "callback_steps", ] ) def a ( self : int ) -> Optional[int]: torch.manual_seed(0 ) lowerCAmelCase__ = 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 , ) lowerCAmelCase__ = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=SCREAMING_SNAKE_CASE__ , set_alpha_to_one=SCREAMING_SNAKE_CASE__ , ) torch.manual_seed(0 ) lowerCAmelCase__ = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) lowerCAmelCase__ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="gelu" , projection_dim=512 , ) lowerCAmelCase__ = CLIPTextModel(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) lowerCAmelCase__ = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, } return components def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Dict=0 ) -> Tuple: # 3 frames lowerCAmelCase__ = floats_tensor((1, 3, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) if str(SCREAMING_SNAKE_CASE__ ).startswith("mps" ): lowerCAmelCase__ = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: lowerCAmelCase__ = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = { "prompt": "A painting of a squirrel eating a burger", "video": video, "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "pt", } return inputs def a ( self : Union[str, Any] ) -> str: lowerCAmelCase__ = "cpu" # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ = self.get_dummy_components() lowerCAmelCase__ = VideoToVideoSDPipeline(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = "np" lowerCAmelCase__ = sd_pipe(**SCREAMING_SNAKE_CASE__ ).frames lowerCAmelCase__ = frames[0][-3:, -3:, -1] assert frames[0].shape == (32, 32, 3) lowerCAmelCase__ = np.array([106, 117, 113, 174, 137, 112, 148, 151, 131] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def a ( self : List[Any] ) -> str: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE__ , expected_max_diff=5e-3 ) @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a ( self : List[Any] ) -> str: pass @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a ( self : int ) -> Optional[Any]: pass @unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline." ) def a ( self : List[str] ) -> Optional[int]: pass def a ( self : Optional[Any] ) -> Tuple: return super().test_progress_bar() @slow @skip_mps class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : str ) -> int: lowerCAmelCase__ = VideoToVideoSDPipeline.from_pretrained("cerspense/zeroscope_v2_XL" , torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames lowerCAmelCase__ = torch.Generator(device="cpu" ).manual_seed(0 ) lowerCAmelCase__ = torch.randn((1, 10, 3, 1_024, 576) , generator=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = video.to("cuda" ) lowerCAmelCase__ = "Spiderman is surfing" lowerCAmelCase__ = pipe(SCREAMING_SNAKE_CASE__ , video=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=3 , output_type="pt" ).frames lowerCAmelCase__ = np.array([-1.0_458_984, -1.1_279_297, -0.9_663_086, -0.91_503_906, -0.75_097_656] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1e-2
61
1
from math import sqrt import numpy as np from sympy import symbols # Coefficient # Speed of light (m/s) UpperCamelCase = 2_9979_2458 # Symbols UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = symbols('ct x y z') def _A ( lowerCAmelCase_ : float ): """simple docstring""" if velocity > c: raise ValueError("Speed must not exceed light speed 299,792,458 [m/s]!" ) elif velocity < 1: # Usually the speed should be much higher than 1 (c order of magnitude) raise ValueError("Speed must be greater than or equal to 1!" ) return velocity / c def _A ( lowerCAmelCase_ : float ): """simple docstring""" return 1 / sqrt(1 - beta(lowerCAmelCase_ ) ** 2 ) def _A ( lowerCAmelCase_ : float ): """simple docstring""" return np.array( [ [gamma(lowerCAmelCase_ ), -gamma(lowerCAmelCase_ ) * beta(lowerCAmelCase_ ), 0, 0], [-gamma(lowerCAmelCase_ ) * beta(lowerCAmelCase_ ), gamma(lowerCAmelCase_ ), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ] ) def _A ( lowerCAmelCase_ : float , lowerCAmelCase_ : np.ndarray | None = None ): """simple docstring""" if event is None: lowerCAmelCase__ = np.array([ct, x, y, z] ) # Symbolic four vector else: event[0] *= c # x0 is ct (speed of light * time) return transformation_matrix(lowerCAmelCase_ ) @ event if __name__ == "__main__": import doctest doctest.testmod() # Example of symbolic vector: UpperCamelCase = transform(2997_9245) print('Example of four vector: ') print(F"""ct' = {four_vector[0]}""") print(F"""x' = {four_vector[1]}""") print(F"""y' = {four_vector[2]}""") print(F"""z' = {four_vector[3]}""") # Substitute symbols with numerical values UpperCamelCase = {ct: c, x: 1, y: 1, z: 1} UpperCamelCase = [four_vector[i].subs(sub_dict) for i in range(4)] print(F"""\n{numerical_vector}""")
61
from __future__ import annotations def _A ( lowerCAmelCase_ : list , lowerCAmelCase_ : int , lowerCAmelCase_ : int , lowerCAmelCase_ : int ): """simple docstring""" lowerCAmelCase__ = [] lowerCAmelCase__ , lowerCAmelCase__ = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0 ) ) lowerCAmelCase__ = result + left + right return input_list def _A ( lowerCAmelCase_ : list ): """simple docstring""" if len(lowerCAmelCase_ ) <= 1: return input_list lowerCAmelCase__ = list(lowerCAmelCase_ ) # iteration for two-way merging lowerCAmelCase__ = 2 while p <= len(lowerCAmelCase_ ): # getting low, high and middle value for merge-sort of single list for i in range(0 , len(lowerCAmelCase_ ) , lowerCAmelCase_ ): lowerCAmelCase__ = i lowerCAmelCase__ = i + p - 1 lowerCAmelCase__ = (low + high + 1) // 2 lowerCAmelCase__ = merge(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # final merge of last two parts if p * 2 >= len(lowerCAmelCase_ ): lowerCAmelCase__ = i lowerCAmelCase__ = merge(lowerCAmelCase_ , 0 , lowerCAmelCase_ , len(lowerCAmelCase_ ) - 1 ) break p *= 2 return input_list if __name__ == "__main__": UpperCamelCase = input('Enter numbers separated by a comma:\n').strip() if user_input == "": UpperCamelCase = [] else: UpperCamelCase = [int(item.strip()) for item in user_input.split(',')] print(iter_merge_sort(unsorted))
61
1
from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar UpperCamelCase = TypeVar('KEY') UpperCamelCase = TypeVar('VAL') @dataclass(frozen=UpperCamelCase__ , slots=UpperCamelCase__ ) class __lowerCamelCase ( Generic[KEY, VAL] ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 class __lowerCamelCase ( _Item ): """simple docstring""" def __init__( self : List[Any] ) -> None: super().__init__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __bool__( self : Union[str, Any] ) -> bool: return False UpperCamelCase = _DeletedItem() class __lowerCamelCase ( MutableMapping[KEY, VAL] ): """simple docstring""" def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : int = 8 , SCREAMING_SNAKE_CASE__ : float = 0.75 ) -> None: lowerCAmelCase__ = initial_block_size lowerCAmelCase__ = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 lowerCAmelCase__ = capacity_factor lowerCAmelCase__ = 0 def a ( self : int , SCREAMING_SNAKE_CASE__ : KEY ) -> int: return hash(SCREAMING_SNAKE_CASE__ ) % len(self._buckets ) def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int ) -> int: return (ind + 1) % len(self._buckets ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : KEY , SCREAMING_SNAKE_CASE__ : VAL ) -> bool: lowerCAmelCase__ = self._buckets[ind] if not stored: lowerCAmelCase__ = _Item(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self._len += 1 return True elif stored.key == key: lowerCAmelCase__ = _Item(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return True else: return False def a ( self : Optional[int] ) -> bool: lowerCAmelCase__ = len(self._buckets ) * self._capacity_factor return len(self ) >= int(SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] ) -> bool: if len(self._buckets ) <= self._initial_block_size: return False lowerCAmelCase__ = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = self._buckets lowerCAmelCase__ = [None] * new_size lowerCAmelCase__ = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def a ( self : str ) -> None: self._resize(len(self._buckets ) * 2 ) def a ( self : Union[str, Any] ) -> None: self._resize(len(self._buckets ) // 2 ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : KEY ) -> Iterator[int]: lowerCAmelCase__ = self._get_bucket_index(SCREAMING_SNAKE_CASE__ ) for _ in range(len(self._buckets ) ): yield ind lowerCAmelCase__ = self._get_next_ind(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : KEY , SCREAMING_SNAKE_CASE__ : VAL ) -> None: for ind in self._iterate_buckets(SCREAMING_SNAKE_CASE__ ): if self._try_set(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): break def __setitem__( self : str , SCREAMING_SNAKE_CASE__ : KEY , SCREAMING_SNAKE_CASE__ : VAL ) -> None: if self._is_full(): self._size_up() self._add_item(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __delitem__( self : Any , SCREAMING_SNAKE_CASE__ : KEY ) -> None: for ind in self._iterate_buckets(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = self._buckets[ind] if item is None: raise KeyError(SCREAMING_SNAKE_CASE__ ) if item is _deleted: continue if item.key == key: lowerCAmelCase__ = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : KEY ) -> VAL: for ind in self._iterate_buckets(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(SCREAMING_SNAKE_CASE__ ) def __len__( self : List[Any] ) -> int: return self._len def __iter__( self : Optional[int] ) -> Iterator[KEY]: yield from (item.key for item in self._buckets if item) def __repr__( self : Union[str, Any] ) -> str: lowerCAmelCase__ = " ,".join( f'{item.key}: {item.val}' for item in self._buckets if item ) return f'HashMap({val_string})'
61
import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, ) class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=13 , SCREAMING_SNAKE_CASE__ : int=7 , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=99 , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : List[str]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : Optional[Any]=37 , SCREAMING_SNAKE_CASE__ : Optional[int]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE__ : Tuple=512 , SCREAMING_SNAKE_CASE__ : Tuple=16 , SCREAMING_SNAKE_CASE__ : Optional[Any]=2 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 , SCREAMING_SNAKE_CASE__ : Dict=4 , ) -> Optional[int]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = seq_length lowerCAmelCase__ = is_training lowerCAmelCase__ = use_attention_mask lowerCAmelCase__ = use_token_type_ids lowerCAmelCase__ = use_labels lowerCAmelCase__ = vocab_size lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = type_vocab_size lowerCAmelCase__ = type_sequence_label_size lowerCAmelCase__ = initializer_range lowerCAmelCase__ = num_choices def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase__ = None if self.use_attention_mask: lowerCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase__ = None if self.use_token_type_ids: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCAmelCase__ = RobertaPreLayerNormConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def a ( self : List[str] ) -> Union[str, Any]: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict def a ( self : Optional[Any] ) -> Dict: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = True lowerCAmelCase__ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax # Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40 class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = True snake_case__ = ( ( FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, ) if is_flax_available() else () ) def a ( self : int ) -> Dict: lowerCAmelCase__ = FlaxRobertaPreLayerNormModelTester(self ) @slow def a ( self : Tuple ) -> Union[str, Any]: for model_class_name in self.all_model_classes: lowerCAmelCase__ = model_class_name.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(np.ones((1, 1) ) ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_flax class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @slow def a ( self : int ) -> Dict: lowerCAmelCase__ = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ )[0] lowerCAmelCase__ = [1, 11, 50_265] self.assertEqual(list(output.shape ) , SCREAMING_SNAKE_CASE__ ) # compare the actual values for a slice. lowerCAmelCase__ = np.array( [[[40.4_880, 18.0_199, -5.2_367], [-1.8_877, -4.0_885, 10.7_085], [-2.2_613, -5.6_110, 7.2_665]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) @slow def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = FlaxRobertaPreLayerNormModel.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ )[0] # compare the actual values for a slice. lowerCAmelCase__ = np.array( [[[0.0_208, -0.0_356, 0.0_237], [-0.1_569, -0.0_411, -0.2_626], [0.1_879, 0.0_125, -0.0_089]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available UpperCamelCase = { 'configuration_pix2struct': [ 'PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Pix2StructConfig', 'Pix2StructTextConfig', 'Pix2StructVisionConfig', ], 'processing_pix2struct': ['Pix2StructProcessor'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['Pix2StructImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ 'PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST', 'Pix2StructPreTrainedModel', 'Pix2StructForConditionalGeneration', 'Pix2StructVisionModel', 'Pix2StructTextModel', ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys UpperCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
61
class __lowerCamelCase : """simple docstring""" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = size lowerCAmelCase__ = [0] * size lowerCAmelCase__ = [0] * size @staticmethod def a ( SCREAMING_SNAKE_CASE__ : int ) -> int: return index | (index + 1) @staticmethod def a ( SCREAMING_SNAKE_CASE__ : int ) -> int: return (index & (index + 1)) - 1 def a ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = value while index < self.size: lowerCAmelCase__ = self.get_prev(SCREAMING_SNAKE_CASE__ ) + 1 if current_left_border == index: lowerCAmelCase__ = value else: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_next(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> int: right -= 1 # Because of right is exclusive lowerCAmelCase__ = 0 while left <= right: lowerCAmelCase__ = self.get_prev(SCREAMING_SNAKE_CASE__ ) if left <= current_left: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , self.tree[right] ) lowerCAmelCase__ = current_left else: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
61
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCamelCase = { 'configuration_distilbert': [ 'DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DistilBertConfig', 'DistilBertOnnxConfig', ], 'tokenization_distilbert': ['DistilBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['DistilBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ 'DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'DistilBertForMaskedLM', 'DistilBertForMultipleChoice', 'DistilBertForQuestionAnswering', 'DistilBertForSequenceClassification', 'DistilBertForTokenClassification', 'DistilBertModel', 'DistilBertPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ 'TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFDistilBertForMaskedLM', 'TFDistilBertForMultipleChoice', 'TFDistilBertForQuestionAnswering', 'TFDistilBertForSequenceClassification', 'TFDistilBertForTokenClassification', 'TFDistilBertMainLayer', 'TFDistilBertModel', 'TFDistilBertPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ 'FlaxDistilBertForMaskedLM', 'FlaxDistilBertForMultipleChoice', 'FlaxDistilBertForQuestionAnswering', 'FlaxDistilBertForSequenceClassification', 'FlaxDistilBertForTokenClassification', 'FlaxDistilBertModel', 'FlaxDistilBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_distilbert import ( DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DistilBertConfig, DistilBertOnnxConfig, ) from .tokenization_distilbert import DistilBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_distilbert_fast import DistilBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_distilbert import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, DistilBertPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertMainLayer, TFDistilBertModel, TFDistilBertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, FlaxDistilBertPreTrainedModel, ) else: import sys UpperCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
61
import unittest from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin UpperCamelCase = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = XLNetTokenizer snake_case__ = XLNetTokenizerFast snake_case__ = True snake_case__ = True def a ( self : str ) -> str: super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) tokenizer.sanitize_special_tokens() tokenizer.save_pretrained(self.tmpdirname ) def a ( self : List[str] ) -> List[Any]: lowerCAmelCase__ = "<s>" lowerCAmelCase__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def a ( self : Union[str, Any] ) -> str: lowerCAmelCase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "<eod>" ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 1_006 ) def a ( self : int ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 1_000 ) def a ( self : List[str] ) -> Any: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("This is a test" ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [285, 46, 10, 170, 382] ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) lowerCAmelCase__ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] ) lowerCAmelCase__ = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) def a ( self : Optional[int] ) -> Optional[Any]: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "", "i", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "se", ".", ] , ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["▁he", "ll", "o"] ) def a ( self : List[Any] ) -> Optional[int]: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "se", ".", ] , ) @slow def a ( self : Any ) -> Any: lowerCAmelCase__ = XLNetTokenizer.from_pretrained("xlnet-base-cased" ) lowerCAmelCase__ = tokenizer.encode("sequence builders" , add_special_tokens=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.encode("multi-sequence build" , add_special_tokens=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert encoded_sentence == text + [4, 3] assert encoded_pair == text + [4] + text_a + [4, 3] @slow def a ( self : Union[str, Any] ) -> Any: # fmt: off lowerCAmelCase__ = {"input_ids": [[17, 21_442, 270, 17, 10, 14_645, 318, 34, 17, 4_546, 3_145, 787, 13, 7_752, 22_018, 23, 21, 17, 4_546, 3_145, 787, 13, 3_352, 14_431, 13, 5_500, 11, 1_176, 580, 13, 16_819, 4_797, 23, 17, 10, 17_135, 658, 19, 457, 7_932, 13, 184, 19, 3_154, 17_135, 6_468, 19, 1_404, 12_269, 19, 4_229, 5_356, 16_264, 46, 19, 17, 20_545, 10_395, 9, 9, 9, 11, 28, 6_421, 9_531, 20_729, 17, 10, 353, 17_022, 11, 21, 6_421, 9_531, 16_949, 17, 10, 11_509, 753, 11, 33, 95, 2_421, 7_385, 956, 14_431, 2_626, 25, 842, 7_385, 4_836, 21, 1_429, 2_272, 9_855, 3_120, 161, 24_738, 19, 13_203, 658, 218, 787, 21, 430, 18_482, 847, 2_637, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 322, 22_178, 27, 1_064, 22, 956, 13, 11_101, 1_429, 5_854, 24_313, 18_953, 40, 422, 24_366, 68, 1_758, 37, 10_483, 14_257, 31, 207, 263, 21, 203, 3_773, 25, 71, 9_735, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 32, 2_049, 3_442, 17, 13_894, 3_380, 23, 95, 18, 17_634, 2_288, 9, 4, 3]], "token_type_ids": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=SCREAMING_SNAKE_CASE__ , model_name="xlnet-base-cased" , revision="c841166438c31ec7ca9a106dee7bb312b73ae511" , )
61
1
import inspect import unittest from typing import List import numpy as np from transformers import EfficientFormerConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerModel, ) from transformers.models.efficientformer.modeling_tf_efficientformer import ( TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_vision_available(): from PIL import Image from transformers import EfficientFormerImageProcessor class __lowerCamelCase : """simple docstring""" def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int = 13 , SCREAMING_SNAKE_CASE__ : int = 64 , SCREAMING_SNAKE_CASE__ : int = 2 , SCREAMING_SNAKE_CASE__ : int = 3 , SCREAMING_SNAKE_CASE__ : int = 3 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : int = 128 , SCREAMING_SNAKE_CASE__ : int=[16, 32, 64, 128] , SCREAMING_SNAKE_CASE__ : int = 7 , SCREAMING_SNAKE_CASE__ : int = 4 , SCREAMING_SNAKE_CASE__ : int = 37 , SCREAMING_SNAKE_CASE__ : str = "gelu" , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : int = 10 , SCREAMING_SNAKE_CASE__ : float = 0.02 , SCREAMING_SNAKE_CASE__ : int = 2 , SCREAMING_SNAKE_CASE__ : int = 1 , SCREAMING_SNAKE_CASE__ : int = 128 , SCREAMING_SNAKE_CASE__ : List[int] = [2, 2, 2, 2] , SCREAMING_SNAKE_CASE__ : int = 2 , SCREAMING_SNAKE_CASE__ : int = 2 , ) -> Tuple: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = image_size lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = is_training lowerCAmelCase__ = use_labels lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = type_sequence_label_size lowerCAmelCase__ = initializer_range lowerCAmelCase__ = encoder_stride lowerCAmelCase__ = num_attention_outputs lowerCAmelCase__ = embed_dim lowerCAmelCase__ = embed_dim + 1 lowerCAmelCase__ = resolution lowerCAmelCase__ = depths lowerCAmelCase__ = hidden_sizes lowerCAmelCase__ = dim lowerCAmelCase__ = mlp_expansion_ratio def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase__ = None if self.use_labels: lowerCAmelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCAmelCase__ = self.get_config() return config, pixel_values, labels def a ( self : int ) -> List[str]: return EfficientFormerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=SCREAMING_SNAKE_CASE__ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , resolution=self.resolution , depths=self.depths , hidden_sizes=self.hidden_sizes , dim=self.dim , mlp_expansion_ratio=self.mlp_expansion_ratio , ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Any: lowerCAmelCase__ = TFEfficientFormerModel(config=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ , training=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> int: lowerCAmelCase__ = self.type_sequence_label_size lowerCAmelCase__ = TFEfficientFormerForImageClassification(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ , training=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images lowerCAmelCase__ = 1 lowerCAmelCase__ = TFEfficientFormerForImageClassification(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def a ( self : Dict ) -> Optional[Any]: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"pixel_values": pixel_values} return config, inputs_dict @require_tf class __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = ( ( TFEfficientFormerModel, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerForImageClassification, ) if is_tf_available() else () ) snake_case__ = ( { "feature-extraction": TFEfficientFormerModel, "image-classification": ( TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, ), } if is_tf_available() else {} ) snake_case__ = False snake_case__ = False snake_case__ = False snake_case__ = False snake_case__ = False def a ( self : List[str] ) -> int: lowerCAmelCase__ = TFEfficientFormerModelTester(self ) lowerCAmelCase__ = ConfigTester( self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ , hidden_size=37 ) def a ( self : Any ) -> Union[str, Any]: self.config_tester.run_common_tests() @unittest.skip(reason="EfficientFormer does not use inputs_embeds" ) def a ( self : str ) -> Dict: pass @unittest.skip(reason="EfficientFormer does not support input and output embeddings" ) def a ( self : Optional[Any] ) -> List[str]: pass def a ( self : Union[str, Any] ) -> Union[str, Any]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase__ = [*signature.parameters.keys()] lowerCAmelCase__ = ["pixel_values"] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] ) -> Union[str, Any]: def check_hidden_states_output(SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] ): lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , training=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states lowerCAmelCase__ = getattr( self.model_tester , "expected_num_hidden_layers" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) if hasattr(self.model_tester , "encoder_seq_length" ): lowerCAmelCase__ = self.model_tester.encoder_seq_length if hasattr(self.model_tester , "chunk_length" ) and self.model_tester.chunk_length > 1: lowerCAmelCase__ = seq_length * self.model_tester.chunk_length else: lowerCAmelCase__ = self.model_tester.seq_length self.assertListEqual( list(hidden_states[-1].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) if config.is_encoder_decoder: lowerCAmelCase__ = outputs.decoder_hidden_states self.asseretIsInstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = getattr(self.model_tester , "seq_length" , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = getattr(self.model_tester , "decoder_seq_length" , SCREAMING_SNAKE_CASE__ ) self.assertListEqual( list(hidden_states[-1].shape[-2:] ) , [decoder_seq_length, self.model_tester.hidden_size] , ) lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int]=False ) -> Tuple: lowerCAmelCase__ = super()._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_labels=SCREAMING_SNAKE_CASE__ ) if return_labels: if model_class.__name__ == "TFEfficientFormerForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def a ( self : List[Any] ) -> List[Any]: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) @unittest.skip(reason="EfficientFormer does not implement masked image modeling yet" ) def a ( self : List[str] ) -> Union[str, Any]: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*SCREAMING_SNAKE_CASE__ ) def a ( self : str ) -> Any: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE__ ) @slow def a ( self : Optional[Any] ) -> str: for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase__ = TFEfficientFormerModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] ) -> Optional[Any]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ = True lowerCAmelCase__ = getattr(self.model_tester , "seq_length" , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = getattr(self.model_tester , "encoder_seq_length" , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = getattr(self.model_tester , "key_length" , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = getattr(self.model_tester , "chunk_length" , SCREAMING_SNAKE_CASE__ ) if chunk_length is not None and hasattr(self.model_tester , "num_hashes" ): lowerCAmelCase__ = encoder_seq_length * self.model_tester.num_hashes for model_class in self.all_model_classes: lowerCAmelCase__ = True lowerCAmelCase__ = False lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , training=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_attention_outputs ) # check that output_attentions also work using config del inputs_dict["output_attentions"] lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , training=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_attention_outputs ) if chunk_length is not None: self.assertListEqual( list(attentions[0].shape[-4:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length] , ) else: self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length] , ) def a ( self : Union[str, Any] ) -> Any: # We use a simplified version of this test for EfficientFormer because it requires training=False # and Keras refuses to let us force that during functional construction lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # Prepare our model lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) # These are maximally general inputs for the model, with multiple None dimensions # Hopefully this will catch any conditionals that fail for flexible shapes lowerCAmelCase__ = { key: tf.keras.Input(shape=val.shape[1:] , dtype=val.dtype , name=SCREAMING_SNAKE_CASE__ ) for key, val in model.input_signature.items() if key in model.dummy_inputs } lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) self.assertTrue(outputs_dict is not None ) def _A ( ): """simple docstring""" lowerCAmelCase__ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf @require_vision class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @cached_property def a ( self : Dict ) -> Dict: return ( EfficientFormerImageProcessor.from_pretrained("snap-research/efficientformer-l1-300" ) if is_vision_available() else None ) @slow def a ( self : str ) -> Optional[Any]: lowerCAmelCase__ = TFEfficientFormerForImageClassification.from_pretrained("snap-research/efficientformer-l1-300" ) lowerCAmelCase__ = self.default_image_processor lowerCAmelCase__ = prepare_img() lowerCAmelCase__ = image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors="tf" ) # forward pass lowerCAmelCase__ = model(**SCREAMING_SNAKE_CASE__ , training=SCREAMING_SNAKE_CASE__ ) # verify the logits lowerCAmelCase__ = tf.TensorShape((1, 1_000) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tf.constant([-0.0_555, 0.4_825, -0.0_852] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) @slow def a ( self : Tuple ) -> Union[str, Any]: lowerCAmelCase__ = TFEfficientFormerForImageClassificationWithTeacher.from_pretrained( "snap-research/efficientformer-l1-300" ) lowerCAmelCase__ = self.default_image_processor lowerCAmelCase__ = prepare_img() lowerCAmelCase__ = image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors="tf" ) # forward pass lowerCAmelCase__ = model(**SCREAMING_SNAKE_CASE__ , training=SCREAMING_SNAKE_CASE__ ) # verify the logits lowerCAmelCase__ = tf.TensorShape((1, 1_000) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tf.constant([-0.1_312, 0.4_353, -1.0_499] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
import operator as op UpperCamelCase = 'scaler.pt' UpperCamelCase = 'pytorch_model' UpperCamelCase = 'random_states' UpperCamelCase = 'optimizer' UpperCamelCase = 'scheduler' UpperCamelCase = 'pytorch_model.bin' UpperCamelCase = 'pytorch_model.bin.index.json' UpperCamelCase = 'model.safetensors' UpperCamelCase = 'model.safetensors.index.json' UpperCamelCase = '1.10.2' UpperCamelCase = 'py38' UpperCamelCase = '4.17.0' UpperCamelCase = ['ml.p3.16xlarge', 'ml.p3dn.24xlarge', 'ml.p4dn.24xlarge'] UpperCamelCase = ['FULL_SHARD', 'SHARD_GRAD_OP', 'NO_SHARD', 'HYBRID_SHARD', 'HYBRID_SHARD_ZERO2'] UpperCamelCase = ['TRANSFORMER_BASED_WRAP', 'SIZE_BASED_WRAP', 'NO_WRAP'] UpperCamelCase = ['BACKWARD_PRE', 'BACKWARD_POST', 'NO_PREFETCH'] UpperCamelCase = ['FULL_STATE_DICT', 'LOCAL_STATE_DICT', 'SHARDED_STATE_DICT'] UpperCamelCase = '2.0.1' UpperCamelCase = ['pdsh', 'standard', 'openmpi', 'mvapich'] UpperCamelCase = ['default', 'reduce-overhead', 'max-autotune'] UpperCamelCase = {'>': op.gt, '>=': op.ge, '==': op.eq, '!=': op.ne, '<=': op.le, '<': op.lt} # These are the args for `torch.distributed.launch` for pytorch < 1.9 UpperCamelCase = [ 'nnodes', 'nproc_per_node', 'rdzv_backend', 'rdzv_endpoint', 'rdzv_id', 'rdzv_conf', 'standalone', 'max_restarts', 'monitor_interval', 'start_method', 'role', 'module', 'm', 'no_python', 'run_path', 'log_dir', 'r', 'redirects', 't', 'tee', 'node_rank', 'master_addr', 'master_port', ] UpperCamelCase = ['DEEPSPEED', 'MULTI_GPU', 'FSDP', 'MEGATRON_LM'] UpperCamelCase = ['DEEPSPEED', 'MULTI_XPU', 'FSDP']
61
1
from math import asin, atan, cos, radians, sin, sqrt, tan UpperCamelCase = 6_378_137.0 UpperCamelCase = 6_356_752.314_245 UpperCamelCase = 637_8137 def _A ( lowerCAmelCase_ : float , lowerCAmelCase_ : float , lowerCAmelCase_ : float , lowerCAmelCase_ : float ): """simple docstring""" lowerCAmelCase__ = (AXIS_A - AXIS_B) / AXIS_A lowerCAmelCase__ = atan((1 - flattening) * tan(radians(lowerCAmelCase_ ) ) ) lowerCAmelCase__ = atan((1 - flattening) * tan(radians(lowerCAmelCase_ ) ) ) lowerCAmelCase__ = radians(lowerCAmelCase_ ) lowerCAmelCase__ = radians(lowerCAmelCase_ ) # Equation lowerCAmelCase__ = sin((phi_a - phi_a) / 2 ) lowerCAmelCase__ = sin((lambda_a - lambda_a) / 2 ) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda lowerCAmelCase__ = sqrt(sin_sq_phi + (cos(lowerCAmelCase_ ) * cos(lowerCAmelCase_ ) * sin_sq_lambda) ) return 2 * RADIUS * asin(lowerCAmelCase_ ) if __name__ == "__main__": import doctest doctest.testmod()
61
import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'vocab_file': 'sentencepiece.model'} UpperCamelCase = { 'vocab_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model', }, } UpperCamelCase = { 'google/rembert': 256, } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int]=False , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : Any="[CLS]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" , SCREAMING_SNAKE_CASE__ : Dict="[UNK]" , SCREAMING_SNAKE_CASE__ : Optional[Any]="[SEP]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[PAD]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[CLS]" , SCREAMING_SNAKE_CASE__ : List[Any]="[MASK]" , **SCREAMING_SNAKE_CASE__ : str , ) -> Dict: super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ , remove_space=SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = do_lower_case lowerCAmelCase__ = remove_space lowerCAmelCase__ = keep_accents lowerCAmelCase__ = vocab_file lowerCAmelCase__ = spm.SentencePieceProcessor() self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def a ( self : int ) -> Union[str, Any]: return len(self.sp_model ) def a ( self : Any ) -> str: lowerCAmelCase__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Union[str, Any] ) -> List[str]: lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = d lowerCAmelCase__ = spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int=False ) -> Optional[int]: lowerCAmelCase__ = self.sp_model.EncodeAsPieces(SCREAMING_SNAKE_CASE__ ) return pieces def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> List[Any]: return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Dict: return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : int ) -> int: lowerCAmelCase__ = self.sp_model.decode_pieces(SCREAMING_SNAKE_CASE__ ) return out_string def a ( self : int , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: 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 not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error("Vocabulary path ({}) should be a directory".format(SCREAMING_SNAKE_CASE__ ) ) return lowerCAmelCase__ = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
61
1
import inspect import tempfile from collections import OrderedDict, UserDict from collections.abc import MutableMapping from contextlib import ExitStack, contextmanager from dataclasses import fields from enum import Enum from typing import Any, ContextManager, List, Tuple import numpy as np from .import_utils import is_flax_available, is_tf_available, is_torch_available, is_torch_fx_proxy if is_flax_available(): import jax.numpy as jnp class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def __get__( self : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str]=None ) -> str: # See docs.python.org/3/howto/descriptor.html#properties if obj is None: return self if self.fget is None: raise AttributeError("unreadable attribute" ) lowerCAmelCase__ = "__cached_" + self.fget.__name__ lowerCAmelCase__ = getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if cached is None: lowerCAmelCase__ = self.fget(SCREAMING_SNAKE_CASE__ ) setattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return cached def _A ( lowerCAmelCase_ : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = val.lower() if val in {"y", "yes", "t", "true", "on", "1"}: return 1 if val in {"n", "no", "f", "false", "off", "0"}: return 0 raise ValueError(F'invalid truth value {val!r}' ) def _A ( lowerCAmelCase_ : Dict ): """simple docstring""" if is_torch_fx_proxy(lowerCAmelCase_ ): return True if is_torch_available(): import torch if isinstance(lowerCAmelCase_ , torch.Tensor ): return True if is_tf_available(): import tensorflow as tf if isinstance(lowerCAmelCase_ , tf.Tensor ): return True if is_flax_available(): import jax.numpy as jnp from jax.core import Tracer if isinstance(lowerCAmelCase_ , (jnp.ndarray, Tracer) ): return True return isinstance(lowerCAmelCase_ , np.ndarray ) def _A ( lowerCAmelCase_ : Tuple ): """simple docstring""" return isinstance(lowerCAmelCase_ , np.ndarray ) def _A ( lowerCAmelCase_ : List[str] ): """simple docstring""" return _is_numpy(lowerCAmelCase_ ) def _A ( lowerCAmelCase_ : Optional[int] ): """simple docstring""" import torch return isinstance(lowerCAmelCase_ , torch.Tensor ) def _A ( lowerCAmelCase_ : Dict ): """simple docstring""" return False if not is_torch_available() else _is_torch(lowerCAmelCase_ ) def _A ( lowerCAmelCase_ : List[Any] ): """simple docstring""" import torch return isinstance(lowerCAmelCase_ , torch.device ) def _A ( lowerCAmelCase_ : int ): """simple docstring""" return False if not is_torch_available() else _is_torch_device(lowerCAmelCase_ ) def _A ( lowerCAmelCase_ : Any ): """simple docstring""" import torch if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): if hasattr(lowerCAmelCase_ , lowerCAmelCase_ ): lowerCAmelCase__ = getattr(lowerCAmelCase_ , lowerCAmelCase_ ) else: return False return isinstance(lowerCAmelCase_ , torch.dtype ) def _A ( lowerCAmelCase_ : List[Any] ): """simple docstring""" return False if not is_torch_available() else _is_torch_dtype(lowerCAmelCase_ ) def _A ( lowerCAmelCase_ : Dict ): """simple docstring""" import tensorflow as tf return isinstance(lowerCAmelCase_ , tf.Tensor ) def _A ( lowerCAmelCase_ : Union[str, Any] ): """simple docstring""" return False if not is_tf_available() else _is_tensorflow(lowerCAmelCase_ ) def _A ( lowerCAmelCase_ : Dict ): """simple docstring""" import tensorflow as tf # the `is_symbolic_tensor` predicate is only available starting with TF 2.14 if hasattr(lowerCAmelCase_ , "is_symbolic_tensor" ): return tf.is_symbolic_tensor(lowerCAmelCase_ ) return type(lowerCAmelCase_ ) == tf.Tensor def _A ( lowerCAmelCase_ : Optional[int] ): """simple docstring""" return False if not is_tf_available() else _is_tf_symbolic_tensor(lowerCAmelCase_ ) def _A ( lowerCAmelCase_ : List[str] ): """simple docstring""" import jax.numpy as jnp # noqa: F811 return isinstance(lowerCAmelCase_ , jnp.ndarray ) def _A ( lowerCAmelCase_ : Any ): """simple docstring""" return False if not is_flax_available() else _is_jax(lowerCAmelCase_ ) def _A ( lowerCAmelCase_ : Any ): """simple docstring""" if isinstance(lowerCAmelCase_ , (dict, UserDict) ): return {k: to_py_obj(lowerCAmelCase_ ) for k, v in obj.items()} elif isinstance(lowerCAmelCase_ , (list, tuple) ): return [to_py_obj(lowerCAmelCase_ ) for o in obj] elif is_tf_tensor(lowerCAmelCase_ ): return obj.numpy().tolist() elif is_torch_tensor(lowerCAmelCase_ ): return obj.detach().cpu().tolist() elif is_jax_tensor(lowerCAmelCase_ ): return np.asarray(lowerCAmelCase_ ).tolist() elif isinstance(lowerCAmelCase_ , (np.ndarray, np.number) ): # tolist also works on 0d np arrays return obj.tolist() else: return obj def _A ( lowerCAmelCase_ : Union[str, Any] ): """simple docstring""" if isinstance(lowerCAmelCase_ , (dict, UserDict) ): return {k: to_numpy(lowerCAmelCase_ ) for k, v in obj.items()} elif isinstance(lowerCAmelCase_ , (list, tuple) ): return np.array(lowerCAmelCase_ ) elif is_tf_tensor(lowerCAmelCase_ ): return obj.numpy() elif is_torch_tensor(lowerCAmelCase_ ): return obj.detach().cpu().numpy() elif is_jax_tensor(lowerCAmelCase_ ): return np.asarray(lowerCAmelCase_ ) else: return obj class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def a ( self : List[Any] ) -> Any: lowerCAmelCase__ = fields(self ) # Safety and consistency checks if not len(SCREAMING_SNAKE_CASE__ ): raise ValueError(f'{self.__class__.__name__} has no fields.' ) if not all(field.default is None for field in class_fields[1:] ): raise ValueError(f'{self.__class__.__name__} should not have more than one required field.' ) lowerCAmelCase__ = getattr(self , class_fields[0].name ) lowerCAmelCase__ = all(getattr(self , field.name ) is None for field in class_fields[1:] ) if other_fields_are_none and not is_tensor(SCREAMING_SNAKE_CASE__ ): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = first_field.items() lowerCAmelCase__ = True else: try: lowerCAmelCase__ = iter(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = True except TypeError: lowerCAmelCase__ = False # if we provided an iterator as first field and the iterator is a (key, value) iterator # set the associated fields if first_field_iterator: for idx, element in enumerate(SCREAMING_SNAKE_CASE__ ): if ( not isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ) or not len(SCREAMING_SNAKE_CASE__ ) == 2 or not isinstance(element[0] , SCREAMING_SNAKE_CASE__ ) ): if idx == 0: # If we do not have an iterator of key/values, set it as attribute lowerCAmelCase__ = first_field else: # If we have a mixed iterator, raise an error raise ValueError( f'Cannot set key/value for {element}. It needs to be a tuple (key, value).' ) break setattr(self , element[0] , element[1] ) if element[1] is not None: lowerCAmelCase__ = element[1] elif first_field is not None: lowerCAmelCase__ = first_field else: for field in class_fields: lowerCAmelCase__ = getattr(self , field.name ) if v is not None: lowerCAmelCase__ = v def __delitem__( self : Union[str, Any] , *SCREAMING_SNAKE_CASE__ : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : Tuple ) -> int: raise Exception(f'You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.' ) def a ( self : Dict , *SCREAMING_SNAKE_CASE__ : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Optional[Any]: raise Exception(f'You cannot use ``setdefault`` on a {self.__class__.__name__} instance.' ) def a ( self : List[str] , *SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : Dict ) -> Any: raise Exception(f'You cannot use ``pop`` on a {self.__class__.__name__} instance.' ) def a ( self : Any , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[int]: raise Exception(f'You cannot use ``update`` on a {self.__class__.__name__} instance.' ) def __getitem__( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = dict(self.items() ) return inner_dict[k] else: return self.to_tuple()[k] def __setattr__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple ) -> List[str]: if name in self.keys() and value is not None: # Don't call self.__setitem__ to avoid recursion errors super().__setitem__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) super().__setattr__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __setitem__( self : str , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int ) -> Optional[int]: # Will raise a KeyException if needed super().__setitem__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Don't call self.__setattr__ to avoid recursion errors super().__setattr__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def a ( self : str ) -> Tuple[Any]: return tuple(self[k] for k in self.keys() ) class __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" @classmethod def a ( cls : Optional[int] , SCREAMING_SNAKE_CASE__ : Any ) -> str: raise ValueError( f'{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys() )}' ) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "longest" snake_case__ = "max_length" snake_case__ = "do_not_pad" class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "pt" snake_case__ = "tf" snake_case__ = "np" snake_case__ = "jax" class __lowerCamelCase : """simple docstring""" def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : List[ContextManager] ) -> Union[str, Any]: lowerCAmelCase__ = context_managers lowerCAmelCase__ = ExitStack() def __enter__( self : List[Any] ) -> Dict: for context_manager in self.context_managers: self.stack.enter_context(SCREAMING_SNAKE_CASE__ ) def __exit__( self : List[Any] , *SCREAMING_SNAKE_CASE__ : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: self.stack.__exit__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def _A ( lowerCAmelCase_ : int ): """simple docstring""" lowerCAmelCase__ = infer_framework(lowerCAmelCase_ ) if framework == "tf": lowerCAmelCase__ = inspect.signature(model_class.call ) # TensorFlow models elif framework == "pt": lowerCAmelCase__ = inspect.signature(model_class.forward ) # PyTorch models else: lowerCAmelCase__ = inspect.signature(model_class.__call__ ) # Flax models for p in signature.parameters: if p == "return_loss" and signature.parameters[p].default is True: return True return False def _A ( lowerCAmelCase_ : Any ): """simple docstring""" lowerCAmelCase__ = model_class.__name__ lowerCAmelCase__ = infer_framework(lowerCAmelCase_ ) if framework == "tf": lowerCAmelCase__ = inspect.signature(model_class.call ) # TensorFlow models elif framework == "pt": lowerCAmelCase__ = inspect.signature(model_class.forward ) # PyTorch models else: lowerCAmelCase__ = inspect.signature(model_class.__call__ ) # Flax models if "QuestionAnswering" in model_name: return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")] else: return [p for p in signature.parameters if "label" in p] def _A ( lowerCAmelCase_ : MutableMapping , lowerCAmelCase_ : str = "" , lowerCAmelCase_ : str = "." ): """simple docstring""" def _flatten_dict(lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : List[str]="" , lowerCAmelCase_ : Tuple="." ): for k, v in d.items(): lowerCAmelCase__ = str(lowerCAmelCase_ ) + delimiter + str(lowerCAmelCase_ ) if parent_key else k if v and isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): yield from flatten_dict(lowerCAmelCase_ , lowerCAmelCase_ , delimiter=lowerCAmelCase_ ).items() else: yield key, v return dict(_flatten_dict(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ) @contextmanager def _A ( lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : bool = False ): """simple docstring""" if use_temp_dir: with tempfile.TemporaryDirectory() as tmp_dir: yield tmp_dir else: yield working_dir def _A ( lowerCAmelCase_ : Dict , lowerCAmelCase_ : str=None ): """simple docstring""" if is_numpy_array(lowerCAmelCase_ ): return np.transpose(lowerCAmelCase_ , axes=lowerCAmelCase_ ) elif is_torch_tensor(lowerCAmelCase_ ): return array.T if axes is None else array.permute(*lowerCAmelCase_ ) elif is_tf_tensor(lowerCAmelCase_ ): import tensorflow as tf return tf.transpose(lowerCAmelCase_ , perm=lowerCAmelCase_ ) elif is_jax_tensor(lowerCAmelCase_ ): return jnp.transpose(lowerCAmelCase_ , axes=lowerCAmelCase_ ) else: raise ValueError(F'Type not supported for transpose: {type(lowerCAmelCase_ )}.' ) def _A ( lowerCAmelCase_ : Any , lowerCAmelCase_ : Tuple ): """simple docstring""" if is_numpy_array(lowerCAmelCase_ ): return np.reshape(lowerCAmelCase_ , lowerCAmelCase_ ) elif is_torch_tensor(lowerCAmelCase_ ): return array.reshape(*lowerCAmelCase_ ) elif is_tf_tensor(lowerCAmelCase_ ): import tensorflow as tf return tf.reshape(lowerCAmelCase_ , lowerCAmelCase_ ) elif is_jax_tensor(lowerCAmelCase_ ): return jnp.reshape(lowerCAmelCase_ , lowerCAmelCase_ ) else: raise ValueError(F'Type not supported for reshape: {type(lowerCAmelCase_ )}.' ) def _A ( lowerCAmelCase_ : Any , lowerCAmelCase_ : List[str]=None ): """simple docstring""" if is_numpy_array(lowerCAmelCase_ ): return np.squeeze(lowerCAmelCase_ , axis=lowerCAmelCase_ ) elif is_torch_tensor(lowerCAmelCase_ ): return array.squeeze() if axis is None else array.squeeze(dim=lowerCAmelCase_ ) elif is_tf_tensor(lowerCAmelCase_ ): import tensorflow as tf return tf.squeeze(lowerCAmelCase_ , axis=lowerCAmelCase_ ) elif is_jax_tensor(lowerCAmelCase_ ): return jnp.squeeze(lowerCAmelCase_ , axis=lowerCAmelCase_ ) else: raise ValueError(F'Type not supported for squeeze: {type(lowerCAmelCase_ )}.' ) def _A ( lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : Tuple ): """simple docstring""" if is_numpy_array(lowerCAmelCase_ ): return np.expand_dims(lowerCAmelCase_ , lowerCAmelCase_ ) elif is_torch_tensor(lowerCAmelCase_ ): return array.unsqueeze(dim=lowerCAmelCase_ ) elif is_tf_tensor(lowerCAmelCase_ ): import tensorflow as tf return tf.expand_dims(lowerCAmelCase_ , axis=lowerCAmelCase_ ) elif is_jax_tensor(lowerCAmelCase_ ): return jnp.expand_dims(lowerCAmelCase_ , axis=lowerCAmelCase_ ) else: raise ValueError(F'Type not supported for expand_dims: {type(lowerCAmelCase_ )}.' ) def _A ( lowerCAmelCase_ : int ): """simple docstring""" if is_numpy_array(lowerCAmelCase_ ): return np.size(lowerCAmelCase_ ) elif is_torch_tensor(lowerCAmelCase_ ): return array.numel() elif is_tf_tensor(lowerCAmelCase_ ): import tensorflow as tf return tf.size(lowerCAmelCase_ ) elif is_jax_tensor(lowerCAmelCase_ ): return array.size else: raise ValueError(F'Type not supported for expand_dims: {type(lowerCAmelCase_ )}.' ) def _A ( lowerCAmelCase_ : Any , lowerCAmelCase_ : Tuple ): """simple docstring""" for key, value in auto_map.items(): if isinstance(lowerCAmelCase_ , (tuple, list) ): lowerCAmelCase__ = [F'{repo_id}--{v}' if (v is not None and "--" not in v) else v for v in value] elif value is not None and "--" not in value: lowerCAmelCase__ = F'{repo_id}--{value}' return auto_map def _A ( lowerCAmelCase_ : Optional[int] ): """simple docstring""" for base_class in inspect.getmro(lowerCAmelCase_ ): lowerCAmelCase__ = base_class.__module__ lowerCAmelCase__ = base_class.__name__ if module.startswith("tensorflow" ) or module.startswith("keras" ) or name == "TFPreTrainedModel": return "tf" elif module.startswith("torch" ) or name == "PreTrainedModel": return "pt" elif module.startswith("flax" ) or module.startswith("jax" ) or name == "FlaxPreTrainedModel": return "flax" else: raise TypeError(F'Could not infer framework from class {model_class}.' )
61
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
61
1
import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification if is_tf_available(): from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification if is_flax_available(): from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification UpperCamelCase = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co UpperCamelCase = 'main' # Default branch name UpperCamelCase = 'f2c752cfc5c0ab6f4bdec59acea69eefbee381c2' # One particular commit (not the top of `main`) UpperCamelCase = 'aaaaaaa' # This commit does not exist, so we should 404. UpperCamelCase = 'd9e9f15bc825e4b2c9249e9578f884bbcb5e3684' # Sha-1 of config.json on the top of `main`, for checking purposes UpperCamelCase = '4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3' @contextlib.contextmanager def _A ( ): """simple docstring""" print("Welcome!" ) yield print("Bye!" ) @contextlib.contextmanager def _A ( ): """simple docstring""" print("Bonjour!" ) yield print("Au revoir!" ) class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : Union[str, Any] ) -> Optional[int]: # If the spec is missing, importlib would not be able to import the module dynamically. assert transformers.__spec__ is not None assert importlib.util.find_spec("transformers" ) is not None class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @unittest.mock.patch("sys.stdout" , new_callable=io.StringIO ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : int ) -> Optional[Any]: with ContextManagers([] ): print("Transformers are awesome!" ) # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue() , "Transformers are awesome!\n" ) @unittest.mock.patch("sys.stdout" , new_callable=io.StringIO ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: with ContextManagers([context_en()] ): print("Transformers are awesome!" ) # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue() , "Welcome!\nTransformers are awesome!\nBye!\n" ) @unittest.mock.patch("sys.stdout" , new_callable=io.StringIO ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> str: with ContextManagers([context_fr(), context_en()] ): print("Transformers are awesome!" ) # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue() , "Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n" ) @require_torch def a ( self : Optional[Any] ) -> Dict: self.assertEqual(find_labels(SCREAMING_SNAKE_CASE__ ) , ["labels"] ) self.assertEqual(find_labels(SCREAMING_SNAKE_CASE__ ) , ["labels", "next_sentence_label"] ) self.assertEqual(find_labels(SCREAMING_SNAKE_CASE__ ) , ["start_positions", "end_positions"] ) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" pass self.assertEqual(find_labels(SCREAMING_SNAKE_CASE__ ) , ["labels"] ) @require_tf def a ( self : Optional[int] ) -> List[Any]: self.assertEqual(find_labels(SCREAMING_SNAKE_CASE__ ) , ["labels"] ) self.assertEqual(find_labels(SCREAMING_SNAKE_CASE__ ) , ["labels", "next_sentence_label"] ) self.assertEqual(find_labels(SCREAMING_SNAKE_CASE__ ) , ["start_positions", "end_positions"] ) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" pass self.assertEqual(find_labels(SCREAMING_SNAKE_CASE__ ) , ["labels"] ) @require_flax def a ( self : Optional[Any] ) -> Dict: # Flax models don't have labels self.assertEqual(find_labels(SCREAMING_SNAKE_CASE__ ) , [] ) self.assertEqual(find_labels(SCREAMING_SNAKE_CASE__ ) , [] ) self.assertEqual(find_labels(SCREAMING_SNAKE_CASE__ ) , [] ) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" pass self.assertEqual(find_labels(SCREAMING_SNAKE_CASE__ ) , [] )
61
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = ["pixel_values"] def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Union[int, float] = 1 / 255 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> None: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = size if size is not None else {"shortest_edge": 384} lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = do_resize lowerCAmelCase__ = size # Default value set here for backwards compatibility where the value in config is None lowerCAmelCase__ = crop_pct if crop_pct is not None else 224 / 256 lowerCAmelCase__ = resample lowerCAmelCase__ = do_rescale lowerCAmelCase__ = rescale_factor lowerCAmelCase__ = do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN lowerCAmelCase__ = image_std if image_std is not None else IMAGENET_STANDARD_STD def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : int , ) -> np.ndarray: lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) if "shortest_edge" not in size: raise ValueError(f'Size dictionary must contain \'shortest_edge\' key. Got {size.keys()}' ) lowerCAmelCase__ = size["shortest_edge"] if shortest_edge < 384: # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct lowerCAmelCase__ = int(shortest_edge / crop_pct ) lowerCAmelCase__ = get_resize_output_image_size(SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # then crop to (shortest_edge, shortest_edge) return center_crop(image=SCREAMING_SNAKE_CASE__ , size=(shortest_edge, shortest_edge) , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) else: # warping (no cropping) when evaluated at 384 or larger return resize( SCREAMING_SNAKE_CASE__ , size=(shortest_edge, shortest_edge) , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : int , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[int, float] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> List[Any]: return rescale(SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Optional[int] , ) -> np.ndarray: return normalize(SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : ImageInput , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE__ : ChannelDimension = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE__ : Dict , ) -> PIL.Image.Image: lowerCAmelCase__ = do_resize if do_resize is not None else self.do_resize lowerCAmelCase__ = crop_pct if crop_pct is not None else self.crop_pct lowerCAmelCase__ = resample if resample is not None else self.resample lowerCAmelCase__ = do_rescale if do_rescale is not None else self.do_rescale lowerCAmelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCAmelCase__ = do_normalize if do_normalize is not None else self.do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else self.image_mean lowerCAmelCase__ = image_std if image_std is not None else self.image_std lowerCAmelCase__ = size if size is not None else self.size lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = make_list_of_images(SCREAMING_SNAKE_CASE__ ) if not valid_images(SCREAMING_SNAKE_CASE__ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_resize and size["shortest_edge"] < 384 and crop_pct is None: raise ValueError("crop_pct must be specified if size < 384." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. lowerCAmelCase__ = [to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if do_resize: lowerCAmelCase__ = [self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , crop_pct=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images] if do_rescale: lowerCAmelCase__ = [self.rescale(image=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ ) for image in images] if do_normalize: lowerCAmelCase__ = [self.normalize(image=SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = {"pixel_values": images} return BatchFeature(data=SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ )
61
1
import fire from utils import calculate_rouge, save_json def _A ( lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : int=None , **lowerCAmelCase_ : Dict ): """simple docstring""" lowerCAmelCase__ = [x.strip() for x in open(lowerCAmelCase_ ).readlines()] lowerCAmelCase__ = [x.strip() for x in open(lowerCAmelCase_ ).readlines()][: len(lowerCAmelCase_ )] lowerCAmelCase__ = calculate_rouge(lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ) if save_path is not None: save_json(lowerCAmelCase_ , lowerCAmelCase_ , indent=lowerCAmelCase_ ) return metrics # these print nicely if __name__ == "__main__": fire.Fire(calculate_rouge_path)
61
import shutil import tempfile import unittest import numpy as np import pytest from transformers import is_speech_available, is_vision_available from transformers.testing_utils import require_torch if is_vision_available(): from transformers import TvltImageProcessor if is_speech_available(): from transformers import TvltFeatureExtractor from transformers import TvltProcessor @require_torch class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : Any ) -> int: lowerCAmelCase__ = "ZinengTang/tvlt-base" lowerCAmelCase__ = tempfile.mkdtemp() def a ( self : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: return TvltImageProcessor.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE__ ) def a ( self : int , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> str: return TvltFeatureExtractor.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] ) -> Any: shutil.rmtree(self.tmpdirname ) def a ( self : Any ) -> Union[str, Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) lowerCAmelCase__ = TvltProcessor.from_pretrained(self.tmpdirname ) self.assertIsInstance(processor.feature_extractor , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> List[Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([12_000] ) lowerCAmelCase__ = feature_extractor(SCREAMING_SNAKE_CASE__ , return_tensors="np" ) lowerCAmelCase__ = processor(audio=SCREAMING_SNAKE_CASE__ , return_tensors="np" ) for key in audio_dict.keys(): self.assertAlmostEqual(audio_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a ( self : Dict ) -> str: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([3, 224, 224] ) lowerCAmelCase__ = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors="np" ) lowerCAmelCase__ = processor(images=SCREAMING_SNAKE_CASE__ , return_tensors="np" ) for key in image_dict.keys(): self.assertAlmostEqual(image_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a ( self : int ) -> Any: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([12_000] ) lowerCAmelCase__ = np.ones([3, 224, 224] ) lowerCAmelCase__ = processor(audio=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , ["audio_values", "audio_mask", "pixel_values", "pixel_mask"] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE__ ): processor() def a ( self : Tuple ) -> Optional[Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( processor.model_input_names , image_processor.model_input_names + feature_extractor.model_input_names , msg="`processor` and `image_processor`+`feature_extractor` model input names do not match" , )
61
1
import json import os import unittest from transformers import OpenAIGPTTokenizer, OpenAIGPTTokenizerFast from transformers.models.openai.tokenization_openai import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_spacy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = OpenAIGPTTokenizer snake_case__ = OpenAIGPTTokenizerFast snake_case__ = True snake_case__ = False def a ( self : Dict ) -> str: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt lowerCAmelCase__ = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "w</w>", "r</w>", "t</w>", "lo", "low", "er</w>", "low</w>", "lowest</w>", "newer</w>", "wider</w>", "<unk>", ] lowerCAmelCase__ = dict(zip(SCREAMING_SNAKE_CASE__ , range(len(SCREAMING_SNAKE_CASE__ ) ) ) ) lowerCAmelCase__ = ["#version: 0.2", "l o", "lo w", "e r</w>", ""] lowerCAmelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) lowerCAmelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE__ ) ) with open(self.merges_file , "w" ) as fp: fp.write("\n".join(SCREAMING_SNAKE_CASE__ ) ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[Any]: return "lower newer", "lower newer" def a ( self : List[str] ) -> Dict: lowerCAmelCase__ = OpenAIGPTTokenizer(self.vocab_file , self.merges_file ) lowerCAmelCase__ = "lower" lowerCAmelCase__ = ["low", "er</w>"] lowerCAmelCase__ = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokens + ["<unk>"] lowerCAmelCase__ = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : Any=15 ) -> Tuple: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): lowerCAmelCase__ = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # Simple input lowerCAmelCase__ = "This is a simple input" lowerCAmelCase__ = ["This is a simple input 1", "This is a simple input 2"] lowerCAmelCase__ = ("This is a simple input", "This is a pair") lowerCAmelCase__ = [ ("This is a simple input 1", "This is a simple input 2"), ("This is a simple pair 1", "This is a simple pair 2"), ] # Simple input tests self.assertRaises(SCREAMING_SNAKE_CASE__ , tokenizer_r.encode , SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , padding="max_length" ) # Simple input self.assertRaises(SCREAMING_SNAKE_CASE__ , tokenizer_r.encode_plus , SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , padding="max_length" ) # Simple input self.assertRaises( SCREAMING_SNAKE_CASE__ , tokenizer_r.batch_encode_plus , SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , padding="max_length" , ) # Pair input self.assertRaises(SCREAMING_SNAKE_CASE__ , tokenizer_r.encode , SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , padding="max_length" ) # Pair input self.assertRaises(SCREAMING_SNAKE_CASE__ , tokenizer_r.encode_plus , SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , padding="max_length" ) # Pair input self.assertRaises( SCREAMING_SNAKE_CASE__ , tokenizer_r.batch_encode_plus , SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , padding="max_length" , ) def a ( self : Optional[int] ) -> int: pass @require_ftfy @require_spacy @require_tokenizers class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" pass
61
import os # Precomputes a list of the 100 first triangular numbers UpperCamelCase = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def _A ( ): """simple docstring""" lowerCAmelCase__ = os.path.dirname(os.path.realpath(lowerCAmelCase_ ) ) lowerCAmelCase__ = os.path.join(lowerCAmelCase_ , "words.txt" ) lowerCAmelCase__ = "" with open(lowerCAmelCase_ ) as f: lowerCAmelCase__ = f.readline() lowerCAmelCase__ = [word.strip("\"" ) for word in words.strip("\r\n" ).split("," )] lowerCAmelCase__ = [ word for word in [sum(ord(lowerCAmelCase_ ) - 64 for x in word ) for word in words] if word in TRIANGULAR_NUMBERS ] return len(lowerCAmelCase_ ) if __name__ == "__main__": print(solution())
61
1
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(): import tensorflow as tf from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING UpperCamelCase = logging.get_logger(__name__) @add_end_docstrings(UpperCamelCase__ ) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def __init__( self : Optional[int] , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : Tuple ) -> Dict: super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) requires_backends(self , "vision" ) self.check_model_type( TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING if self.framework == "tf" else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING ) def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None ) -> Optional[int]: lowerCAmelCase__ = {} if top_k is not None: lowerCAmelCase__ = top_k return {}, {}, postprocess_params def __call__( self : Any , SCREAMING_SNAKE_CASE__ : Union[str, List[str], "Image.Image", List["Image.Image"]] , **SCREAMING_SNAKE_CASE__ : str ) -> Dict: return super().__call__(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Optional[Any]: lowerCAmelCase__ = load_image(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors=self.framework ) return model_inputs def a ( self : int , SCREAMING_SNAKE_CASE__ : int ) -> List[Any]: lowerCAmelCase__ = self.model(**SCREAMING_SNAKE_CASE__ ) return model_outputs def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int=5 ) -> str: if top_k > self.model.config.num_labels: lowerCAmelCase__ = self.model.config.num_labels if self.framework == "pt": lowerCAmelCase__ = model_outputs.logits.softmax(-1 )[0] lowerCAmelCase__ , lowerCAmelCase__ = probs.topk(SCREAMING_SNAKE_CASE__ ) elif self.framework == "tf": lowerCAmelCase__ = stable_softmax(model_outputs.logits , axis=-1 )[0] lowerCAmelCase__ = tf.math.top_k(SCREAMING_SNAKE_CASE__ , k=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ , lowerCAmelCase__ = topk.values.numpy(), topk.indices.numpy() else: raise ValueError(f'Unsupported framework: {self.framework}' ) lowerCAmelCase__ = scores.tolist() lowerCAmelCase__ = ids.tolist() return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )]
61
import random def _A ( lowerCAmelCase_ : Dict , lowerCAmelCase_ : int , lowerCAmelCase_ : Any ): """simple docstring""" lowerCAmelCase__ = a[left_index] lowerCAmelCase__ = left_index + 1 for j in range(left_index + 1 , lowerCAmelCase_ ): if a[j] < pivot: lowerCAmelCase__ , lowerCAmelCase__ = a[i], a[j] i += 1 lowerCAmelCase__ , lowerCAmelCase__ = a[i - 1], a[left_index] return i - 1 def _A ( lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : str ): """simple docstring""" if left < right: lowerCAmelCase__ = random.randint(lowerCAmelCase_ , right - 1 ) lowerCAmelCase__ , lowerCAmelCase__ = ( a[left], a[pivot], ) # switches the pivot with the left most bound lowerCAmelCase__ = partition(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) quick_sort_random( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # recursive quicksort to the left of the pivot point quick_sort_random( lowerCAmelCase_ , pivot_index + 1 , lowerCAmelCase_ ) # recursive quicksort to the right of the pivot point def _A ( ): """simple docstring""" lowerCAmelCase__ = input("Enter numbers separated by a comma:\n" ).strip() lowerCAmelCase__ = [int(lowerCAmelCase_ ) for item in user_input.split("," )] quick_sort_random(lowerCAmelCase_ , 0 , len(lowerCAmelCase_ ) ) print(lowerCAmelCase_ ) if __name__ == "__main__": main()
61
1
def _A ( lowerCAmelCase_ : int = 1000 ): """simple docstring""" return sum(2 * a * ((a - 1) // 2) for a in range(3 , n + 1 ) ) if __name__ == "__main__": print(solution())
61
import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process UpperCamelCase = logging.getLogger(__name__) @dataclass class __lowerCamelCase : """simple docstring""" snake_case__ = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) snake_case__ = field( default="NER" , metadata={"help": "Task type to fine tune in training (e.g. NER, POS, etc)"} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) snake_case__ = field(default=UpperCamelCase__ , metadata={"help": "Set this flag to use fast tokenization."} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) @dataclass class __lowerCamelCase : """simple docstring""" snake_case__ = field( metadata={"help": "The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."} , ) snake_case__ = field( default=1_2_8 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Overwrite the cached training and evaluation sets"} ) def _A ( ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. Use' " --overwrite_output_dir to overcome." ) lowerCAmelCase__ = import_module("tasks" ) try: lowerCAmelCase__ = getattr(lowerCAmelCase_ , model_args.task_type ) lowerCAmelCase__ = token_classification_task_clazz() except AttributeError: raise ValueError( F'Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. ' F'Available tasks classes are: {TokenClassificationTask.__subclasses__()}' ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("Training/evaluation parameters %s" , lowerCAmelCase_ ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task lowerCAmelCase__ = token_classification_task.get_labels(data_args.labels ) lowerCAmelCase__ = dict(enumerate(lowerCAmelCase_ ) ) lowerCAmelCase__ = len(lowerCAmelCase_ ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowerCAmelCase__ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=lowerCAmelCase_ , idalabel=lowerCAmelCase_ , labelaid={label: i for i, label in enumerate(lowerCAmelCase_ )} , cache_dir=model_args.cache_dir , ) lowerCAmelCase__ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast , ) lowerCAmelCase__ = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , ) # Get datasets lowerCAmelCase__ = ( TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) lowerCAmelCase__ = ( TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def align_predictions(lowerCAmelCase_ : np.ndarray , lowerCAmelCase_ : np.ndarray ) -> Tuple[List[int], List[int]]: lowerCAmelCase__ = np.argmax(lowerCAmelCase_ , axis=2 ) lowerCAmelCase__ , lowerCAmelCase__ = preds.shape lowerCAmelCase__ = [[] for _ in range(lowerCAmelCase_ )] lowerCAmelCase__ = [[] for _ in range(lowerCAmelCase_ )] for i in range(lowerCAmelCase_ ): for j in range(lowerCAmelCase_ ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(lowerCAmelCase_ : EvalPrediction ) -> Dict: lowerCAmelCase__ , lowerCAmelCase__ = align_predictions(p.predictions , p.label_ids ) return { "accuracy_score": accuracy_score(lowerCAmelCase_ , lowerCAmelCase_ ), "precision": precision_score(lowerCAmelCase_ , lowerCAmelCase_ ), "recall": recall_score(lowerCAmelCase_ , lowerCAmelCase_ ), "f1": fa_score(lowerCAmelCase_ , lowerCAmelCase_ ), } # Data collator lowerCAmelCase__ = DataCollatorWithPadding(lowerCAmelCase_ , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer lowerCAmelCase__ = Trainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , train_dataset=lowerCAmelCase_ , eval_dataset=lowerCAmelCase_ , compute_metrics=lowerCAmelCase_ , data_collator=lowerCAmelCase_ , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation lowerCAmelCase__ = {} if training_args.do_eval: logger.info("*** Evaluate ***" ) lowerCAmelCase__ = trainer.evaluate() lowerCAmelCase__ = os.path.join(training_args.output_dir , "eval_results.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: logger.info("***** Eval results *****" ) for key, value in result.items(): logger.info(" %s = %s" , lowerCAmelCase_ , lowerCAmelCase_ ) writer.write("%s = %s\n" % (key, value) ) results.update(lowerCAmelCase_ ) # Predict if training_args.do_predict: lowerCAmelCase__ = TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = trainer.predict(lowerCAmelCase_ ) lowerCAmelCase__ , lowerCAmelCase__ = align_predictions(lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ = os.path.join(training_args.output_dir , "test_results.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: for key, value in metrics.items(): logger.info(" %s = %s" , lowerCAmelCase_ , lowerCAmelCase_ ) writer.write("%s = %s\n" % (key, value) ) # Save predictions lowerCAmelCase__ = os.path.join(training_args.output_dir , "test_predictions.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: with open(os.path.join(data_args.data_dir , "test.txt" ) , "r" ) as f: token_classification_task.write_predictions_to_file(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return results def _A ( lowerCAmelCase_ : Tuple ): """simple docstring""" main() if __name__ == "__main__": main()
61
1
import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def __init__( self : List[Any] , *SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> None: warnings.warn( "The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use FlavaImageProcessor instead." , SCREAMING_SNAKE_CASE__ , ) super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
61
import os import re from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'vocab_file': 'spiece.model'} UpperCamelCase = { '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' ), } } UpperCamelCase = { 'google/bigbird-roberta-base': 4096, 'google/bigbird-roberta-large': 4096, 'google/bigbird-base-trivia-itc': 4096, } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ = ["input_ids", "attention_mask"] snake_case__ = [] def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str]="<unk>" , SCREAMING_SNAKE_CASE__ : List[str]="<s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="</s>" , SCREAMING_SNAKE_CASE__ : Tuple="<pad>" , SCREAMING_SNAKE_CASE__ : Any="[SEP]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[MASK]" , SCREAMING_SNAKE_CASE__ : List[Any]="[CLS]" , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None , **SCREAMING_SNAKE_CASE__ : List[Any] , ) -> None: lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else bos_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else eos_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else unk_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else pad_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cls_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else sep_token # Mask token behave like a normal word, i.e. include the space before it lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else mask_token lowerCAmelCase__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = vocab_file lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def a ( self : List[str] ) -> List[str]: return self.sp_model.get_piece_size() def a ( self : List[str] ) -> Dict: lowerCAmelCase__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Optional[int] ) -> Any: lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Any: lowerCAmelCase__ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowerCAmelCase__ = {} lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: return self.sp_model.piece_to_id(SCREAMING_SNAKE_CASE__ ) def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[str]: lowerCAmelCase__ = self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) return token def a ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: lowerCAmelCase__ = [] lowerCAmelCase__ = "" lowerCAmelCase__ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) + token lowerCAmelCase__ = True lowerCAmelCase__ = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) return out_string.strip() def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : bool = True , **SCREAMING_SNAKE_CASE__ : int , ) -> str: lowerCAmelCase__ = kwargs.pop("use_source_tokenizer" , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 lowerCAmelCase__ = [] lowerCAmelCase__ = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = [] sub_texts.append(SCREAMING_SNAKE_CASE__ ) else: current_sub_text.append(SCREAMING_SNAKE_CASE__ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) ) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: lowerCAmelCase__ = re.sub(r" (\[(MASK|SEP)\])" , r"\1" , " ".join(SCREAMING_SNAKE_CASE__ ) ) else: lowerCAmelCase__ = "".join(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: lowerCAmelCase__ = self.clean_up_tokenization(SCREAMING_SNAKE_CASE__ ) return clean_text else: return text def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return lowerCAmelCase__ = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE__ , "wb" ) as fi: lowerCAmelCase__ = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,) def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] lowerCAmelCase__ = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
61
1
import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import BnbQuantizationConfig from .modeling import ( find_tied_parameters, get_balanced_memory, infer_auto_device_map, load_checkpoint_in_model, offload_weight, set_module_tensor_to_device, ) if is_bnb_available(): import bitsandbytes as bnb from copy import deepcopy UpperCamelCase = logging.getLogger(__name__) def _A ( lowerCAmelCase_ : torch.nn.Module , lowerCAmelCase_ : BnbQuantizationConfig , lowerCAmelCase_ : Union[str, os.PathLike] = None , lowerCAmelCase_ : Optional[Dict[str, Union[int, str, torch.device]]] = None , lowerCAmelCase_ : Optional[List[str]] = None , lowerCAmelCase_ : Optional[Dict[Union[int, str], Union[int, str]]] = None , lowerCAmelCase_ : Optional[Union[str, os.PathLike]] = None , lowerCAmelCase_ : bool = False , ): """simple docstring""" lowerCAmelCase__ = bnb_quantization_config.load_in_abit lowerCAmelCase__ = bnb_quantization_config.load_in_abit if load_in_abit and not is_abit_bnb_available(): raise ImportError( "You have a version of `bitsandbytes` that is not compatible with 8bit quantization," " make sure you have the latest version of `bitsandbytes` installed." ) if load_in_abit and not is_abit_bnb_available(): raise ValueError( "You have a version of `bitsandbytes` that is not compatible with 4bit quantization," "make sure you have the latest version of `bitsandbytes` installed." ) lowerCAmelCase__ = [] # custom device map if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) and len(device_map.keys() ) > 1: lowerCAmelCase__ = [key for key, value in device_map.items() if value in ["disk", "cpu"]] # We keep some modules such as the lm_head in their original dtype for numerical stability reasons if bnb_quantization_config.skip_modules is None: lowerCAmelCase__ = get_keys_to_not_convert(lowerCAmelCase_ ) # add cpu modules to skip modules only for 4-bit modules if load_in_abit: bnb_quantization_config.skip_modules.extend(lowerCAmelCase_ ) lowerCAmelCase__ = bnb_quantization_config.skip_modules # We add the modules we want to keep in full precision if bnb_quantization_config.keep_in_fpaa_modules is None: lowerCAmelCase__ = [] lowerCAmelCase__ = bnb_quantization_config.keep_in_fpaa_modules modules_to_not_convert.extend(lowerCAmelCase_ ) # compatibility with peft lowerCAmelCase__ = load_in_abit lowerCAmelCase__ = load_in_abit lowerCAmelCase__ = get_parameter_device(lowerCAmelCase_ ) if model_device.type != "meta": # quantization of an already loaded model logger.warning( "It is not recommended to quantize a loaded model. " "The model should be instantiated under the `init_empty_weights` context manager." ) lowerCAmelCase__ = replace_with_bnb_layers(lowerCAmelCase_ , lowerCAmelCase_ , modules_to_not_convert=lowerCAmelCase_ ) # convert param to the right dtype lowerCAmelCase__ = bnb_quantization_config.torch_dtype for name, param in model.state_dict().items(): if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ): param.to(torch.floataa ) if param.dtype != torch.floataa: lowerCAmelCase__ = name.replace(".weight" , "" ).replace(".bias" , "" ) lowerCAmelCase__ = getattr(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) if param is not None: param.to(torch.floataa ) elif torch.is_floating_point(lowerCAmelCase_ ): param.to(lowerCAmelCase_ ) if model_device.type == "cuda": # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda model.cuda(torch.cuda.current_device() ) torch.cuda.empty_cache() elif torch.cuda.is_available(): model.to(torch.cuda.current_device() ) else: raise RuntimeError("No GPU found. A GPU is needed for quantization." ) logger.info( F'The model device type is {model_device.type}. However, cuda is needed for quantization.' "We move the model to cuda." ) return model elif weights_location is None: raise RuntimeError( F'`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} ' ) else: with init_empty_weights(): lowerCAmelCase__ = replace_with_bnb_layers( lowerCAmelCase_ , lowerCAmelCase_ , modules_to_not_convert=lowerCAmelCase_ ) lowerCAmelCase__ = get_quantized_model_device_map( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , max_memory=lowerCAmelCase_ , no_split_module_classes=lowerCAmelCase_ , ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): lowerCAmelCase__ = True lowerCAmelCase__ = any(x in list(device_map.values() ) for x in ["cpu", "disk"] ) load_checkpoint_in_model( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , dtype=bnb_quantization_config.torch_dtype , offload_folder=lowerCAmelCase_ , offload_state_dict=lowerCAmelCase_ , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , ) return dispatch_model(lowerCAmelCase_ , device_map=lowerCAmelCase_ , offload_dir=lowerCAmelCase_ ) def _A ( lowerCAmelCase_ : List[str] , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Optional[Any]=None , lowerCAmelCase_ : Tuple=None , lowerCAmelCase_ : List[str]=None ): """simple docstring""" if device_map is None: if torch.cuda.is_available(): lowerCAmelCase__ = {"": torch.cuda.current_device()} else: raise RuntimeError("No GPU found. A GPU is needed for quantization." ) logger.info("The device_map was not initialized." "Setting device_map to `{'':torch.cuda.current_device()}`." ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( "If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or " "'sequential'." ) lowerCAmelCase__ = {} special_dtypes.update( { name: bnb_quantization_config.torch_dtype for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.skip_modules ) } ) special_dtypes.update( { name: torch.floataa for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules ) } ) lowerCAmelCase__ = {} lowerCAmelCase__ = special_dtypes lowerCAmelCase__ = no_split_module_classes lowerCAmelCase__ = bnb_quantization_config.target_dtype # get max_memory for each device. if device_map != "sequential": lowerCAmelCase__ = get_balanced_memory( lowerCAmelCase_ , low_zero=(device_map == "balanced_low_0") , max_memory=lowerCAmelCase_ , **lowerCAmelCase_ , ) lowerCAmelCase__ = max_memory lowerCAmelCase__ = infer_auto_device_map(lowerCAmelCase_ , **lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): # check if don't have any quantized module on the cpu lowerCAmelCase__ = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules lowerCAmelCase__ = { key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert } for device in ["cpu", "disk"]: if device in device_map_without_some_modules.values(): if bnb_quantization_config.load_in_abit: raise ValueError( "\n Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n these modules in `torch_dtype`, you need to pass a custom `device_map` to\n `load_and_quantize_model`. Check\n https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n for more details.\n " ) else: logger.info( "Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit" ) del device_map_without_some_modules return device_map def _A ( lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Union[str, Any]=None , lowerCAmelCase_ : Optional[int]=None ): """simple docstring""" if modules_to_not_convert is None: lowerCAmelCase__ = [] lowerCAmelCase__ , lowerCAmelCase__ = _replace_with_bnb_layers( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) if not has_been_replaced: logger.warning( "You are loading your model in 8bit or 4bit but no linear modules were found in your model." " this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers." " Please double check your model architecture, or submit an issue on github if you think this is" " a bug." ) return model def _A ( lowerCAmelCase_ : Any , lowerCAmelCase_ : int , lowerCAmelCase_ : Optional[int]=None , lowerCAmelCase_ : int=None , ): """simple docstring""" lowerCAmelCase__ = False for name, module in model.named_children(): if current_key_name is None: lowerCAmelCase__ = [] current_key_name.append(lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , nn.Linear ) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` lowerCAmelCase__ = ".".join(lowerCAmelCase_ ) lowerCAmelCase__ = True for key in modules_to_not_convert: if ( (key in current_key_name_str) and (key + "." in current_key_name_str) ) or key == current_key_name_str: lowerCAmelCase__ = False break if proceed: # Load bnb module with empty weight and replace ``nn.Linear` module if bnb_quantization_config.load_in_abit: lowerCAmelCase__ = bnb.nn.LinearabitLt( module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=lowerCAmelCase_ , threshold=bnb_quantization_config.llm_inta_threshold , ) elif bnb_quantization_config.load_in_abit: lowerCAmelCase__ = bnb.nn.Linearabit( module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , ) else: raise ValueError("load_in_8bit and load_in_4bit can't be both False" ) lowerCAmelCase__ = module.weight.data if module.bias is not None: lowerCAmelCase__ = module.bias.data bnb_module.requires_grad_(lowerCAmelCase_ ) setattr(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ = True if len(list(module.children() ) ) > 0: lowerCAmelCase__ , lowerCAmelCase__ = _replace_with_bnb_layers( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ = has_been_replaced | _has_been_replaced # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def _A ( lowerCAmelCase_ : Optional[Any] ): """simple docstring""" with init_empty_weights(): lowerCAmelCase__ = deepcopy(lowerCAmelCase_ ) # this has 0 cost since it is done inside `init_empty_weights` context manager` lowerCAmelCase__ = find_tied_parameters(lowerCAmelCase_ ) # For compatibility with Accelerate < 0.18 if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): lowerCAmelCase__ = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: lowerCAmelCase__ = sum(lowerCAmelCase_ , [] ) lowerCAmelCase__ = len(lowerCAmelCase_ ) > 0 # Check if it is a base model lowerCAmelCase__ = False if hasattr(lowerCAmelCase_ , "base_model_prefix" ): lowerCAmelCase__ = not hasattr(lowerCAmelCase_ , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head lowerCAmelCase__ = list(model.named_children() ) lowerCAmelCase__ = [list_modules[-1][0]] # add last module together with tied weights lowerCAmelCase__ = set(lowerCAmelCase_ ) - set(lowerCAmelCase_ ) lowerCAmelCase__ = list(set(lowerCAmelCase_ ) ) + list(lowerCAmelCase_ ) # remove ".weight" from the keys lowerCAmelCase__ = [".weight", ".bias"] lowerCAmelCase__ = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: lowerCAmelCase__ = name.replace(lowerCAmelCase_ , "" ) filtered_module_names.append(lowerCAmelCase_ ) return filtered_module_names def _A ( lowerCAmelCase_ : List[str] ): """simple docstring""" for m in model.modules(): if isinstance(lowerCAmelCase_ , bnb.nn.Linearabit ): return True return False def _A ( lowerCAmelCase_ : nn.Module ): """simple docstring""" return next(parameter.parameters() ).device def _A ( lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : str ): """simple docstring""" if fpaa_statistics is None: set_module_tensor_to_device(lowerCAmelCase_ , lowerCAmelCase_ , 0 , dtype=lowerCAmelCase_ , value=lowerCAmelCase_ ) lowerCAmelCase__ = param_name lowerCAmelCase__ = model if "." in tensor_name: lowerCAmelCase__ = tensor_name.split("." ) for split in splits[:-1]: lowerCAmelCase__ = getattr(lowerCAmelCase_ , lowerCAmelCase_ ) if new_module is None: raise ValueError(F'{module} has no attribute {split}.' ) lowerCAmelCase__ = new_module lowerCAmelCase__ = splits[-1] # offload weights lowerCAmelCase__ = False offload_weight(module._parameters[tensor_name] , lowerCAmelCase_ , lowerCAmelCase_ , index=lowerCAmelCase_ ) if hasattr(module._parameters[tensor_name] , "SCB" ): offload_weight( module._parameters[tensor_name].SCB , param_name.replace("weight" , "SCB" ) , lowerCAmelCase_ , index=lowerCAmelCase_ , ) else: offload_weight(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , index=lowerCAmelCase_ ) offload_weight(lowerCAmelCase_ , param_name.replace("weight" , "SCB" ) , lowerCAmelCase_ , index=lowerCAmelCase_ ) set_module_tensor_to_device(lowerCAmelCase_ , lowerCAmelCase_ , "meta" , dtype=lowerCAmelCase_ , value=torch.empty(*param.size() ) )
61
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { 'sayakpaul/vit-msn-base': 'https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json', # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "vit_msn" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple=768 , SCREAMING_SNAKE_CASE__ : Optional[Any]=12 , SCREAMING_SNAKE_CASE__ : List[str]=12 , SCREAMING_SNAKE_CASE__ : Dict=3_072 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.0 , SCREAMING_SNAKE_CASE__ : int=0.0 , SCREAMING_SNAKE_CASE__ : List[str]=0.02 , SCREAMING_SNAKE_CASE__ : List[str]=1e-0_6 , SCREAMING_SNAKE_CASE__ : Dict=224 , SCREAMING_SNAKE_CASE__ : Optional[int]=16 , SCREAMING_SNAKE_CASE__ : Dict=3 , SCREAMING_SNAKE_CASE__ : Dict=True , **SCREAMING_SNAKE_CASE__ : Tuple , ) -> int: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = initializer_range lowerCAmelCase__ = layer_norm_eps lowerCAmelCase__ = image_size lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = qkv_bias
61
1
import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all feature extractors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...feature_extraction_utils import FeatureExtractionMixin from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = OrderedDict( [ ('audio-spectrogram-transformer', 'ASTFeatureExtractor'), ('beit', 'BeitFeatureExtractor'), ('chinese_clip', 'ChineseCLIPFeatureExtractor'), ('clap', 'ClapFeatureExtractor'), ('clip', 'CLIPFeatureExtractor'), ('clipseg', 'ViTFeatureExtractor'), ('conditional_detr', 'ConditionalDetrFeatureExtractor'), ('convnext', 'ConvNextFeatureExtractor'), ('cvt', 'ConvNextFeatureExtractor'), ('data2vec-audio', 'Wav2Vec2FeatureExtractor'), ('data2vec-vision', 'BeitFeatureExtractor'), ('deformable_detr', 'DeformableDetrFeatureExtractor'), ('deit', 'DeiTFeatureExtractor'), ('detr', 'DetrFeatureExtractor'), ('dinat', 'ViTFeatureExtractor'), ('donut-swin', 'DonutFeatureExtractor'), ('dpt', 'DPTFeatureExtractor'), ('encodec', 'EncodecFeatureExtractor'), ('flava', 'FlavaFeatureExtractor'), ('glpn', 'GLPNFeatureExtractor'), ('groupvit', 'CLIPFeatureExtractor'), ('hubert', 'Wav2Vec2FeatureExtractor'), ('imagegpt', 'ImageGPTFeatureExtractor'), ('layoutlmv2', 'LayoutLMv2FeatureExtractor'), ('layoutlmv3', 'LayoutLMv3FeatureExtractor'), ('levit', 'LevitFeatureExtractor'), ('maskformer', 'MaskFormerFeatureExtractor'), ('mctct', 'MCTCTFeatureExtractor'), ('mobilenet_v1', 'MobileNetV1FeatureExtractor'), ('mobilenet_v2', 'MobileNetV2FeatureExtractor'), ('mobilevit', 'MobileViTFeatureExtractor'), ('nat', 'ViTFeatureExtractor'), ('owlvit', 'OwlViTFeatureExtractor'), ('perceiver', 'PerceiverFeatureExtractor'), ('poolformer', 'PoolFormerFeatureExtractor'), ('regnet', 'ConvNextFeatureExtractor'), ('resnet', 'ConvNextFeatureExtractor'), ('segformer', 'SegformerFeatureExtractor'), ('sew', 'Wav2Vec2FeatureExtractor'), ('sew-d', 'Wav2Vec2FeatureExtractor'), ('speech_to_text', 'Speech2TextFeatureExtractor'), ('speecht5', 'SpeechT5FeatureExtractor'), ('swiftformer', 'ViTFeatureExtractor'), ('swin', 'ViTFeatureExtractor'), ('swinv2', 'ViTFeatureExtractor'), ('table-transformer', 'DetrFeatureExtractor'), ('timesformer', 'VideoMAEFeatureExtractor'), ('tvlt', 'TvltFeatureExtractor'), ('unispeech', 'Wav2Vec2FeatureExtractor'), ('unispeech-sat', 'Wav2Vec2FeatureExtractor'), ('van', 'ConvNextFeatureExtractor'), ('videomae', 'VideoMAEFeatureExtractor'), ('vilt', 'ViltFeatureExtractor'), ('vit', 'ViTFeatureExtractor'), ('vit_mae', 'ViTFeatureExtractor'), ('vit_msn', 'ViTFeatureExtractor'), ('wav2vec2', 'Wav2Vec2FeatureExtractor'), ('wav2vec2-conformer', 'Wav2Vec2FeatureExtractor'), ('wavlm', 'Wav2Vec2FeatureExtractor'), ('whisper', 'WhisperFeatureExtractor'), ('xclip', 'CLIPFeatureExtractor'), ('yolos', 'YolosFeatureExtractor'), ] ) UpperCamelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES) def _A ( lowerCAmelCase_ : str ): """simple docstring""" for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items(): if class_name in extractors: lowerCAmelCase__ = model_type_to_module_name(lowerCAmelCase_ ) lowerCAmelCase__ = importlib.import_module(F'.{module_name}' , "transformers.models" ) try: return getattr(lowerCAmelCase_ , lowerCAmelCase_ ) except AttributeError: continue for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items(): if getattr(lowerCAmelCase_ , "__name__" , lowerCAmelCase_ ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. lowerCAmelCase__ = importlib.import_module("transformers" ) if hasattr(lowerCAmelCase_ , lowerCAmelCase_ ): return getattr(lowerCAmelCase_ , lowerCAmelCase_ ) return None def _A ( lowerCAmelCase_ : Union[str, os.PathLike] , lowerCAmelCase_ : Optional[Union[str, os.PathLike]] = None , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : Optional[Dict[str, str]] = None , lowerCAmelCase_ : Optional[Union[bool, str]] = None , lowerCAmelCase_ : Optional[str] = None , lowerCAmelCase_ : bool = False , **lowerCAmelCase_ : Any , ): """simple docstring""" lowerCAmelCase__ = get_file_from_repo( lowerCAmelCase_ , lowerCAmelCase_ , cache_dir=lowerCAmelCase_ , force_download=lowerCAmelCase_ , resume_download=lowerCAmelCase_ , proxies=lowerCAmelCase_ , use_auth_token=lowerCAmelCase_ , revision=lowerCAmelCase_ , local_files_only=lowerCAmelCase_ , ) if resolved_config_file is None: logger.info( "Could not locate the feature extractor configuration file, will try to use the model config instead." ) return {} with open(lowerCAmelCase_ , encoding="utf-8" ) as reader: return json.load(lowerCAmelCase_ ) class __lowerCamelCase : """simple docstring""" def __init__( self : int ) -> int: raise EnvironmentError( "AutoFeatureExtractor is designed to be instantiated " "using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method." ) @classmethod @replace_list_option_in_docstrings(SCREAMING_SNAKE_CASE__ ) def a ( cls : str , SCREAMING_SNAKE_CASE__ : List[str] , **SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: lowerCAmelCase__ = kwargs.pop("config" , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = kwargs.pop("trust_remote_code" , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = True lowerCAmelCase__ , lowerCAmelCase__ = FeatureExtractionMixin.get_feature_extractor_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = config_dict.get("feature_extractor_type" , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = None if "AutoFeatureExtractor" in config_dict.get("auto_map" , {} ): lowerCAmelCase__ = config_dict["auto_map"]["AutoFeatureExtractor"] # If we don't find the feature extractor class in the feature extractor config, let's try the model config. if feature_extractor_class is None and feature_extractor_auto_map is None: if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # It could be in `config.feature_extractor_type`` lowerCAmelCase__ = getattr(SCREAMING_SNAKE_CASE__ , "feature_extractor_type" , SCREAMING_SNAKE_CASE__ ) if hasattr(SCREAMING_SNAKE_CASE__ , "auto_map" ) and "AutoFeatureExtractor" in config.auto_map: lowerCAmelCase__ = config.auto_map["AutoFeatureExtractor"] if feature_extractor_class is not None: lowerCAmelCase__ = feature_extractor_class_from_name(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = feature_extractor_auto_map is not None lowerCAmelCase__ = feature_extractor_class is not None or type(SCREAMING_SNAKE_CASE__ ) in FEATURE_EXTRACTOR_MAPPING lowerCAmelCase__ = resolve_trust_remote_code( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if has_remote_code and trust_remote_code: lowerCAmelCase__ = get_class_from_dynamic_module( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = kwargs.pop("code_revision" , SCREAMING_SNAKE_CASE__ ) if os.path.isdir(SCREAMING_SNAKE_CASE__ ): feature_extractor_class.register_for_auto_class() return feature_extractor_class.from_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) elif feature_extractor_class is not None: return feature_extractor_class.from_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # Last try: we use the FEATURE_EXTRACTOR_MAPPING. elif type(SCREAMING_SNAKE_CASE__ ) in FEATURE_EXTRACTOR_MAPPING: lowerCAmelCase__ = FEATURE_EXTRACTOR_MAPPING[type(SCREAMING_SNAKE_CASE__ )] return feature_extractor_class.from_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) raise ValueError( f'Unrecognized feature extractor in {pretrained_model_name_or_path}. Should have a ' f'`feature_extractor_type` key in its {FEATURE_EXTRACTOR_NAME} of {CONFIG_NAME}, or one of the following ' f'`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in FEATURE_EXTRACTOR_MAPPING_NAMES.keys() )}' ) @staticmethod def a ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[str] ) -> Union[str, Any]: FEATURE_EXTRACTOR_MAPPING.register(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
61
import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def __init__( self : List[Any] , *SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> None: warnings.warn( "The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use FlavaImageProcessor instead." , SCREAMING_SNAKE_CASE__ , ) super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
61
1
import numpy as np import qiskit def _A ( lowerCAmelCase_ : int = 8 , lowerCAmelCase_ : int | None = None ): """simple docstring""" lowerCAmelCase__ = np.random.default_rng(seed=lowerCAmelCase_ ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. lowerCAmelCase__ = 6 * key_len # Measurement basis for Alice's qubits. lowerCAmelCase__ = rng.integers(2 , size=lowerCAmelCase_ ) # The set of states Alice will prepare. lowerCAmelCase__ = rng.integers(2 , size=lowerCAmelCase_ ) # Measurement basis for Bob's qubits. lowerCAmelCase__ = rng.integers(2 , size=lowerCAmelCase_ ) # Quantum Circuit to simulate BB84 lowerCAmelCase__ = qiskit.QuantumCircuit(lowerCAmelCase_ , name="BB84" ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(lowerCAmelCase_ ): if alice_state[index] == 1: bbaa_circ.x(lowerCAmelCase_ ) if alice_basis[index] == 1: bbaa_circ.h(lowerCAmelCase_ ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(lowerCAmelCase_ ): if bob_basis[index] == 1: bbaa_circ.h(lowerCAmelCase_ ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. lowerCAmelCase__ = qiskit.Aer.get_backend("aer_simulator" ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. lowerCAmelCase__ = qiskit.execute(lowerCAmelCase_ , lowerCAmelCase_ , shots=1 , seed_simulator=lowerCAmelCase_ ) # Returns the result of measurement. lowerCAmelCase__ = job.result().get_counts(lowerCAmelCase_ ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. lowerCAmelCase__ = "".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. lowerCAmelCase__ = gen_key[:key_len] if len(lowerCAmelCase_ ) >= key_len else gen_key.ljust(lowerCAmelCase_ , "0" ) return key if __name__ == "__main__": print(F"""The generated key is : {bbaa(8, seed=0)}""") from doctest import testmod testmod()
61
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import ( BaseOutput, OptionalDependencyNotAvailable, is_flax_available, is_k_diffusion_available, is_k_diffusion_version, is_onnx_available, is_torch_available, is_transformers_available, is_transformers_version, ) @dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_cycle_diffusion import CycleDiffusionPipeline from .pipeline_stable_diffusion import StableDiffusionPipeline from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from .pipeline_stable_unclip import StableUnCLIPPipeline from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline from .safety_checker import StableDiffusionSafetyChecker from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.25.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline else: from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.26.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionPixaPixZeroPipeline, ) else: from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline try: if not ( is_torch_available() and is_transformers_available() and is_k_diffusion_available() and is_k_diffusion_version('>=', '0.0.12') ): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline try: if not (is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_onnx_objects import * # noqa F403 else: from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline if is_transformers_available() and is_flax_available(): import flax @flax.struct.dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline from .safety_checker_flax import FlaxStableDiffusionSafetyChecker
61
1
def _A ( lowerCAmelCase_ : list ): """simple docstring""" lowerCAmelCase__ = False while is_sorted is False: # Until all the indices are traversed keep looping lowerCAmelCase__ = True for i in range(0 , len(lowerCAmelCase_ ) - 1 , 2 ): # iterating over all even indices if input_list[i] > input_list[i + 1]: lowerCAmelCase__ , lowerCAmelCase__ = input_list[i + 1], input_list[i] # swapping if elements not in order lowerCAmelCase__ = False for i in range(1 , len(lowerCAmelCase_ ) - 1 , 2 ): # iterating over all odd indices if input_list[i] > input_list[i + 1]: lowerCAmelCase__ , lowerCAmelCase__ = input_list[i + 1], input_list[i] # swapping if elements not in order lowerCAmelCase__ = False return input_list if __name__ == "__main__": print('Enter list to be sorted') UpperCamelCase = [int(x) for x in input().split()] # inputing elements of the list in one line UpperCamelCase = odd_even_sort(input_list) print('The sorted list is') print(sorted_list)
61
def _A ( lowerCAmelCase_ : int ): """simple docstring""" if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("'float' object cannot be interpreted as an integer" ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("'str' object cannot be interpreted as an integer" ) if num == 0: return "0b0" lowerCAmelCase__ = False if num < 0: lowerCAmelCase__ = True lowerCAmelCase__ = -num lowerCAmelCase__ = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(lowerCAmelCase_ ) for e in binary ) return "0b" + "".join(str(lowerCAmelCase_ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
61
1
import io import json import unittest from parameterized import parameterized from transformers import FSMTForConditionalGeneration, FSMTTokenizer from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device from utils import calculate_bleu UpperCamelCase = get_tests_dir() + '/test_data/fsmt/fsmt_val_data.json' with io.open(filename, 'r', encoding='utf-8') as f: UpperCamelCase = json.load(f) @require_torch class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> str: return FSMTTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str ) -> List[Any]: lowerCAmelCase__ = FSMTForConditionalGeneration.from_pretrained(SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ ) if torch_device == "cuda": model.half() return model @parameterized.expand( [ ["en-ru", 26.0], ["ru-en", 22.0], ["en-de", 22.0], ["de-en", 29.0], ] ) @slow def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Optional[int]: # note: this test is not testing the best performance since it only evals a small batch # but it should be enough to detect a regression in the output quality lowerCAmelCase__ = f'facebook/wmt19-{pair}' lowerCAmelCase__ = self.get_tokenizer(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_model(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = bleu_data[pair]["src"] lowerCAmelCase__ = bleu_data[pair]["tgt"] lowerCAmelCase__ = tokenizer(SCREAMING_SNAKE_CASE__ , return_tensors="pt" , truncation=SCREAMING_SNAKE_CASE__ , padding="longest" ).to(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model.generate( input_ids=batch.input_ids , num_beams=8 , ) lowerCAmelCase__ = tokenizer.batch_decode( SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = calculate_bleu(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) print(SCREAMING_SNAKE_CASE__ ) self.assertGreaterEqual(scores["bleu"] , SCREAMING_SNAKE_CASE__ )
61
from __future__ import annotations UpperCamelCase = '#' class __lowerCamelCase : """simple docstring""" def __init__( self : Dict ) -> None: lowerCAmelCase__ = {} def a ( self : Any , SCREAMING_SNAKE_CASE__ : str ) -> None: lowerCAmelCase__ = self._trie for char in text: if char not in trie: lowerCAmelCase__ = {} lowerCAmelCase__ = trie[char] lowerCAmelCase__ = True def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : str ) -> tuple | list: lowerCAmelCase__ = self._trie for char in prefix: if char in trie: lowerCAmelCase__ = trie[char] else: return [] return self._elements(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : dict ) -> tuple: lowerCAmelCase__ = [] for c, v in d.items(): lowerCAmelCase__ = [" "] if c == END else [(c + s) for s in self._elements(SCREAMING_SNAKE_CASE__ )] result.extend(SCREAMING_SNAKE_CASE__ ) return tuple(SCREAMING_SNAKE_CASE__ ) UpperCamelCase = Trie() UpperCamelCase = ('depart', 'detergent', 'daring', 'dog', 'deer', 'deal') for word in words: trie.insert_word(word) def _A ( lowerCAmelCase_ : str ): """simple docstring""" lowerCAmelCase__ = trie.find_word(lowerCAmelCase_ ) return tuple(string + word for word in suffixes ) def _A ( ): """simple docstring""" print(autocomplete_using_trie("de" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
61
1
import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = VQModel snake_case__ = "sample" @property def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Any=(32, 32) ) -> List[Any]: lowerCAmelCase__ = 4 lowerCAmelCase__ = 3 lowerCAmelCase__ = floats_tensor((batch_size, num_channels) + sizes ).to(SCREAMING_SNAKE_CASE__ ) return {"sample": image} @property def a ( self : Tuple ) -> Dict: return (3, 32, 32) @property def a ( self : Optional[Any] ) -> List[Any]: return (3, 32, 32) def a ( self : Dict ) -> Union[str, Any]: lowerCAmelCase__ = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 3, } lowerCAmelCase__ = self.dummy_input return init_dict, inputs_dict def a ( self : Union[str, Any] ) -> List[str]: pass def a ( self : List[Any] ) -> Dict: pass def a ( self : Union[str, Any] ) -> int: lowerCAmelCase__ , lowerCAmelCase__ = VQModel.from_pretrained("fusing/vqgan-dummy" , output_loading_info=SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def a ( self : List[Any] ) -> str: lowerCAmelCase__ = VQModel.from_pretrained("fusing/vqgan-dummy" ) model.to(SCREAMING_SNAKE_CASE__ ).eval() torch.manual_seed(0 ) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0 ) lowerCAmelCase__ = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size ) lowerCAmelCase__ = image.to(SCREAMING_SNAKE_CASE__ ) with torch.no_grad(): lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ).sample lowerCAmelCase__ = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off lowerCAmelCase__ = torch.tensor([-0.0_153, -0.4_044, -0.1_880, -0.5_161, -0.2_418, -0.4_072, -0.1_612, -0.0_633, -0.0_143] ) # fmt: on self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) )
61
import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, TimesformerForVideoClassification, TimesformerModel, ) from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class __lowerCamelCase : """simple docstring""" def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple=13 , SCREAMING_SNAKE_CASE__ : Optional[Any]=10 , SCREAMING_SNAKE_CASE__ : Optional[int]=3 , SCREAMING_SNAKE_CASE__ : List[str]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=2 , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : Optional[int]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : List[Any]=37 , SCREAMING_SNAKE_CASE__ : int="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Any=10 , SCREAMING_SNAKE_CASE__ : int=0.02 , SCREAMING_SNAKE_CASE__ : Tuple="divided_space_time" , SCREAMING_SNAKE_CASE__ : Optional[int]=None , ) -> List[str]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = image_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_frames lowerCAmelCase__ = is_training lowerCAmelCase__ = use_labels lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = attention_type lowerCAmelCase__ = initializer_range lowerCAmelCase__ = scope lowerCAmelCase__ = num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token lowerCAmelCase__ = (image_size // patch_size) ** 2 lowerCAmelCase__ = (num_frames) * self.num_patches_per_frame + 1 def a ( self : int ) -> Tuple: lowerCAmelCase__ = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase__ = None if self.use_labels: lowerCAmelCase__ = ids_tensor([self.batch_size] , self.num_labels ) lowerCAmelCase__ = self.get_config() return config, pixel_values, labels def a ( self : List[Any] ) -> Any: lowerCAmelCase__ = TimesformerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , initializer_range=self.initializer_range , attention_type=self.attention_type , ) lowerCAmelCase__ = self.num_labels return config def a ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: lowerCAmelCase__ = TimesformerModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple ) -> Tuple: lowerCAmelCase__ = TimesformerForVideoClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) # verify the logits shape lowerCAmelCase__ = torch.Size((self.batch_size, self.num_labels) ) self.parent.assertEqual(result.logits.shape , SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> Dict: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else () snake_case__ = ( {"feature-extraction": TimesformerModel, "video-classification": TimesformerForVideoClassification} if is_torch_available() else {} ) snake_case__ = False snake_case__ = False snake_case__ = False snake_case__ = False def a ( self : List[str] ) -> List[Any]: lowerCAmelCase__ = TimesformerModelTester(self ) lowerCAmelCase__ = ConfigTester( self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ , hidden_size=37 ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple=False ) -> str: lowerCAmelCase__ = copy.deepcopy(SCREAMING_SNAKE_CASE__ ) if return_labels: if model_class in get_values(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) return inputs_dict def a ( self : Optional[Any] ) -> List[str]: self.config_tester.run_common_tests() @unittest.skip(reason="TimeSformer does not use inputs_embeds" ) def a ( self : Union[str, Any] ) -> Tuple: pass def a ( self : Dict ) -> List[str]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowerCAmelCase__ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__ , nn.Linear ) ) def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase__ = [*signature.parameters.keys()] lowerCAmelCase__ = ["pixel_values"] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] ) -> Tuple: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*SCREAMING_SNAKE_CASE__ ) @slow def a ( self : str ) -> Tuple: for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase__ = TimesformerModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Dict: if not self.has_attentions: pass else: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ = True for model_class in self.all_model_classes: lowerCAmelCase__ = self.model_tester.seq_length lowerCAmelCase__ = self.model_tester.num_frames lowerCAmelCase__ = True lowerCAmelCase__ = False lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) lowerCAmelCase__ = len(SCREAMING_SNAKE_CASE__ ) # Check attention is always last and order is fine lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(out_len + 1 , len(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) def a ( self : List[str] ) -> Any: def check_hidden_states_output(SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] ): lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.hidden_states lowerCAmelCase__ = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _A ( ): """simple docstring""" lowerCAmelCase__ = hf_hub_download( repo_id="hf-internal-testing/spaghetti-video" , filename="eating_spaghetti.npy" , repo_type="dataset" ) lowerCAmelCase__ = np.load(lowerCAmelCase_ ) return list(lowerCAmelCase_ ) @require_torch @require_vision class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @cached_property def a ( self : Optional[Any] ) -> Union[str, Any]: # logits were tested with a different mean and std, so we use the same here return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) if is_vision_available() else None ) @slow def a ( self : Optional[Any] ) -> str: lowerCAmelCase__ = TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400" ).to( SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.default_image_processor lowerCAmelCase__ = prepare_video() lowerCAmelCase__ = image_processor(video[:8] , return_tensors="pt" ).to(SCREAMING_SNAKE_CASE__ ) # forward pass with torch.no_grad(): lowerCAmelCase__ = model(**SCREAMING_SNAKE_CASE__ ) # verify the logits lowerCAmelCase__ = torch.Size((1, 400) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = torch.tensor([-0.3_016, -0.7_713, -0.4_205] ).to(SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
1
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary # Register SEW's fairseq modules from sew_asapp import tasks # noqa: F401 from transformers import ( SEWConfig, SEWForCTC, SEWModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { 'post_extract_proj': 'feature_projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.upsample.0': 'encoder.upsample.projection', 'encoder.layer_norm': 'encoder.layer_norm', 'w2v_model.layer_norm': 'layer_norm', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', } def _A ( lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : Dict , lowerCAmelCase_ : str , lowerCAmelCase_ : str , lowerCAmelCase_ : str ): """simple docstring""" for attribute in key.split("." ): lowerCAmelCase__ = getattr(lowerCAmelCase_ , lowerCAmelCase_ ) if weight_type is not None: lowerCAmelCase__ = getattr(lowerCAmelCase_ , lowerCAmelCase_ ).shape else: lowerCAmelCase__ = hf_pointer.shape assert hf_shape == value.shape, ( F'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be' F' {value.shape} for {full_name}' ) if weight_type == "weight": lowerCAmelCase__ = value elif weight_type == "weight_g": lowerCAmelCase__ = value elif weight_type == "weight_v": lowerCAmelCase__ = value elif weight_type == "bias": lowerCAmelCase__ = value else: lowerCAmelCase__ = value logger.info(F'{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.' ) def _A ( lowerCAmelCase_ : str , lowerCAmelCase_ : Any , lowerCAmelCase_ : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = [] lowerCAmelCase__ = fairseq_model.state_dict() lowerCAmelCase__ = hf_model.sew.feature_extractor if is_finetuned else hf_model.feature_extractor for name, value in fairseq_dict.items(): lowerCAmelCase__ = False if "conv_layers" in name: load_conv_layer( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , hf_model.config.feat_extract_norm == "group" , ) lowerCAmelCase__ = True else: for key, mapped_key in MAPPING.items(): lowerCAmelCase__ = "sew." + mapped_key if (is_finetuned and mapped_key != "lm_head") else mapped_key if key in name or key.split("w2v_model." )[-1] == name.split("." )[0]: lowerCAmelCase__ = True if "*" in mapped_key: lowerCAmelCase__ = name.split(lowerCAmelCase_ )[0].split("." )[-2] lowerCAmelCase__ = mapped_key.replace("*" , lowerCAmelCase_ ) if "weight_g" in name: lowerCAmelCase__ = "weight_g" elif "weight_v" in name: lowerCAmelCase__ = "weight_v" elif "weight" in name: lowerCAmelCase__ = "weight" elif "bias" in name: lowerCAmelCase__ = "bias" else: lowerCAmelCase__ = None set_recursively(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) continue if not is_used: unused_weights.append(lowerCAmelCase_ ) logger.warning(F'Unused weights: {unused_weights}' ) def _A ( lowerCAmelCase_ : Any , lowerCAmelCase_ : str , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : str ): """simple docstring""" lowerCAmelCase__ = full_name.split("conv_layers." )[-1] lowerCAmelCase__ = name.split("." ) lowerCAmelCase__ = int(items[0] ) lowerCAmelCase__ = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.' ) lowerCAmelCase__ = value logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.' ) lowerCAmelCase__ = value logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F'{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was' " found." ) lowerCAmelCase__ = value logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F'{full_name} has size {value.shape}, but' F' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.' ) lowerCAmelCase__ = value logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) else: unused_weights.append(lowerCAmelCase_ ) def _A ( lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : Tuple ): """simple docstring""" lowerCAmelCase__ = SEWConfig() if is_finetuned: lowerCAmelCase__ = model.wav_encoder.wav_model.cfg else: lowerCAmelCase__ = model.cfg lowerCAmelCase__ = fs_config.conv_bias lowerCAmelCase__ = eval(fs_config.conv_feature_layers ) lowerCAmelCase__ = [x[0] for x in conv_layers] lowerCAmelCase__ = [x[1] for x in conv_layers] lowerCAmelCase__ = [x[2] for x in conv_layers] lowerCAmelCase__ = "gelu" lowerCAmelCase__ = "layer" if fs_config.extractor_mode == "layer_norm" else "group" lowerCAmelCase__ = 0.0 lowerCAmelCase__ = fs_config.activation_fn.name lowerCAmelCase__ = fs_config.encoder_embed_dim lowerCAmelCase__ = 0.02 lowerCAmelCase__ = fs_config.encoder_ffn_embed_dim lowerCAmelCase__ = 1E-5 lowerCAmelCase__ = fs_config.encoder_layerdrop lowerCAmelCase__ = fs_config.encoder_attention_heads lowerCAmelCase__ = fs_config.conv_pos_groups lowerCAmelCase__ = fs_config.conv_pos lowerCAmelCase__ = len(lowerCAmelCase_ ) lowerCAmelCase__ = fs_config.encoder_layers lowerCAmelCase__ = fs_config.squeeze_factor # take care of any params that are overridden by the Wav2VecCtc model if is_finetuned: lowerCAmelCase__ = model.cfg lowerCAmelCase__ = fs_config.final_dropout lowerCAmelCase__ = fs_config.layerdrop lowerCAmelCase__ = fs_config.activation_dropout lowerCAmelCase__ = fs_config.mask_prob > 0 or fs_config.mask_channel_prob > 0 lowerCAmelCase__ = fs_config.attention_dropout lowerCAmelCase__ = fs_config.dropout_input lowerCAmelCase__ = fs_config.dropout lowerCAmelCase__ = fs_config.mask_channel_length lowerCAmelCase__ = fs_config.mask_channel_prob lowerCAmelCase__ = fs_config.mask_length lowerCAmelCase__ = fs_config.mask_prob lowerCAmelCase__ = "Wav2Vec2FeatureExtractor" lowerCAmelCase__ = "Wav2Vec2CTCTokenizer" return config @torch.no_grad() def _A ( lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : Union[str, Any]=None , lowerCAmelCase_ : Dict=None , lowerCAmelCase_ : Optional[int]=True ): """simple docstring""" if is_finetuned: lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"data": "/".join(dict_path.split("/" )[:-1] )} ) else: lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) if config_path is not None: lowerCAmelCase__ = SEWConfig.from_pretrained(lowerCAmelCase_ ) else: lowerCAmelCase__ = convert_config(model[0] , lowerCAmelCase_ ) lowerCAmelCase__ = model[0].eval() lowerCAmelCase__ = True if config.feat_extract_norm == "layer" else False lowerCAmelCase__ = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6000 , padding_value=0 , do_normalize=lowerCAmelCase_ , return_attention_mask=lowerCAmelCase_ , ) if is_finetuned: if dict_path: lowerCAmelCase__ = Dictionary.load(lowerCAmelCase_ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq lowerCAmelCase__ = target_dict.pad_index lowerCAmelCase__ = target_dict.bos_index lowerCAmelCase__ = target_dict.pad_index lowerCAmelCase__ = target_dict.bos_index lowerCAmelCase__ = target_dict.eos_index lowerCAmelCase__ = len(target_dict.symbols ) lowerCAmelCase__ = os.path.join(lowerCAmelCase_ , "vocab.json" ) if not os.path.isdir(lowerCAmelCase_ ): logger.error("--pytorch_dump_folder_path ({}) should be a directory".format(lowerCAmelCase_ ) ) return os.makedirs(lowerCAmelCase_ , exist_ok=lowerCAmelCase_ ) with open(lowerCAmelCase_ , "w" , encoding="utf-8" ) as vocab_handle: json.dump(target_dict.indices , lowerCAmelCase_ ) lowerCAmelCase__ = WavaVecaCTCTokenizer( lowerCAmelCase_ , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="|" , do_lower_case=lowerCAmelCase_ , ) lowerCAmelCase__ = WavaVecaProcessor(feature_extractor=lowerCAmelCase_ , tokenizer=lowerCAmelCase_ ) processor.save_pretrained(lowerCAmelCase_ ) lowerCAmelCase__ = SEWForCTC(lowerCAmelCase_ ) else: lowerCAmelCase__ = SEWModel(lowerCAmelCase_ ) feature_extractor.save_pretrained(lowerCAmelCase_ ) recursively_load_weights(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) hf_model.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--is_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not' ) UpperCamelCase = parser.parse_args() convert_sew_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, args.is_finetuned )
61
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _A ( ): """simple docstring""" lowerCAmelCase__ = ArgumentParser( description=( "PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes" ) ) # Optional arguments for the launch helper parser.add_argument("--num_cores" , type=lowerCAmelCase_ , default=1 , help="Number of TPU cores to use (1 or 8)." ) # positional parser.add_argument( "training_script" , type=lowerCAmelCase_ , help=( "The full path to the single TPU training " "program/script to be launched in parallel, " "followed by all the arguments for the " "training script" ) , ) # rest from the training program parser.add_argument("training_script_args" , nargs=lowerCAmelCase_ ) return parser.parse_args() def _A ( ): """simple docstring""" lowerCAmelCase__ = parse_args() # Import training_script as a module. lowerCAmelCase__ = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) lowerCAmelCase__ = script_fpath.stem lowerCAmelCase__ = importlib.import_module(lowerCAmelCase_ ) # Patch sys.argv lowerCAmelCase__ = [args.training_script] + args.training_script_args + ["--tpu_num_cores", str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
61
1
# Usage: # ./gen-card-facebook-wmt19.py import os from pathlib import Path def _A ( lowerCAmelCase_ : str , lowerCAmelCase_ : Dict , lowerCAmelCase_ : int ): """simple docstring""" lowerCAmelCase__ = { "en": "Machine learning is great, isn't it?", "ru": "Машинное обучение - это здорово, не так ли?", "de": "Maschinelles Lernen ist großartig, oder?", } # BLUE scores as follows: # "pair": [fairseq, transformers] lowerCAmelCase__ = { "ru-en": ["[41.3](http://matrix.statmt.org/matrix/output/1907?run_id=6937)", "39.20"], "en-ru": ["[36.4](http://matrix.statmt.org/matrix/output/1914?run_id=6724)", "33.47"], "en-de": ["[43.1](http://matrix.statmt.org/matrix/output/1909?run_id=6862)", "42.83"], "de-en": ["[42.3](http://matrix.statmt.org/matrix/output/1902?run_id=6750)", "41.35"], } lowerCAmelCase__ = F'{src_lang}-{tgt_lang}' lowerCAmelCase__ = F'\n---\nlanguage: \n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt19\n- facebook\nlicense: apache-2.0\ndatasets:\n- wmt19\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of [fairseq wmt19 transformer](https://github.com/pytorch/fairseq/blob/master/examples/wmt19/README.md) for {src_lang}-{tgt_lang}.\n\nFor more details, please see, [Facebook FAIR\'s WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616).\n\nThe abbreviation FSMT stands for FairSeqMachineTranslation\n\nAll four models are available:\n\n* [wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru)\n* [wmt19-ru-en](https://huggingface.co/facebook/wmt19-ru-en)\n* [wmt19-en-de](https://huggingface.co/facebook/wmt19-en-de)\n* [wmt19-de-en](https://huggingface.co/facebook/wmt19-de-en)\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = "facebook/wmt19-{src_lang}-{tgt_lang}"\ntokenizer = FSMTTokenizer.from_pretrained(mname)\nmodel = FSMTForConditionalGeneration.from_pretrained(mname)\n\ninput = "{texts[src_lang]}"\ninput_ids = tokenizer.encode(input, return_tensors="pt")\noutputs = model.generate(input_ids)\ndecoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(decoded) # {texts[tgt_lang]}\n\n```\n\n#### Limitations and bias\n\n- The original (and this ported model) doesn\'t seem to handle well inputs with repeated sub-phrases, [content gets truncated](https://discuss.huggingface.co/t/issues-with-translating-inputs-containing-repeated-phrases/981)\n\n## Training data\n\nPretrained weights were left identical to the original model released by fairseq. For more details, please, see the [paper](https://arxiv.org/abs/1907.06616).\n\n## Eval results\n\npair | fairseq | transformers\n-------|---------|----------\n{pair} | {scores[pair][0]} | {scores[pair][1]}\n\nThe score is slightly below the score reported by `fairseq`, since `transformers`` currently doesn\'t support:\n- model ensemble, therefore the best performing checkpoint was ported (``model4.pt``).\n- re-ranking\n\nThe score was calculated using this code:\n\n```bash\ngit clone https://github.com/huggingface/transformers\ncd transformers\nexport PAIR={pair}\nexport DATA_DIR=data/$PAIR\nexport SAVE_DIR=data/$PAIR\nexport BS=8\nexport NUM_BEAMS=15\nmkdir -p $DATA_DIR\nsacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target\necho $PAIR\nPYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS\n```\nnote: fairseq reports using a beam of 50, so you should get a slightly higher score if re-run with `--num_beams 50`.\n\n## Data Sources\n\n- [training, etc.](http://www.statmt.org/wmt19/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561)\n\n\n### BibTeX entry and citation info\n\n```bibtex\n@inproceedings{{...,\n year={{2020}},\n title={{Facebook FAIR\'s WMT19 News Translation Task Submission}},\n author={{Ng, Nathan and Yee, Kyra and Baevski, Alexei and Ott, Myle and Auli, Michael and Edunov, Sergey}},\n booktitle={{Proc. of WMT}},\n}}\n```\n\n\n## TODO\n\n- port model ensemble (fairseq uses 4 model checkpoints)\n\n' os.makedirs(lowerCAmelCase_ , exist_ok=lowerCAmelCase_ ) lowerCAmelCase__ = os.path.join(lowerCAmelCase_ , "README.md" ) print(F'Generating {path}' ) with open(lowerCAmelCase_ , "w" , encoding="utf-8" ) as f: f.write(lowerCAmelCase_ ) # make sure we are under the root of the project UpperCamelCase = Path(__file__).resolve().parent.parent.parent UpperCamelCase = repo_dir / 'model_cards' for model_name in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: UpperCamelCase , UpperCamelCase , UpperCamelCase = model_name.split('-') UpperCamelCase = model_cards_dir / 'facebook' / model_name write_model_card(model_card_dir, src_lang=src_lang, tgt_lang=tgt_lang)
61
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool UpperCamelCase = { 'Acehnese Arabic': 'ace_Arab', 'Acehnese Latin': 'ace_Latn', 'Mesopotamian Arabic': 'acm_Arab', 'Ta\'izzi-Adeni Arabic': 'acq_Arab', 'Tunisian Arabic': 'aeb_Arab', 'Afrikaans': 'afr_Latn', 'South Levantine Arabic': 'ajp_Arab', 'Akan': 'aka_Latn', 'Amharic': 'amh_Ethi', 'North Levantine Arabic': 'apc_Arab', 'Modern Standard Arabic': 'arb_Arab', 'Modern Standard Arabic Romanized': 'arb_Latn', 'Najdi Arabic': 'ars_Arab', 'Moroccan Arabic': 'ary_Arab', 'Egyptian Arabic': 'arz_Arab', 'Assamese': 'asm_Beng', 'Asturian': 'ast_Latn', 'Awadhi': 'awa_Deva', 'Central Aymara': 'ayr_Latn', 'South Azerbaijani': 'azb_Arab', 'North Azerbaijani': 'azj_Latn', 'Bashkir': 'bak_Cyrl', 'Bambara': 'bam_Latn', 'Balinese': 'ban_Latn', 'Belarusian': 'bel_Cyrl', 'Bemba': 'bem_Latn', 'Bengali': 'ben_Beng', 'Bhojpuri': 'bho_Deva', 'Banjar Arabic': 'bjn_Arab', 'Banjar Latin': 'bjn_Latn', 'Standard Tibetan': 'bod_Tibt', 'Bosnian': 'bos_Latn', 'Buginese': 'bug_Latn', 'Bulgarian': 'bul_Cyrl', 'Catalan': 'cat_Latn', 'Cebuano': 'ceb_Latn', 'Czech': 'ces_Latn', 'Chokwe': 'cjk_Latn', 'Central Kurdish': 'ckb_Arab', 'Crimean Tatar': 'crh_Latn', 'Welsh': 'cym_Latn', 'Danish': 'dan_Latn', 'German': 'deu_Latn', 'Southwestern Dinka': 'dik_Latn', 'Dyula': 'dyu_Latn', 'Dzongkha': 'dzo_Tibt', 'Greek': 'ell_Grek', 'English': 'eng_Latn', 'Esperanto': 'epo_Latn', 'Estonian': 'est_Latn', 'Basque': 'eus_Latn', 'Ewe': 'ewe_Latn', 'Faroese': 'fao_Latn', 'Fijian': 'fij_Latn', 'Finnish': 'fin_Latn', 'Fon': 'fon_Latn', 'French': 'fra_Latn', 'Friulian': 'fur_Latn', 'Nigerian Fulfulde': 'fuv_Latn', 'Scottish Gaelic': 'gla_Latn', 'Irish': 'gle_Latn', 'Galician': 'glg_Latn', 'Guarani': 'grn_Latn', 'Gujarati': 'guj_Gujr', 'Haitian Creole': 'hat_Latn', 'Hausa': 'hau_Latn', 'Hebrew': 'heb_Hebr', 'Hindi': 'hin_Deva', 'Chhattisgarhi': 'hne_Deva', 'Croatian': 'hrv_Latn', 'Hungarian': 'hun_Latn', 'Armenian': 'hye_Armn', 'Igbo': 'ibo_Latn', 'Ilocano': 'ilo_Latn', 'Indonesian': 'ind_Latn', 'Icelandic': 'isl_Latn', 'Italian': 'ita_Latn', 'Javanese': 'jav_Latn', 'Japanese': 'jpn_Jpan', 'Kabyle': 'kab_Latn', 'Jingpho': 'kac_Latn', 'Kamba': 'kam_Latn', 'Kannada': 'kan_Knda', 'Kashmiri Arabic': 'kas_Arab', 'Kashmiri Devanagari': 'kas_Deva', 'Georgian': 'kat_Geor', 'Central Kanuri Arabic': 'knc_Arab', 'Central Kanuri Latin': 'knc_Latn', 'Kazakh': 'kaz_Cyrl', 'Kabiyè': 'kbp_Latn', 'Kabuverdianu': 'kea_Latn', 'Khmer': 'khm_Khmr', 'Kikuyu': 'kik_Latn', 'Kinyarwanda': 'kin_Latn', 'Kyrgyz': 'kir_Cyrl', 'Kimbundu': 'kmb_Latn', 'Northern Kurdish': 'kmr_Latn', 'Kikongo': 'kon_Latn', 'Korean': 'kor_Hang', 'Lao': 'lao_Laoo', 'Ligurian': 'lij_Latn', 'Limburgish': 'lim_Latn', 'Lingala': 'lin_Latn', 'Lithuanian': 'lit_Latn', 'Lombard': 'lmo_Latn', 'Latgalian': 'ltg_Latn', 'Luxembourgish': 'ltz_Latn', 'Luba-Kasai': 'lua_Latn', 'Ganda': 'lug_Latn', 'Luo': 'luo_Latn', 'Mizo': 'lus_Latn', 'Standard Latvian': 'lvs_Latn', 'Magahi': 'mag_Deva', 'Maithili': 'mai_Deva', 'Malayalam': 'mal_Mlym', 'Marathi': 'mar_Deva', 'Minangkabau Arabic ': 'min_Arab', 'Minangkabau Latin': 'min_Latn', 'Macedonian': 'mkd_Cyrl', 'Plateau Malagasy': 'plt_Latn', 'Maltese': 'mlt_Latn', 'Meitei Bengali': 'mni_Beng', 'Halh Mongolian': 'khk_Cyrl', 'Mossi': 'mos_Latn', 'Maori': 'mri_Latn', 'Burmese': 'mya_Mymr', 'Dutch': 'nld_Latn', 'Norwegian Nynorsk': 'nno_Latn', 'Norwegian Bokmål': 'nob_Latn', 'Nepali': 'npi_Deva', 'Northern Sotho': 'nso_Latn', 'Nuer': 'nus_Latn', 'Nyanja': 'nya_Latn', 'Occitan': 'oci_Latn', 'West Central Oromo': 'gaz_Latn', 'Odia': 'ory_Orya', 'Pangasinan': 'pag_Latn', 'Eastern Panjabi': 'pan_Guru', 'Papiamento': 'pap_Latn', 'Western Persian': 'pes_Arab', 'Polish': 'pol_Latn', 'Portuguese': 'por_Latn', 'Dari': 'prs_Arab', 'Southern Pashto': 'pbt_Arab', 'Ayacucho Quechua': 'quy_Latn', 'Romanian': 'ron_Latn', 'Rundi': 'run_Latn', 'Russian': 'rus_Cyrl', 'Sango': 'sag_Latn', 'Sanskrit': 'san_Deva', 'Santali': 'sat_Olck', 'Sicilian': 'scn_Latn', 'Shan': 'shn_Mymr', 'Sinhala': 'sin_Sinh', 'Slovak': 'slk_Latn', 'Slovenian': 'slv_Latn', 'Samoan': 'smo_Latn', 'Shona': 'sna_Latn', 'Sindhi': 'snd_Arab', 'Somali': 'som_Latn', 'Southern Sotho': 'sot_Latn', 'Spanish': 'spa_Latn', 'Tosk Albanian': 'als_Latn', 'Sardinian': 'srd_Latn', 'Serbian': 'srp_Cyrl', 'Swati': 'ssw_Latn', 'Sundanese': 'sun_Latn', 'Swedish': 'swe_Latn', 'Swahili': 'swh_Latn', 'Silesian': 'szl_Latn', 'Tamil': 'tam_Taml', 'Tatar': 'tat_Cyrl', 'Telugu': 'tel_Telu', 'Tajik': 'tgk_Cyrl', 'Tagalog': 'tgl_Latn', 'Thai': 'tha_Thai', 'Tigrinya': 'tir_Ethi', 'Tamasheq Latin': 'taq_Latn', 'Tamasheq Tifinagh': 'taq_Tfng', 'Tok Pisin': 'tpi_Latn', 'Tswana': 'tsn_Latn', 'Tsonga': 'tso_Latn', 'Turkmen': 'tuk_Latn', 'Tumbuka': 'tum_Latn', 'Turkish': 'tur_Latn', 'Twi': 'twi_Latn', 'Central Atlas Tamazight': 'tzm_Tfng', 'Uyghur': 'uig_Arab', 'Ukrainian': 'ukr_Cyrl', 'Umbundu': 'umb_Latn', 'Urdu': 'urd_Arab', 'Northern Uzbek': 'uzn_Latn', 'Venetian': 'vec_Latn', 'Vietnamese': 'vie_Latn', 'Waray': 'war_Latn', 'Wolof': 'wol_Latn', 'Xhosa': 'xho_Latn', 'Eastern Yiddish': 'ydd_Hebr', 'Yoruba': 'yor_Latn', 'Yue Chinese': 'yue_Hant', 'Chinese Simplified': 'zho_Hans', 'Chinese Traditional': 'zho_Hant', 'Standard Malay': 'zsm_Latn', 'Zulu': 'zul_Latn', } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "facebook/nllb-200-distilled-600M" snake_case__ = ( "This is a tool that translates text from a language to another. It takes three inputs: `text`, which should " "be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, " "which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in " "plain English, such as 'Romanian', or 'Albanian'. It returns the text translated in `tgt_lang`." ) snake_case__ = "translator" snake_case__ = AutoTokenizer snake_case__ = AutoModelForSeqaSeqLM snake_case__ = LANGUAGE_CODES snake_case__ = ["text", "text", "text"] snake_case__ = ["text"] def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: if src_lang not in self.lang_to_code: raise ValueError(f'{src_lang} is not a supported language.' ) if tgt_lang not in self.lang_to_code: raise ValueError(f'{tgt_lang} is not a supported language.' ) lowerCAmelCase__ = self.lang_to_code[src_lang] lowerCAmelCase__ = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( SCREAMING_SNAKE_CASE__ , return_tensors="pt" , src_lang=SCREAMING_SNAKE_CASE__ , tgt_lang=SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: return self.model.generate(**SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[str]: return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=SCREAMING_SNAKE_CASE__ )
61
1
UpperCamelCase = frozenset( [ 'prompt', 'height', 'width', 'guidance_scale', 'negative_prompt', 'prompt_embeds', 'negative_prompt_embeds', 'cross_attention_kwargs', ] ) UpperCamelCase = frozenset(['prompt', 'negative_prompt']) UpperCamelCase = frozenset([]) UpperCamelCase = frozenset(['image']) UpperCamelCase = frozenset( [ 'image', 'height', 'width', 'guidance_scale', ] ) UpperCamelCase = frozenset(['image']) UpperCamelCase = frozenset( [ 'prompt', 'image', 'height', 'width', 'guidance_scale', 'negative_prompt', 'prompt_embeds', 'negative_prompt_embeds', ] ) UpperCamelCase = frozenset(['prompt', 'image', 'negative_prompt']) UpperCamelCase = frozenset( [ # Text guided image variation with an image mask 'prompt', 'image', 'mask_image', 'height', 'width', 'guidance_scale', 'negative_prompt', 'prompt_embeds', 'negative_prompt_embeds', ] ) UpperCamelCase = frozenset(['prompt', 'image', 'mask_image', 'negative_prompt']) UpperCamelCase = frozenset( [ # image variation with an image mask 'image', 'mask_image', 'height', 'width', 'guidance_scale', ] ) UpperCamelCase = frozenset(['image', 'mask_image']) UpperCamelCase = frozenset( [ 'example_image', 'image', 'mask_image', 'height', 'width', 'guidance_scale', ] ) UpperCamelCase = frozenset(['example_image', 'image', 'mask_image']) UpperCamelCase = frozenset(['class_labels']) UpperCamelCase = frozenset(['class_labels']) UpperCamelCase = frozenset(['batch_size']) UpperCamelCase = frozenset([]) UpperCamelCase = frozenset(['batch_size']) UpperCamelCase = frozenset([]) UpperCamelCase = frozenset( [ 'prompt', 'audio_length_in_s', 'guidance_scale', 'negative_prompt', 'prompt_embeds', 'negative_prompt_embeds', 'cross_attention_kwargs', ] ) UpperCamelCase = frozenset(['prompt', 'negative_prompt']) UpperCamelCase = frozenset(['input_tokens']) UpperCamelCase = frozenset(['input_tokens'])
61
import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = VideoToVideoSDPipeline snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"video"} ) - {"image", "width", "height"} snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"video"} ) - {"image"} snake_case__ = PipelineTesterMixin.required_optional_params - {"latents"} snake_case__ = False # No `output_type`. snake_case__ = frozenset( [ "num_inference_steps", "generator", "latents", "return_dict", "callback", "callback_steps", ] ) def a ( self : int ) -> Optional[int]: torch.manual_seed(0 ) lowerCAmelCase__ = 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 , ) lowerCAmelCase__ = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=SCREAMING_SNAKE_CASE__ , set_alpha_to_one=SCREAMING_SNAKE_CASE__ , ) torch.manual_seed(0 ) lowerCAmelCase__ = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) lowerCAmelCase__ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="gelu" , projection_dim=512 , ) lowerCAmelCase__ = CLIPTextModel(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) lowerCAmelCase__ = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, } return components def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Dict=0 ) -> Tuple: # 3 frames lowerCAmelCase__ = floats_tensor((1, 3, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) if str(SCREAMING_SNAKE_CASE__ ).startswith("mps" ): lowerCAmelCase__ = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: lowerCAmelCase__ = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = { "prompt": "A painting of a squirrel eating a burger", "video": video, "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "pt", } return inputs def a ( self : Union[str, Any] ) -> str: lowerCAmelCase__ = "cpu" # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ = self.get_dummy_components() lowerCAmelCase__ = VideoToVideoSDPipeline(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = "np" lowerCAmelCase__ = sd_pipe(**SCREAMING_SNAKE_CASE__ ).frames lowerCAmelCase__ = frames[0][-3:, -3:, -1] assert frames[0].shape == (32, 32, 3) lowerCAmelCase__ = np.array([106, 117, 113, 174, 137, 112, 148, 151, 131] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def a ( self : List[Any] ) -> str: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE__ , expected_max_diff=5e-3 ) @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a ( self : List[Any] ) -> str: pass @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a ( self : int ) -> Optional[Any]: pass @unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline." ) def a ( self : List[str] ) -> Optional[int]: pass def a ( self : Optional[Any] ) -> Tuple: return super().test_progress_bar() @slow @skip_mps class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : str ) -> int: lowerCAmelCase__ = VideoToVideoSDPipeline.from_pretrained("cerspense/zeroscope_v2_XL" , torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames lowerCAmelCase__ = torch.Generator(device="cpu" ).manual_seed(0 ) lowerCAmelCase__ = torch.randn((1, 10, 3, 1_024, 576) , generator=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = video.to("cuda" ) lowerCAmelCase__ = "Spiderman is surfing" lowerCAmelCase__ = pipe(SCREAMING_SNAKE_CASE__ , video=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=3 , output_type="pt" ).frames lowerCAmelCase__ = np.array([-1.0_458_984, -1.1_279_297, -0.9_663_086, -0.91_503_906, -0.75_097_656] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1e-2
61
1
import argparse import gc import json import os import shutil import warnings import torch from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer try: from transformers import LlamaTokenizerFast except ImportError as e: warnings.warn(e) warnings.warn( 'The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion' ) UpperCamelCase = None UpperCamelCase = { '7B': 1_1008, '13B': 1_3824, '30B': 1_7920, '65B': 2_2016, '70B': 2_8672, } UpperCamelCase = { '7B': 1, '7Bf': 1, '13B': 2, '13Bf': 2, '30B': 4, '65B': 8, '70B': 8, '70Bf': 8, } def _A ( lowerCAmelCase_ : int , lowerCAmelCase_ : Optional[Any]=1 , lowerCAmelCase_ : Tuple=256 ): """simple docstring""" return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3 ) ) + multiple_of - 1) // multiple_of) def _A ( lowerCAmelCase_ : Dict ): """simple docstring""" with open(lowerCAmelCase_ , "r" ) as f: return json.load(lowerCAmelCase_ ) def _A ( lowerCAmelCase_ : Tuple , lowerCAmelCase_ : int ): """simple docstring""" with open(lowerCAmelCase_ , "w" ) as f: json.dump(lowerCAmelCase_ , lowerCAmelCase_ ) def _A ( lowerCAmelCase_ : List[str] , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : List[str]=True ): """simple docstring""" os.makedirs(lowerCAmelCase_ , exist_ok=lowerCAmelCase_ ) lowerCAmelCase__ = os.path.join(lowerCAmelCase_ , "tmp" ) os.makedirs(lowerCAmelCase_ , exist_ok=lowerCAmelCase_ ) lowerCAmelCase__ = read_json(os.path.join(lowerCAmelCase_ , "params.json" ) ) lowerCAmelCase__ = NUM_SHARDS[model_size] lowerCAmelCase__ = params["n_layers"] lowerCAmelCase__ = params["n_heads"] lowerCAmelCase__ = n_heads // num_shards lowerCAmelCase__ = params["dim"] lowerCAmelCase__ = dim // n_heads lowerCAmelCase__ = 10000.0 lowerCAmelCase__ = 1.0 / (base ** (torch.arange(0 , lowerCAmelCase_ , 2 ).float() / dims_per_head)) if "n_kv_heads" in params: lowerCAmelCase__ = params["n_kv_heads"] # for GQA / MQA lowerCAmelCase__ = n_heads_per_shard // num_key_value_heads lowerCAmelCase__ = dim // num_key_value_heads else: # compatibility with other checkpoints lowerCAmelCase__ = n_heads lowerCAmelCase__ = n_heads_per_shard lowerCAmelCase__ = dim # permute for sliced rotary def permute(lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Optional[Any]=n_heads , lowerCAmelCase_ : Tuple=dim , lowerCAmelCase_ : Union[str, Any]=dim ): return w.view(lowerCAmelCase_ , dima // n_heads // 2 , 2 , lowerCAmelCase_ ).transpose(1 , 2 ).reshape(lowerCAmelCase_ , lowerCAmelCase_ ) print(F'Fetching all parameters from the checkpoint at {input_base_path}.' ) # Load weights if model_size == "7B": # Not sharded # (The sharded implementation would also work, but this is simpler.) lowerCAmelCase__ = torch.load(os.path.join(lowerCAmelCase_ , "consolidated.00.pth" ) , map_location="cpu" ) else: # Sharded lowerCAmelCase__ = [ torch.load(os.path.join(lowerCAmelCase_ , F'consolidated.{i:02d}.pth' ) , map_location="cpu" ) for i in range(lowerCAmelCase_ ) ] lowerCAmelCase__ = 0 lowerCAmelCase__ = {"weight_map": {}} for layer_i in range(lowerCAmelCase_ ): lowerCAmelCase__ = F'pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin' if model_size == "7B": # Unsharded lowerCAmelCase__ = { F'model.layers.{layer_i}.self_attn.q_proj.weight': permute( loaded[F'layers.{layer_i}.attention.wq.weight'] ), F'model.layers.{layer_i}.self_attn.k_proj.weight': permute( loaded[F'layers.{layer_i}.attention.wk.weight'] ), F'model.layers.{layer_i}.self_attn.v_proj.weight': loaded[F'layers.{layer_i}.attention.wv.weight'], F'model.layers.{layer_i}.self_attn.o_proj.weight': loaded[F'layers.{layer_i}.attention.wo.weight'], F'model.layers.{layer_i}.mlp.gate_proj.weight': loaded[F'layers.{layer_i}.feed_forward.w1.weight'], F'model.layers.{layer_i}.mlp.down_proj.weight': loaded[F'layers.{layer_i}.feed_forward.w2.weight'], F'model.layers.{layer_i}.mlp.up_proj.weight': loaded[F'layers.{layer_i}.feed_forward.w3.weight'], F'model.layers.{layer_i}.input_layernorm.weight': loaded[F'layers.{layer_i}.attention_norm.weight'], F'model.layers.{layer_i}.post_attention_layernorm.weight': loaded[F'layers.{layer_i}.ffn_norm.weight'], } else: # Sharded # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned. lowerCAmelCase__ = { F'model.layers.{layer_i}.input_layernorm.weight': loaded[0][ F'layers.{layer_i}.attention_norm.weight' ].clone(), F'model.layers.{layer_i}.post_attention_layernorm.weight': loaded[0][ F'layers.{layer_i}.ffn_norm.weight' ].clone(), } lowerCAmelCase__ = permute( torch.cat( [ loaded[i][F'layers.{layer_i}.attention.wq.weight'].view(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) for i in range(lowerCAmelCase_ ) ] , dim=0 , ).reshape(lowerCAmelCase_ , lowerCAmelCase_ ) ) lowerCAmelCase__ = permute( torch.cat( [ loaded[i][F'layers.{layer_i}.attention.wk.weight'].view( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) for i in range(lowerCAmelCase_ ) ] , dim=0 , ).reshape(lowerCAmelCase_ , lowerCAmelCase_ ) , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ) lowerCAmelCase__ = torch.cat( [ loaded[i][F'layers.{layer_i}.attention.wv.weight'].view( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) for i in range(lowerCAmelCase_ ) ] , dim=0 , ).reshape(lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ = torch.cat( [loaded[i][F'layers.{layer_i}.attention.wo.weight'] for i in range(lowerCAmelCase_ )] , dim=1 ) lowerCAmelCase__ = torch.cat( [loaded[i][F'layers.{layer_i}.feed_forward.w1.weight'] for i in range(lowerCAmelCase_ )] , dim=0 ) lowerCAmelCase__ = torch.cat( [loaded[i][F'layers.{layer_i}.feed_forward.w2.weight'] for i in range(lowerCAmelCase_ )] , dim=1 ) lowerCAmelCase__ = torch.cat( [loaded[i][F'layers.{layer_i}.feed_forward.w3.weight'] for i in range(lowerCAmelCase_ )] , dim=0 ) lowerCAmelCase__ = inv_freq for k, v in state_dict.items(): lowerCAmelCase__ = filename param_count += v.numel() torch.save(lowerCAmelCase_ , os.path.join(lowerCAmelCase_ , lowerCAmelCase_ ) ) lowerCAmelCase__ = F'pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin' if model_size == "7B": # Unsharded lowerCAmelCase__ = { "model.embed_tokens.weight": loaded["tok_embeddings.weight"], "model.norm.weight": loaded["norm.weight"], "lm_head.weight": loaded["output.weight"], } else: lowerCAmelCase__ = { "model.norm.weight": loaded[0]["norm.weight"], "model.embed_tokens.weight": torch.cat( [loaded[i]["tok_embeddings.weight"] for i in range(lowerCAmelCase_ )] , dim=1 ), "lm_head.weight": torch.cat([loaded[i]["output.weight"] for i in range(lowerCAmelCase_ )] , dim=0 ), } for k, v in state_dict.items(): lowerCAmelCase__ = filename param_count += v.numel() torch.save(lowerCAmelCase_ , os.path.join(lowerCAmelCase_ , lowerCAmelCase_ ) ) # Write configs lowerCAmelCase__ = {"total_size": param_count * 2} write_json(lowerCAmelCase_ , os.path.join(lowerCAmelCase_ , "pytorch_model.bin.index.json" ) ) lowerCAmelCase__ = params["ffn_dim_multiplier"] if "ffn_dim_multiplier" in params else 1 lowerCAmelCase__ = params["multiple_of"] if "multiple_of" in params else 256 lowerCAmelCase__ = LlamaConfig( hidden_size=lowerCAmelCase_ , intermediate_size=compute_intermediate_size(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) , num_attention_heads=params["n_heads"] , num_hidden_layers=params["n_layers"] , rms_norm_eps=params["norm_eps"] , num_key_value_heads=lowerCAmelCase_ , ) config.save_pretrained(lowerCAmelCase_ ) # Make space so we can load the model properly now. del state_dict del loaded gc.collect() print("Loading the checkpoint in a Llama model." ) lowerCAmelCase__ = LlamaForCausalLM.from_pretrained(lowerCAmelCase_ , torch_dtype=torch.floataa , low_cpu_mem_usage=lowerCAmelCase_ ) # Avoid saving this as part of the config. del model.config._name_or_path print("Saving in the Transformers format." ) model.save_pretrained(lowerCAmelCase_ , safe_serialization=lowerCAmelCase_ ) shutil.rmtree(lowerCAmelCase_ ) def _A ( lowerCAmelCase_ : Tuple , lowerCAmelCase_ : int ): """simple docstring""" lowerCAmelCase__ = LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast print(F'Saving a {tokenizer_class.__name__} to {tokenizer_path}.' ) lowerCAmelCase__ = tokenizer_class(lowerCAmelCase_ ) tokenizer.save_pretrained(lowerCAmelCase_ ) def _A ( ): """simple docstring""" lowerCAmelCase__ = argparse.ArgumentParser() parser.add_argument( "--input_dir" , help="Location of LLaMA weights, which contains tokenizer.model and model folders" , ) parser.add_argument( "--model_size" , choices=["7B", "7Bf", "13B", "13Bf", "30B", "65B", "70B", "70Bf", "tokenizer_only"] , ) parser.add_argument( "--output_dir" , help="Location to write HF model and tokenizer" , ) parser.add_argument("--safe_serialization" , type=lowerCAmelCase_ , help="Whether or not to save using `safetensors`." ) lowerCAmelCase__ = parser.parse_args() if args.model_size != "tokenizer_only": write_model( model_path=args.output_dir , input_base_path=os.path.join(args.input_dir , args.model_size ) , model_size=args.model_size , safe_serialization=args.safe_serialization , ) lowerCAmelCase__ = os.path.join(args.input_dir , "tokenizer.model" ) write_tokenizer(args.output_dir , lowerCAmelCase_ ) if __name__ == "__main__": main()
61
from __future__ import annotations def _A ( lowerCAmelCase_ : list , lowerCAmelCase_ : int , lowerCAmelCase_ : int , lowerCAmelCase_ : int ): """simple docstring""" lowerCAmelCase__ = [] lowerCAmelCase__ , lowerCAmelCase__ = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0 ) ) lowerCAmelCase__ = result + left + right return input_list def _A ( lowerCAmelCase_ : list ): """simple docstring""" if len(lowerCAmelCase_ ) <= 1: return input_list lowerCAmelCase__ = list(lowerCAmelCase_ ) # iteration for two-way merging lowerCAmelCase__ = 2 while p <= len(lowerCAmelCase_ ): # getting low, high and middle value for merge-sort of single list for i in range(0 , len(lowerCAmelCase_ ) , lowerCAmelCase_ ): lowerCAmelCase__ = i lowerCAmelCase__ = i + p - 1 lowerCAmelCase__ = (low + high + 1) // 2 lowerCAmelCase__ = merge(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # final merge of last two parts if p * 2 >= len(lowerCAmelCase_ ): lowerCAmelCase__ = i lowerCAmelCase__ = merge(lowerCAmelCase_ , 0 , lowerCAmelCase_ , len(lowerCAmelCase_ ) - 1 ) break p *= 2 return input_list if __name__ == "__main__": UpperCamelCase = input('Enter numbers separated by a comma:\n').strip() if user_input == "": UpperCamelCase = [] else: UpperCamelCase = [int(item.strip()) for item in user_input.split(',')] print(iter_merge_sort(unsorted))
61
1
from collections.abc import Callable def _A ( lowerCAmelCase_ : Callable[[float], float] , lowerCAmelCase_ : float , lowerCAmelCase_ : float ): """simple docstring""" lowerCAmelCase__ = a lowerCAmelCase__ = b if function(lowerCAmelCase_ ) == 0: # one of the a or b is a root for the function return a elif function(lowerCAmelCase_ ) == 0: return b elif ( function(lowerCAmelCase_ ) * function(lowerCAmelCase_ ) > 0 ): # if none of these are root and they are both positive or negative, # then this algorithm can't find the root raise ValueError("could not find root in given interval." ) else: lowerCAmelCase__ = start + (end - start) / 2.0 while abs(start - mid ) > 10**-7: # until precisely equals to 10^-7 if function(lowerCAmelCase_ ) == 0: return mid elif function(lowerCAmelCase_ ) * function(lowerCAmelCase_ ) < 0: lowerCAmelCase__ = mid else: lowerCAmelCase__ = mid lowerCAmelCase__ = start + (end - start) / 2.0 return mid def _A ( lowerCAmelCase_ : float ): """simple docstring""" return x**3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 1000)) import doctest doctest.testmod()
61
import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, ) class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=13 , SCREAMING_SNAKE_CASE__ : int=7 , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=99 , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : List[str]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : Optional[Any]=37 , SCREAMING_SNAKE_CASE__ : Optional[int]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE__ : Tuple=512 , SCREAMING_SNAKE_CASE__ : Tuple=16 , SCREAMING_SNAKE_CASE__ : Optional[Any]=2 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 , SCREAMING_SNAKE_CASE__ : Dict=4 , ) -> Optional[int]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = seq_length lowerCAmelCase__ = is_training lowerCAmelCase__ = use_attention_mask lowerCAmelCase__ = use_token_type_ids lowerCAmelCase__ = use_labels lowerCAmelCase__ = vocab_size lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = type_vocab_size lowerCAmelCase__ = type_sequence_label_size lowerCAmelCase__ = initializer_range lowerCAmelCase__ = num_choices def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase__ = None if self.use_attention_mask: lowerCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase__ = None if self.use_token_type_ids: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCAmelCase__ = RobertaPreLayerNormConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def a ( self : List[str] ) -> Union[str, Any]: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict def a ( self : Optional[Any] ) -> Dict: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = True lowerCAmelCase__ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax # Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40 class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = True snake_case__ = ( ( FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, ) if is_flax_available() else () ) def a ( self : int ) -> Dict: lowerCAmelCase__ = FlaxRobertaPreLayerNormModelTester(self ) @slow def a ( self : Tuple ) -> Union[str, Any]: for model_class_name in self.all_model_classes: lowerCAmelCase__ = model_class_name.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(np.ones((1, 1) ) ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_flax class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @slow def a ( self : int ) -> Dict: lowerCAmelCase__ = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ )[0] lowerCAmelCase__ = [1, 11, 50_265] self.assertEqual(list(output.shape ) , SCREAMING_SNAKE_CASE__ ) # compare the actual values for a slice. lowerCAmelCase__ = np.array( [[[40.4_880, 18.0_199, -5.2_367], [-1.8_877, -4.0_885, 10.7_085], [-2.2_613, -5.6_110, 7.2_665]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) @slow def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = FlaxRobertaPreLayerNormModel.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ )[0] # compare the actual values for a slice. lowerCAmelCase__ = np.array( [[[0.0_208, -0.0_356, 0.0_237], [-0.1_569, -0.0_411, -0.2_626], [0.1_879, 0.0_125, -0.0_089]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
1
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import ( BaseOutput, OptionalDependencyNotAvailable, is_flax_available, is_k_diffusion_available, is_k_diffusion_version, is_onnx_available, is_torch_available, is_transformers_available, is_transformers_version, ) @dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_cycle_diffusion import CycleDiffusionPipeline from .pipeline_stable_diffusion import StableDiffusionPipeline from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from .pipeline_stable_unclip import StableUnCLIPPipeline from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline from .safety_checker import StableDiffusionSafetyChecker from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.25.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline else: from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.26.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionPixaPixZeroPipeline, ) else: from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline try: if not ( is_torch_available() and is_transformers_available() and is_k_diffusion_available() and is_k_diffusion_version('>=', '0.0.12') ): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline try: if not (is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_onnx_objects import * # noqa F403 else: from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline if is_transformers_available() and is_flax_available(): import flax @flax.struct.dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline from .safety_checker_flax import FlaxStableDiffusionSafetyChecker
61
class __lowerCamelCase : """simple docstring""" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = size lowerCAmelCase__ = [0] * size lowerCAmelCase__ = [0] * size @staticmethod def a ( SCREAMING_SNAKE_CASE__ : int ) -> int: return index | (index + 1) @staticmethod def a ( SCREAMING_SNAKE_CASE__ : int ) -> int: return (index & (index + 1)) - 1 def a ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = value while index < self.size: lowerCAmelCase__ = self.get_prev(SCREAMING_SNAKE_CASE__ ) + 1 if current_left_border == index: lowerCAmelCase__ = value else: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_next(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> int: right -= 1 # Because of right is exclusive lowerCAmelCase__ = 0 while left <= right: lowerCAmelCase__ = self.get_prev(SCREAMING_SNAKE_CASE__ ) if left <= current_left: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , self.tree[right] ) lowerCAmelCase__ = current_left else: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
61
1
import math import random from typing import Any from .hill_climbing import SearchProblem def _A ( lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : bool = True , lowerCAmelCase_ : float = math.inf , lowerCAmelCase_ : float = -math.inf , lowerCAmelCase_ : float = math.inf , lowerCAmelCase_ : float = -math.inf , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : float = 100 , lowerCAmelCase_ : float = 0.01 , lowerCAmelCase_ : float = 1 , ): """simple docstring""" lowerCAmelCase__ = False lowerCAmelCase__ = search_prob lowerCAmelCase__ = start_temperate lowerCAmelCase__ = [] lowerCAmelCase__ = 0 lowerCAmelCase__ = None while not search_end: lowerCAmelCase__ = current_state.score() if best_state is None or current_score > best_state.score(): lowerCAmelCase__ = current_state scores.append(lowerCAmelCase_ ) iterations += 1 lowerCAmelCase__ = None lowerCAmelCase__ = current_state.get_neighbors() while ( next_state is None and neighbors ): # till we do not find a neighbor that we can move to lowerCAmelCase__ = random.randint(0 , len(lowerCAmelCase_ ) - 1 ) # picking a random neighbor lowerCAmelCase__ = neighbors.pop(lowerCAmelCase_ ) lowerCAmelCase__ = picked_neighbor.score() - current_score if ( picked_neighbor.x > max_x or picked_neighbor.x < min_x or picked_neighbor.y > max_y or picked_neighbor.y < min_y ): continue # neighbor outside our bounds if not find_max: lowerCAmelCase__ = change * -1 # in case we are finding minimum if change > 0: # improves the solution lowerCAmelCase__ = picked_neighbor else: lowerCAmelCase__ = (math.e) ** ( change / current_temp ) # probability generation function if random.random() < probability: # random number within probability lowerCAmelCase__ = picked_neighbor lowerCAmelCase__ = current_temp - (current_temp * rate_of_decrease) if current_temp < threshold_temp or next_state is None: # temperature below threshold, or could not find a suitable neighbor lowerCAmelCase__ = True else: lowerCAmelCase__ = next_state if visualization: from matplotlib import pyplot as plt plt.plot(range(lowerCAmelCase_ ) , lowerCAmelCase_ ) plt.xlabel("Iterations" ) plt.ylabel("Function values" ) plt.show() return best_state if __name__ == "__main__": def _A ( lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : List[str] ): """simple docstring""" return (x**2) + (y**2) # starting the problem with initial coordinates (12, 47) UpperCamelCase = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) UpperCamelCase = simulated_annealing( prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( 'The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ' F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) # starting the problem with initial coordinates (12, 47) UpperCamelCase = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) UpperCamelCase = simulated_annealing( prob, find_max=True, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( 'The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ' F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) def _A ( lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : Optional[Any] ): """simple docstring""" return (3 * x**2) - (6 * y) UpperCamelCase = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) UpperCamelCase = simulated_annealing(prob, find_max=False, visualization=True) print( 'The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ' F"""{local_min.score()}""" ) UpperCamelCase = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) UpperCamelCase = simulated_annealing(prob, find_max=True, visualization=True) print( 'The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ' F"""{local_min.score()}""" )
61
import unittest from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin UpperCamelCase = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = XLNetTokenizer snake_case__ = XLNetTokenizerFast snake_case__ = True snake_case__ = True def a ( self : str ) -> str: super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) tokenizer.sanitize_special_tokens() tokenizer.save_pretrained(self.tmpdirname ) def a ( self : List[str] ) -> List[Any]: lowerCAmelCase__ = "<s>" lowerCAmelCase__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def a ( self : Union[str, Any] ) -> str: lowerCAmelCase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "<eod>" ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 1_006 ) def a ( self : int ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 1_000 ) def a ( self : List[str] ) -> Any: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("This is a test" ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [285, 46, 10, 170, 382] ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) lowerCAmelCase__ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] ) lowerCAmelCase__ = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) def a ( self : Optional[int] ) -> Optional[Any]: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "", "i", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "se", ".", ] , ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["▁he", "ll", "o"] ) def a ( self : List[Any] ) -> Optional[int]: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "se", ".", ] , ) @slow def a ( self : Any ) -> Any: lowerCAmelCase__ = XLNetTokenizer.from_pretrained("xlnet-base-cased" ) lowerCAmelCase__ = tokenizer.encode("sequence builders" , add_special_tokens=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.encode("multi-sequence build" , add_special_tokens=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert encoded_sentence == text + [4, 3] assert encoded_pair == text + [4] + text_a + [4, 3] @slow def a ( self : Union[str, Any] ) -> Any: # fmt: off lowerCAmelCase__ = {"input_ids": [[17, 21_442, 270, 17, 10, 14_645, 318, 34, 17, 4_546, 3_145, 787, 13, 7_752, 22_018, 23, 21, 17, 4_546, 3_145, 787, 13, 3_352, 14_431, 13, 5_500, 11, 1_176, 580, 13, 16_819, 4_797, 23, 17, 10, 17_135, 658, 19, 457, 7_932, 13, 184, 19, 3_154, 17_135, 6_468, 19, 1_404, 12_269, 19, 4_229, 5_356, 16_264, 46, 19, 17, 20_545, 10_395, 9, 9, 9, 11, 28, 6_421, 9_531, 20_729, 17, 10, 353, 17_022, 11, 21, 6_421, 9_531, 16_949, 17, 10, 11_509, 753, 11, 33, 95, 2_421, 7_385, 956, 14_431, 2_626, 25, 842, 7_385, 4_836, 21, 1_429, 2_272, 9_855, 3_120, 161, 24_738, 19, 13_203, 658, 218, 787, 21, 430, 18_482, 847, 2_637, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 322, 22_178, 27, 1_064, 22, 956, 13, 11_101, 1_429, 5_854, 24_313, 18_953, 40, 422, 24_366, 68, 1_758, 37, 10_483, 14_257, 31, 207, 263, 21, 203, 3_773, 25, 71, 9_735, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 32, 2_049, 3_442, 17, 13_894, 3_380, 23, 95, 18, 17_634, 2_288, 9, 4, 3]], "token_type_ids": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=SCREAMING_SNAKE_CASE__ , model_name="xlnet-base-cased" , revision="c841166438c31ec7ca9a106dee7bb312b73ae511" , )
61
1
# NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline # noqa: F401 deprecate( 'stable diffusion controlnet', '0.22.0', 'Importing `FlaxStableDiffusionControlNetPipeline` from diffusers.pipelines.stable_diffusion.flax_pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import FlaxStableDiffusionControlNetPipeline` instead.', standard_warn=False, stacklevel=3, )
61
import operator as op UpperCamelCase = 'scaler.pt' UpperCamelCase = 'pytorch_model' UpperCamelCase = 'random_states' UpperCamelCase = 'optimizer' UpperCamelCase = 'scheduler' UpperCamelCase = 'pytorch_model.bin' UpperCamelCase = 'pytorch_model.bin.index.json' UpperCamelCase = 'model.safetensors' UpperCamelCase = 'model.safetensors.index.json' UpperCamelCase = '1.10.2' UpperCamelCase = 'py38' UpperCamelCase = '4.17.0' UpperCamelCase = ['ml.p3.16xlarge', 'ml.p3dn.24xlarge', 'ml.p4dn.24xlarge'] UpperCamelCase = ['FULL_SHARD', 'SHARD_GRAD_OP', 'NO_SHARD', 'HYBRID_SHARD', 'HYBRID_SHARD_ZERO2'] UpperCamelCase = ['TRANSFORMER_BASED_WRAP', 'SIZE_BASED_WRAP', 'NO_WRAP'] UpperCamelCase = ['BACKWARD_PRE', 'BACKWARD_POST', 'NO_PREFETCH'] UpperCamelCase = ['FULL_STATE_DICT', 'LOCAL_STATE_DICT', 'SHARDED_STATE_DICT'] UpperCamelCase = '2.0.1' UpperCamelCase = ['pdsh', 'standard', 'openmpi', 'mvapich'] UpperCamelCase = ['default', 'reduce-overhead', 'max-autotune'] UpperCamelCase = {'>': op.gt, '>=': op.ge, '==': op.eq, '!=': op.ne, '<=': op.le, '<': op.lt} # These are the args for `torch.distributed.launch` for pytorch < 1.9 UpperCamelCase = [ 'nnodes', 'nproc_per_node', 'rdzv_backend', 'rdzv_endpoint', 'rdzv_id', 'rdzv_conf', 'standalone', 'max_restarts', 'monitor_interval', 'start_method', 'role', 'module', 'm', 'no_python', 'run_path', 'log_dir', 'r', 'redirects', 't', 'tee', 'node_rank', 'master_addr', 'master_port', ] UpperCamelCase = ['DEEPSPEED', 'MULTI_GPU', 'FSDP', 'MEGATRON_LM'] UpperCamelCase = ['DEEPSPEED', 'MULTI_XPU', 'FSDP']
61
1
# Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version UpperCamelCase = get_logger(__name__) class __lowerCamelCase : """simple docstring""" snake_case__ = "dummy_data" snake_case__ = "datasets" snake_case__ = False def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Union[Version, str] , SCREAMING_SNAKE_CASE__ : Optional[str] = None , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[List[Callable]] = None , ) -> Union[str, Any]: lowerCAmelCase__ = 0 lowerCAmelCase__ = dataset_name lowerCAmelCase__ = cache_dir lowerCAmelCase__ = use_local_dummy_data lowerCAmelCase__ = config # download_callbacks take a single url as input lowerCAmelCase__ = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root lowerCAmelCase__ = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general lowerCAmelCase__ = str(SCREAMING_SNAKE_CASE__ ) # to be downloaded lowerCAmelCase__ = None lowerCAmelCase__ = None @property def a ( self : Union[str, Any] ) -> List[str]: if self._dummy_file is None: lowerCAmelCase__ = self.download_dummy_data() return self._dummy_file @property def a ( self : Optional[int] ) -> Any: if self.config is not None: # structure is dummy / config_name / version_name return os.path.join("dummy" , self.config.name , self.version_name ) # structure is dummy / version_name return os.path.join("dummy" , self.version_name ) @property def a ( self : int ) -> Optional[int]: return os.path.join(self.dummy_data_folder , "dummy_data.zip" ) def a ( self : int ) -> str: lowerCAmelCase__ = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) lowerCAmelCase__ = cached_path( SCREAMING_SNAKE_CASE__ , cache_dir=self.cache_dir , extract_compressed_file=SCREAMING_SNAKE_CASE__ , force_extract=SCREAMING_SNAKE_CASE__ ) return os.path.join(SCREAMING_SNAKE_CASE__ , self.dummy_file_name ) @property def a ( self : List[Any] ) -> Union[str, Any]: return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file ) @property def a ( self : Optional[int] ) -> Union[str, Any]: if self._bucket_url is None: lowerCAmelCase__ = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , "/" ) ) return self._bucket_url @property def a ( self : List[Any] ) -> Any: # return full path if its a dir if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep , "/" ).split("/" )[:-1] ) def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , *SCREAMING_SNAKE_CASE__ : List[str] ) -> Tuple: if self.load_existing_dummy_data: # dummy data is downloaded and tested lowerCAmelCase__ = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned lowerCAmelCase__ = self.dummy_file_name # special case when data_url is a dict if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return self.create_dummy_data_dict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ): return self.create_dummy_data_list(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: return self.create_dummy_data_single(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : str , *SCREAMING_SNAKE_CASE__ : int ) -> List[str]: return self.download_and_extract(SCREAMING_SNAKE_CASE__ ) def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> List[Any]: return self.download_and_extract(SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> str: return path def a ( self : List[str] ) -> Dict: return {} def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : int ) -> Optional[Any]: lowerCAmelCase__ = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): for single_url in single_urls: download_callback(SCREAMING_SNAKE_CASE__ ) else: lowerCAmelCase__ = single_urls download_callback(SCREAMING_SNAKE_CASE__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = [os.path.join(SCREAMING_SNAKE_CASE__ , urllib.parse.quote_plus(Path(SCREAMING_SNAKE_CASE__ ).name ) ) for x in single_urls] else: lowerCAmelCase__ = single_urls lowerCAmelCase__ = os.path.join(SCREAMING_SNAKE_CASE__ , urllib.parse.quote_plus(Path(SCREAMING_SNAKE_CASE__ ).name ) ) lowerCAmelCase__ = value # make sure that values are unique if all(isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique lowerCAmelCase__ = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[str] ) -> List[str]: lowerCAmelCase__ = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one lowerCAmelCase__ = all(bool(re.findall("[0-9]{3,}-of-[0-9]{3,}" , SCREAMING_SNAKE_CASE__ ) ) for url in data_url ) lowerCAmelCase__ = all( url.startswith("https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed" ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): lowerCAmelCase__ = [data_url[0]] * len(SCREAMING_SNAKE_CASE__ ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(SCREAMING_SNAKE_CASE__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus lowerCAmelCase__ = os.path.join(SCREAMING_SNAKE_CASE__ , urllib.parse.quote_plus(single_url.split("/" )[-1] ) ) dummy_data_list.append(SCREAMING_SNAKE_CASE__ ) return dummy_data_list def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> int: for download_callback in self.download_callbacks: download_callback(SCREAMING_SNAKE_CASE__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus lowerCAmelCase__ = os.path.join(SCREAMING_SNAKE_CASE__ , urllib.parse.quote_plus(data_url.split("/" )[-1] ) ) if os.path.exists(SCREAMING_SNAKE_CASE__ ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def a ( self : Any ) -> str: pass def a ( self : List[str] ) -> Optional[int]: pass def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Union[str, Any]: def _iter_archive_members(SCREAMING_SNAKE_CASE__ : Tuple ): # this preserves the order of the members inside the ZIP archive lowerCAmelCase__ = Path(self.dummy_file ).parent lowerCAmelCase__ = path.relative_to(SCREAMING_SNAKE_CASE__ ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: lowerCAmelCase__ = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = Path(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = _iter_archive_members(SCREAMING_SNAKE_CASE__ ) if self.use_local_dummy_data else path.rglob("*" ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith((".", "__") ): yield file_path.relative_to(SCREAMING_SNAKE_CASE__ ).as_posix(), file_path.open("rb" ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] ) -> int: if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = [paths] for path in paths: if os.path.isfile(SCREAMING_SNAKE_CASE__ ): if os.path.basename(SCREAMING_SNAKE_CASE__ ).startswith((".", "__") ): return yield path else: for dirpath, dirnames, filenames in os.walk(SCREAMING_SNAKE_CASE__ ): if os.path.basename(SCREAMING_SNAKE_CASE__ ).startswith((".", "__") ): continue dirnames.sort() for filename in sorted(SCREAMING_SNAKE_CASE__ ): if filename.startswith((".", "__") ): continue yield os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
61
import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'vocab_file': 'sentencepiece.model'} UpperCamelCase = { 'vocab_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model', }, } UpperCamelCase = { 'google/rembert': 256, } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int]=False , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : Any="[CLS]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" , SCREAMING_SNAKE_CASE__ : Dict="[UNK]" , SCREAMING_SNAKE_CASE__ : Optional[Any]="[SEP]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[PAD]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[CLS]" , SCREAMING_SNAKE_CASE__ : List[Any]="[MASK]" , **SCREAMING_SNAKE_CASE__ : str , ) -> Dict: super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ , remove_space=SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = do_lower_case lowerCAmelCase__ = remove_space lowerCAmelCase__ = keep_accents lowerCAmelCase__ = vocab_file lowerCAmelCase__ = spm.SentencePieceProcessor() self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def a ( self : int ) -> Union[str, Any]: return len(self.sp_model ) def a ( self : Any ) -> str: lowerCAmelCase__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Union[str, Any] ) -> List[str]: lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = d lowerCAmelCase__ = spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int=False ) -> Optional[int]: lowerCAmelCase__ = self.sp_model.EncodeAsPieces(SCREAMING_SNAKE_CASE__ ) return pieces def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> List[Any]: return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Dict: return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : int ) -> int: lowerCAmelCase__ = self.sp_model.decode_pieces(SCREAMING_SNAKE_CASE__ ) return out_string def a ( self : int , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: 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 not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error("Vocabulary path ({}) should be a directory".format(SCREAMING_SNAKE_CASE__ ) ) return lowerCAmelCase__ = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
61
1
import json import os import shutil import tempfile from unittest import TestCase from transformers import BartTokenizer, BartTokenizerFast, DPRQuestionEncoderTokenizer, DPRQuestionEncoderTokenizerFast from transformers.models.bart.configuration_bart import BartConfig from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES from transformers.models.dpr.configuration_dpr import DPRConfig from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES from transformers.testing_utils import require_faiss, require_tokenizers, require_torch, slow from transformers.utils import is_datasets_available, is_faiss_available, is_torch_available if is_torch_available() and is_datasets_available() and is_faiss_available(): from transformers.models.rag.configuration_rag import RagConfig from transformers.models.rag.tokenization_rag import RagTokenizer @require_faiss @require_torch class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def a ( self : Any ) -> Optional[int]: lowerCAmelCase__ = tempfile.mkdtemp() lowerCAmelCase__ = 8 # DPR tok lowerCAmelCase__ = [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] lowerCAmelCase__ = os.path.join(self.tmpdirname , "dpr_tokenizer" ) os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = os.path.join(SCREAMING_SNAKE_CASE__ , DPR_VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) # BART tok lowerCAmelCase__ = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "\u0120", "\u0120l", "\u0120n", "\u0120lo", "\u0120low", "er", "\u0120lowest", "\u0120newer", "\u0120wider", "<unk>", ] lowerCAmelCase__ = dict(zip(SCREAMING_SNAKE_CASE__ , range(len(SCREAMING_SNAKE_CASE__ ) ) ) ) lowerCAmelCase__ = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""] lowerCAmelCase__ = {"unk_token": "<unk>"} lowerCAmelCase__ = os.path.join(self.tmpdirname , "bart_tokenizer" ) os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = os.path.join(SCREAMING_SNAKE_CASE__ , BART_VOCAB_FILES_NAMES["vocab_file"] ) lowerCAmelCase__ = os.path.join(SCREAMING_SNAKE_CASE__ , BART_VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE__ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(SCREAMING_SNAKE_CASE__ ) ) def a ( self : Tuple ) -> DPRQuestionEncoderTokenizer: return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , "dpr_tokenizer" ) ) def a ( self : Dict ) -> BartTokenizer: return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname , "bart_tokenizer" ) ) def a ( self : str ) -> Tuple: shutil.rmtree(self.tmpdirname ) @require_tokenizers def a ( self : str ) -> Optional[int]: lowerCAmelCase__ = os.path.join(self.tmpdirname , "rag_tokenizer" ) lowerCAmelCase__ = RagConfig(question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() ) lowerCAmelCase__ = RagTokenizer(question_encoder=self.get_dpr_tokenizer() , generator=self.get_bart_tokenizer() ) rag_config.save_pretrained(SCREAMING_SNAKE_CASE__ ) rag_tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = RagTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ , config=SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(new_rag_tokenizer.question_encoder , SCREAMING_SNAKE_CASE__ ) self.assertEqual(new_rag_tokenizer.question_encoder.get_vocab() , rag_tokenizer.question_encoder.get_vocab() ) self.assertIsInstance(new_rag_tokenizer.generator , SCREAMING_SNAKE_CASE__ ) self.assertEqual(new_rag_tokenizer.generator.get_vocab() , rag_tokenizer.generator.get_vocab() ) @slow def a ( self : Dict ) -> Dict: lowerCAmelCase__ = RagTokenizer.from_pretrained("facebook/rag-token-nq" ) lowerCAmelCase__ = [ "who got the first nobel prize in physics", "when is the next deadpool movie being released", "which mode is used for short wave broadcast service", "who is the owner of reading football club", "when is the next scandal episode coming out", "when is the last time the philadelphia won the superbowl", "what is the most current adobe flash player version", "how many episodes are there in dragon ball z", "what is the first step in the evolution of the eye", "where is gall bladder situated in human body", "what is the main mineral in lithium batteries", "who is the president of usa right now", "where do the greasers live in the outsiders", "panda is a national animal of which country", "what is the name of manchester united stadium", ] lowerCAmelCase__ = tokenizer(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @slow def a ( self : List[Any] ) -> Dict: lowerCAmelCase__ = RagTokenizer.from_pretrained("facebook/rag-sequence-nq" ) lowerCAmelCase__ = [ "who got the first nobel prize in physics", "when is the next deadpool movie being released", "which mode is used for short wave broadcast service", "who is the owner of reading football club", "when is the next scandal episode coming out", "when is the last time the philadelphia won the superbowl", "what is the most current adobe flash player version", "how many episodes are there in dragon ball z", "what is the first step in the evolution of the eye", "where is gall bladder situated in human body", "what is the main mineral in lithium batteries", "who is the president of usa right now", "where do the greasers live in the outsiders", "panda is a national animal of which country", "what is the name of manchester united stadium", ] lowerCAmelCase__ = tokenizer(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ )
61
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
61
1
import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Any , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple=7 , SCREAMING_SNAKE_CASE__ : Optional[int]=3 , SCREAMING_SNAKE_CASE__ : Optional[int]=18 , SCREAMING_SNAKE_CASE__ : int=30 , SCREAMING_SNAKE_CASE__ : Optional[int]=400 , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : int=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , ) -> Union[str, Any]: lowerCAmelCase__ = size if size is not None else {"height": 18, "width": 18} lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = image_size lowerCAmelCase__ = min_resolution lowerCAmelCase__ = max_resolution lowerCAmelCase__ = do_resize lowerCAmelCase__ = size lowerCAmelCase__ = apply_ocr def a ( self : str ) -> Any: return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = LayoutLMvaImageProcessor if is_pytesseract_available() else None def a ( self : int ) -> Tuple: lowerCAmelCase__ = LayoutLMvaImageProcessingTester(self ) @property def a ( self : Optional[int] ) -> int: return self.image_processor_tester.prepare_image_processor_dict() def a ( self : Tuple ) -> Optional[Any]: lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "do_resize" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "size" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "apply_ocr" ) ) def a ( self : Optional[int] ) -> Optional[Any]: lowerCAmelCase__ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 18, "width": 18} ) lowerCAmelCase__ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"height": 42, "width": 42} ) def a ( self : List[Any] ) -> Union[str, Any]: pass def a ( self : Any ) -> Optional[int]: # Initialize image_processing lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input lowerCAmelCase__ = image_processing(image_inputs[0] , return_tensors="pt" ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) self.assertIsInstance(encoding.words , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(encoding.boxes , SCREAMING_SNAKE_CASE__ ) # Test batched lowerCAmelCase__ = image_processing(SCREAMING_SNAKE_CASE__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def a ( self : Union[str, Any] ) -> Optional[int]: # Initialize image_processing lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCAmelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) # Test not batched input lowerCAmelCase__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched lowerCAmelCase__ = image_processing(SCREAMING_SNAKE_CASE__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def a ( self : List[str] ) -> List[str]: # Initialize image_processing lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCAmelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input lowerCAmelCase__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched lowerCAmelCase__ = image_processing(SCREAMING_SNAKE_CASE__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def a ( self : int ) -> List[Any]: # with apply_OCR = True lowerCAmelCase__ = LayoutLMvaImageProcessor() from datasets import load_dataset lowerCAmelCase__ = load_dataset("hf-internal-testing/fixtures_docvqa" , split="test" ) lowerCAmelCase__ = Image.open(ds[0]["file"] ).convert("RGB" ) lowerCAmelCase__ = image_processing(SCREAMING_SNAKE_CASE__ , return_tensors="pt" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 lowerCAmelCase__ = [["11:14", "to", "11:39", "a.m", "11:39", "to", "11:44", "a.m.", "11:44", "a.m.", "to", "12:25", "p.m.", "12:25", "to", "12:58", "p.m.", "12:58", "to", "4:00", "p.m.", "2:00", "to", "5:00", "p.m.", "Coffee", "Break", "Coffee", "will", "be", "served", "for", "men", "and", "women", "in", "the", "lobby", "adjacent", "to", "exhibit", "area.", "Please", "move", "into", "exhibit", "area.", "(Exhibits", "Open)", "TRRF", "GENERAL", "SESSION", "(PART", "|)", "Presiding:", "Lee", "A.", "Waller", "TRRF", "Vice", "President", "“Introductory", "Remarks”", "Lee", "A.", "Waller,", "TRRF", "Vice", "Presi-", "dent", "Individual", "Interviews", "with", "TRRF", "Public", "Board", "Members", "and", "Sci-", "entific", "Advisory", "Council", "Mem-", "bers", "Conducted", "by", "TRRF", "Treasurer", "Philip", "G.", "Kuehn", "to", "get", "answers", "which", "the", "public", "refrigerated", "warehousing", "industry", "is", "looking", "for.", "Plus", "questions", "from", "the", "floor.", "Dr.", "Emil", "M.", "Mrak,", "University", "of", "Cal-", "ifornia,", "Chairman,", "TRRF", "Board;", "Sam", "R.", "Cecil,", "University", "of", "Georgia", "College", "of", "Agriculture;", "Dr.", "Stanley", "Charm,", "Tufts", "University", "School", "of", "Medicine;", "Dr.", "Robert", "H.", "Cotton,", "ITT", "Continental", "Baking", "Company;", "Dr.", "Owen", "Fennema,", "University", "of", "Wis-", "consin;", "Dr.", "Robert", "E.", "Hardenburg,", "USDA.", "Questions", "and", "Answers", "Exhibits", "Open", "Capt.", "Jack", "Stoney", "Room", "TRRF", "Scientific", "Advisory", "Council", "Meeting", "Ballroom", "Foyer"]] # noqa: E231 lowerCAmelCase__ = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(encoding.boxes , SCREAMING_SNAKE_CASE__ ) # with apply_OCR = False lowerCAmelCase__ = LayoutLMvaImageProcessor(apply_ocr=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = image_processing(SCREAMING_SNAKE_CASE__ , return_tensors="pt" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
61
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = ["pixel_values"] def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Union[int, float] = 1 / 255 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> None: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = size if size is not None else {"shortest_edge": 384} lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = do_resize lowerCAmelCase__ = size # Default value set here for backwards compatibility where the value in config is None lowerCAmelCase__ = crop_pct if crop_pct is not None else 224 / 256 lowerCAmelCase__ = resample lowerCAmelCase__ = do_rescale lowerCAmelCase__ = rescale_factor lowerCAmelCase__ = do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN lowerCAmelCase__ = image_std if image_std is not None else IMAGENET_STANDARD_STD def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : int , ) -> np.ndarray: lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) if "shortest_edge" not in size: raise ValueError(f'Size dictionary must contain \'shortest_edge\' key. Got {size.keys()}' ) lowerCAmelCase__ = size["shortest_edge"] if shortest_edge < 384: # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct lowerCAmelCase__ = int(shortest_edge / crop_pct ) lowerCAmelCase__ = get_resize_output_image_size(SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # then crop to (shortest_edge, shortest_edge) return center_crop(image=SCREAMING_SNAKE_CASE__ , size=(shortest_edge, shortest_edge) , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) else: # warping (no cropping) when evaluated at 384 or larger return resize( SCREAMING_SNAKE_CASE__ , size=(shortest_edge, shortest_edge) , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : int , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[int, float] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> List[Any]: return rescale(SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Optional[int] , ) -> np.ndarray: return normalize(SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : ImageInput , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE__ : ChannelDimension = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE__ : Dict , ) -> PIL.Image.Image: lowerCAmelCase__ = do_resize if do_resize is not None else self.do_resize lowerCAmelCase__ = crop_pct if crop_pct is not None else self.crop_pct lowerCAmelCase__ = resample if resample is not None else self.resample lowerCAmelCase__ = do_rescale if do_rescale is not None else self.do_rescale lowerCAmelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCAmelCase__ = do_normalize if do_normalize is not None else self.do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else self.image_mean lowerCAmelCase__ = image_std if image_std is not None else self.image_std lowerCAmelCase__ = size if size is not None else self.size lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = make_list_of_images(SCREAMING_SNAKE_CASE__ ) if not valid_images(SCREAMING_SNAKE_CASE__ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_resize and size["shortest_edge"] < 384 and crop_pct is None: raise ValueError("crop_pct must be specified if size < 384." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. lowerCAmelCase__ = [to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if do_resize: lowerCAmelCase__ = [self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , crop_pct=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images] if do_rescale: lowerCAmelCase__ = [self.rescale(image=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ ) for image in images] if do_normalize: lowerCAmelCase__ = [self.normalize(image=SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = {"pixel_values": images} return BatchFeature(data=SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ )
61
1
import os import textwrap import pyarrow as pa import pytest from datasets import ClassLabel, Features, Image from datasets.packaged_modules.csv.csv import Csv from ..utils import require_pil @pytest.fixture def _A ( lowerCAmelCase_ : List[Any] ): """simple docstring""" lowerCAmelCase__ = tmp_path / "file.csv" lowerCAmelCase__ = textwrap.dedent( "\\n header1,header2\n 1,2\n 10,20\n " ) with open(lowerCAmelCase_ , "w" ) as f: f.write(lowerCAmelCase_ ) return str(lowerCAmelCase_ ) @pytest.fixture def _A ( lowerCAmelCase_ : Any ): """simple docstring""" lowerCAmelCase__ = tmp_path / "malformed_file.csv" lowerCAmelCase__ = textwrap.dedent( "\\n header1,header2\n 1,2\n 10,20,\n " ) with open(lowerCAmelCase_ , "w" ) as f: f.write(lowerCAmelCase_ ) return str(lowerCAmelCase_ ) @pytest.fixture def _A ( lowerCAmelCase_ : List[str] , lowerCAmelCase_ : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = tmp_path / "csv_with_image.csv" lowerCAmelCase__ = textwrap.dedent( F'\\n image\n {image_file}\n ' ) with open(lowerCAmelCase_ , "w" ) as f: f.write(lowerCAmelCase_ ) return str(lowerCAmelCase_ ) @pytest.fixture def _A ( lowerCAmelCase_ : int ): """simple docstring""" lowerCAmelCase__ = tmp_path / "csv_with_label.csv" lowerCAmelCase__ = textwrap.dedent( "\\n label\n good\n bad\n good\n " ) with open(lowerCAmelCase_ , "w" ) as f: f.write(lowerCAmelCase_ ) return str(lowerCAmelCase_ ) @pytest.fixture def _A ( lowerCAmelCase_ : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = tmp_path / "csv_with_int_list.csv" lowerCAmelCase__ = textwrap.dedent( "\\n int_list\n 1 2 3\n 4 5 6\n 7 8 9\n " ) with open(lowerCAmelCase_ , "w" ) as f: f.write(lowerCAmelCase_ ) return str(lowerCAmelCase_ ) def _A ( lowerCAmelCase_ : Dict , lowerCAmelCase_ : Any , lowerCAmelCase_ : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = Csv() lowerCAmelCase__ = csv._generate_tables([[csv_file, malformed_csv_file]] ) with pytest.raises(lowerCAmelCase_ , match="Error tokenizing data" ): for _ in generator: pass assert any( record.levelname == "ERROR" and "Failed to read file" in record.message and os.path.basename(lowerCAmelCase_ ) in record.message for record in caplog.records ) @require_pil def _A ( lowerCAmelCase_ : Dict ): """simple docstring""" with open(lowerCAmelCase_ , encoding="utf-8" ) as f: lowerCAmelCase__ = f.read().splitlines()[1] lowerCAmelCase__ = Csv(encoding="utf-8" , features=Features({"image": Image()} ) ) lowerCAmelCase__ = csv._generate_tables([[csv_file_with_image]] ) lowerCAmelCase__ = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field("image" ).type == Image()() lowerCAmelCase__ = pa_table.to_pydict()["image"] assert generated_content == [{"path": image_file, "bytes": None}] def _A ( lowerCAmelCase_ : Union[str, Any] ): """simple docstring""" with open(lowerCAmelCase_ , encoding="utf-8" ) as f: lowerCAmelCase__ = f.read().splitlines()[1:] lowerCAmelCase__ = Csv(encoding="utf-8" , features=Features({"label": ClassLabel(names=["good", "bad"] )} ) ) lowerCAmelCase__ = csv._generate_tables([[csv_file_with_label]] ) lowerCAmelCase__ = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field("label" ).type == ClassLabel(names=["good", "bad"] )() lowerCAmelCase__ = pa_table.to_pydict()["label"] assert generated_content == [ClassLabel(names=["good", "bad"] ).straint(lowerCAmelCase_ ) for label in labels] def _A ( lowerCAmelCase_ : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = Csv(encoding="utf-8" , sep="," , converters={"int_list": lambda lowerCAmelCase_ : [int(lowerCAmelCase_ ) for i in x.split()]} ) lowerCAmelCase__ = csv._generate_tables([[csv_file_with_int_list]] ) lowerCAmelCase__ = pa.concat_tables([table for _, table in generator] ) assert pa.types.is_list(pa_table.schema.field("int_list" ).type ) lowerCAmelCase__ = pa_table.to_pydict()["int_list"] assert generated_content == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
61
import shutil import tempfile import unittest import numpy as np import pytest from transformers import is_speech_available, is_vision_available from transformers.testing_utils import require_torch if is_vision_available(): from transformers import TvltImageProcessor if is_speech_available(): from transformers import TvltFeatureExtractor from transformers import TvltProcessor @require_torch class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : Any ) -> int: lowerCAmelCase__ = "ZinengTang/tvlt-base" lowerCAmelCase__ = tempfile.mkdtemp() def a ( self : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: return TvltImageProcessor.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE__ ) def a ( self : int , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> str: return TvltFeatureExtractor.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] ) -> Any: shutil.rmtree(self.tmpdirname ) def a ( self : Any ) -> Union[str, Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) lowerCAmelCase__ = TvltProcessor.from_pretrained(self.tmpdirname ) self.assertIsInstance(processor.feature_extractor , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> List[Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([12_000] ) lowerCAmelCase__ = feature_extractor(SCREAMING_SNAKE_CASE__ , return_tensors="np" ) lowerCAmelCase__ = processor(audio=SCREAMING_SNAKE_CASE__ , return_tensors="np" ) for key in audio_dict.keys(): self.assertAlmostEqual(audio_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a ( self : Dict ) -> str: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([3, 224, 224] ) lowerCAmelCase__ = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors="np" ) lowerCAmelCase__ = processor(images=SCREAMING_SNAKE_CASE__ , return_tensors="np" ) for key in image_dict.keys(): self.assertAlmostEqual(image_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a ( self : int ) -> Any: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([12_000] ) lowerCAmelCase__ = np.ones([3, 224, 224] ) lowerCAmelCase__ = processor(audio=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , ["audio_values", "audio_mask", "pixel_values", "pixel_mask"] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE__ ): processor() def a ( self : Tuple ) -> Optional[Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( processor.model_input_names , image_processor.model_input_names + feature_extractor.model_input_names , msg="`processor` and `image_processor`+`feature_extractor` model input names do not match" , )
61
1
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
61
import os # Precomputes a list of the 100 first triangular numbers UpperCamelCase = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def _A ( ): """simple docstring""" lowerCAmelCase__ = os.path.dirname(os.path.realpath(lowerCAmelCase_ ) ) lowerCAmelCase__ = os.path.join(lowerCAmelCase_ , "words.txt" ) lowerCAmelCase__ = "" with open(lowerCAmelCase_ ) as f: lowerCAmelCase__ = f.readline() lowerCAmelCase__ = [word.strip("\"" ) for word in words.strip("\r\n" ).split("," )] lowerCAmelCase__ = [ word for word in [sum(ord(lowerCAmelCase_ ) - 64 for x in word ) for word in words] if word in TRIANGULAR_NUMBERS ] return len(lowerCAmelCase_ ) if __name__ == "__main__": print(solution())
61
1
import inspect import os import unittest from dataclasses import dataclass import torch from accelerate import Accelerator, DistributedDataParallelKwargs, GradScalerKwargs from accelerate.state import AcceleratorState from accelerate.test_utils import execute_subprocess_async, require_cuda, require_multi_gpu from accelerate.utils import KwargsHandler @dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 0 snake_case__ = False snake_case__ = 3.0 class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : Tuple ) -> List[str]: # If no defaults are changed, `to_kwargs` returns an empty dict. self.assertDictEqual(MockClass().to_kwargs() , {} ) self.assertDictEqual(MockClass(a=2 ).to_kwargs() , {"a": 2} ) self.assertDictEqual(MockClass(a=2 , b=SCREAMING_SNAKE_CASE__ ).to_kwargs() , {"a": 2, "b": True} ) self.assertDictEqual(MockClass(a=2 , c=2.25 ).to_kwargs() , {"a": 2, "c": 2.25} ) @require_cuda def a ( self : List[Any] ) -> str: # If no defaults are changed, `to_kwargs` returns an empty dict. lowerCAmelCase__ = GradScalerKwargs(init_scale=1_024 , growth_factor=2 ) AcceleratorState._reset_state() lowerCAmelCase__ = Accelerator(mixed_precision="fp16" , kwargs_handlers=[scaler_handler] ) print(accelerator.use_fpaa ) lowerCAmelCase__ = accelerator.scaler # Check the kwargs have been applied self.assertEqual(scaler._init_scale , 1_024.0 ) self.assertEqual(scaler._growth_factor , 2.0 ) # Check the other values are at the default self.assertEqual(scaler._backoff_factor , 0.5 ) self.assertEqual(scaler._growth_interval , 2_000 ) self.assertEqual(scaler._enabled , SCREAMING_SNAKE_CASE__ ) @require_multi_gpu def a ( self : List[str] ) -> Optional[int]: lowerCAmelCase__ = ["torchrun", f'--nproc_per_node={torch.cuda.device_count()}', inspect.getfile(self.__class__ )] execute_subprocess_async(SCREAMING_SNAKE_CASE__ , env=os.environ.copy() ) if __name__ == "__main__": UpperCamelCase = DistributedDataParallelKwargs(bucket_cap_mb=15, find_unused_parameters=True) UpperCamelCase = Accelerator(kwargs_handlers=[ddp_scaler]) UpperCamelCase = torch.nn.Linear(100, 200) UpperCamelCase = accelerator.prepare(model) # Check the values changed in kwargs UpperCamelCase = '' UpperCamelCase = model.bucket_bytes_cap // (1024 * 1024) if observed_bucket_cap_map != 15: error_msg += F"Kwargs badly passed, should have `15` but found {observed_bucket_cap_map}.\n" if model.find_unused_parameters is not True: error_msg += F"Kwargs badly passed, should have `True` but found {model.find_unused_parameters}.\n" # Check the values of the defaults if model.dim != 0: error_msg += F"Default value not respected, should have `0` but found {model.dim}.\n" if model.broadcast_buffers is not True: error_msg += F"Default value not respected, should have `True` but found {model.broadcast_buffers}.\n" if model.gradient_as_bucket_view is not False: error_msg += F"Default value not respected, should have `False` but found {model.gradient_as_bucket_view}.\n" # 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)
61
import random def _A ( lowerCAmelCase_ : Dict , lowerCAmelCase_ : int , lowerCAmelCase_ : Any ): """simple docstring""" lowerCAmelCase__ = a[left_index] lowerCAmelCase__ = left_index + 1 for j in range(left_index + 1 , lowerCAmelCase_ ): if a[j] < pivot: lowerCAmelCase__ , lowerCAmelCase__ = a[i], a[j] i += 1 lowerCAmelCase__ , lowerCAmelCase__ = a[i - 1], a[left_index] return i - 1 def _A ( lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : str ): """simple docstring""" if left < right: lowerCAmelCase__ = random.randint(lowerCAmelCase_ , right - 1 ) lowerCAmelCase__ , lowerCAmelCase__ = ( a[left], a[pivot], ) # switches the pivot with the left most bound lowerCAmelCase__ = partition(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) quick_sort_random( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # recursive quicksort to the left of the pivot point quick_sort_random( lowerCAmelCase_ , pivot_index + 1 , lowerCAmelCase_ ) # recursive quicksort to the right of the pivot point def _A ( ): """simple docstring""" lowerCAmelCase__ = input("Enter numbers separated by a comma:\n" ).strip() lowerCAmelCase__ = [int(lowerCAmelCase_ ) for item in user_input.split("," )] quick_sort_random(lowerCAmelCase_ , 0 , len(lowerCAmelCase_ ) ) print(lowerCAmelCase_ ) if __name__ == "__main__": main()
61
1
import os from typing import List, Optional, Union from ...image_processing_utils import BatchFeature from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType from ..auto import AutoTokenizer class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = ["image_processor", "tokenizer"] snake_case__ = "BlipImageProcessor" snake_case__ = "AutoTokenizer" def __init__( self : str , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple ) -> Dict: super().__init__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # add QFormer tokenizer lowerCAmelCase__ = qformer_tokenizer def __call__( self : Dict , SCREAMING_SNAKE_CASE__ : ImageInput = None , SCREAMING_SNAKE_CASE__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = False , SCREAMING_SNAKE_CASE__ : Union[bool, str, TruncationStrategy] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , **SCREAMING_SNAKE_CASE__ : List[Any] , ) -> BatchFeature: if images is None and text is None: raise ValueError("You have to specify at least images or text." ) lowerCAmelCase__ = BatchFeature() if text is not None: lowerCAmelCase__ = self.tokenizer( text=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , stride=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , return_overflowing_tokens=SCREAMING_SNAKE_CASE__ , return_special_tokens_mask=SCREAMING_SNAKE_CASE__ , return_offsets_mapping=SCREAMING_SNAKE_CASE__ , return_token_type_ids=SCREAMING_SNAKE_CASE__ , return_length=SCREAMING_SNAKE_CASE__ , verbose=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) encoding.update(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.qformer_tokenizer( text=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , stride=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , return_overflowing_tokens=SCREAMING_SNAKE_CASE__ , return_special_tokens_mask=SCREAMING_SNAKE_CASE__ , return_offsets_mapping=SCREAMING_SNAKE_CASE__ , return_token_type_ids=SCREAMING_SNAKE_CASE__ , return_length=SCREAMING_SNAKE_CASE__ , verbose=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = qformer_text_encoding.pop("input_ids" ) lowerCAmelCase__ = qformer_text_encoding.pop("attention_mask" ) if images is not None: lowerCAmelCase__ = self.image_processor(SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ ) encoding.update(SCREAMING_SNAKE_CASE__ ) return encoding def a ( self : Union[str, Any] , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : Any ) -> Dict: return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : Any , *SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : int ) -> Union[str, Any]: return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def a ( self : Dict ) -> List[Any]: lowerCAmelCase__ = self.tokenizer.model_input_names lowerCAmelCase__ = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : Dict ) -> Any: if os.path.isfile(SCREAMING_SNAKE_CASE__ ): raise ValueError(f'Provided path ({save_directory}) should be a directory, not a file' ) os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = os.path.join(SCREAMING_SNAKE_CASE__ , "qformer_tokenizer" ) self.qformer_tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) return super().save_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) @classmethod def a ( cls : Optional[Any] , SCREAMING_SNAKE_CASE__ : Dict , **SCREAMING_SNAKE_CASE__ : int ) -> str: lowerCAmelCase__ = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ , subfolder="qformer_tokenizer" ) lowerCAmelCase__ = cls._get_arguments_from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) args.append(SCREAMING_SNAKE_CASE__ ) return cls(*SCREAMING_SNAKE_CASE__ )
61
import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process UpperCamelCase = logging.getLogger(__name__) @dataclass class __lowerCamelCase : """simple docstring""" snake_case__ = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) snake_case__ = field( default="NER" , metadata={"help": "Task type to fine tune in training (e.g. NER, POS, etc)"} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) snake_case__ = field(default=UpperCamelCase__ , metadata={"help": "Set this flag to use fast tokenization."} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) @dataclass class __lowerCamelCase : """simple docstring""" snake_case__ = field( metadata={"help": "The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."} , ) snake_case__ = field( default=1_2_8 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Overwrite the cached training and evaluation sets"} ) def _A ( ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. Use' " --overwrite_output_dir to overcome." ) lowerCAmelCase__ = import_module("tasks" ) try: lowerCAmelCase__ = getattr(lowerCAmelCase_ , model_args.task_type ) lowerCAmelCase__ = token_classification_task_clazz() except AttributeError: raise ValueError( F'Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. ' F'Available tasks classes are: {TokenClassificationTask.__subclasses__()}' ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("Training/evaluation parameters %s" , lowerCAmelCase_ ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task lowerCAmelCase__ = token_classification_task.get_labels(data_args.labels ) lowerCAmelCase__ = dict(enumerate(lowerCAmelCase_ ) ) lowerCAmelCase__ = len(lowerCAmelCase_ ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowerCAmelCase__ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=lowerCAmelCase_ , idalabel=lowerCAmelCase_ , labelaid={label: i for i, label in enumerate(lowerCAmelCase_ )} , cache_dir=model_args.cache_dir , ) lowerCAmelCase__ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast , ) lowerCAmelCase__ = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , ) # Get datasets lowerCAmelCase__ = ( TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) lowerCAmelCase__ = ( TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def align_predictions(lowerCAmelCase_ : np.ndarray , lowerCAmelCase_ : np.ndarray ) -> Tuple[List[int], List[int]]: lowerCAmelCase__ = np.argmax(lowerCAmelCase_ , axis=2 ) lowerCAmelCase__ , lowerCAmelCase__ = preds.shape lowerCAmelCase__ = [[] for _ in range(lowerCAmelCase_ )] lowerCAmelCase__ = [[] for _ in range(lowerCAmelCase_ )] for i in range(lowerCAmelCase_ ): for j in range(lowerCAmelCase_ ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(lowerCAmelCase_ : EvalPrediction ) -> Dict: lowerCAmelCase__ , lowerCAmelCase__ = align_predictions(p.predictions , p.label_ids ) return { "accuracy_score": accuracy_score(lowerCAmelCase_ , lowerCAmelCase_ ), "precision": precision_score(lowerCAmelCase_ , lowerCAmelCase_ ), "recall": recall_score(lowerCAmelCase_ , lowerCAmelCase_ ), "f1": fa_score(lowerCAmelCase_ , lowerCAmelCase_ ), } # Data collator lowerCAmelCase__ = DataCollatorWithPadding(lowerCAmelCase_ , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer lowerCAmelCase__ = Trainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , train_dataset=lowerCAmelCase_ , eval_dataset=lowerCAmelCase_ , compute_metrics=lowerCAmelCase_ , data_collator=lowerCAmelCase_ , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation lowerCAmelCase__ = {} if training_args.do_eval: logger.info("*** Evaluate ***" ) lowerCAmelCase__ = trainer.evaluate() lowerCAmelCase__ = os.path.join(training_args.output_dir , "eval_results.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: logger.info("***** Eval results *****" ) for key, value in result.items(): logger.info(" %s = %s" , lowerCAmelCase_ , lowerCAmelCase_ ) writer.write("%s = %s\n" % (key, value) ) results.update(lowerCAmelCase_ ) # Predict if training_args.do_predict: lowerCAmelCase__ = TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = trainer.predict(lowerCAmelCase_ ) lowerCAmelCase__ , lowerCAmelCase__ = align_predictions(lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ = os.path.join(training_args.output_dir , "test_results.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: for key, value in metrics.items(): logger.info(" %s = %s" , lowerCAmelCase_ , lowerCAmelCase_ ) writer.write("%s = %s\n" % (key, value) ) # Save predictions lowerCAmelCase__ = os.path.join(training_args.output_dir , "test_predictions.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: with open(os.path.join(data_args.data_dir , "test.txt" ) , "r" ) as f: token_classification_task.write_predictions_to_file(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return results def _A ( lowerCAmelCase_ : Tuple ): """simple docstring""" main() if __name__ == "__main__": main()
61
1
from typing import Dict from transformers import EvalPrediction, HfArgumentParser, TrainingArguments, is_torch_available from transformers.testing_utils import ( TestCasePlus, execute_subprocess_async, get_torch_dist_unique_port, require_torch_multi_gpu, require_torch_neuroncore, ) from transformers.training_args import ParallelMode from transformers.utils import logging UpperCamelCase = logging.get_logger(__name__) if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset from transformers import Trainer class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : int = 101 ) -> List[str]: lowerCAmelCase__ = length def __len__( self : Tuple ) -> Union[str, Any]: return self.length def __getitem__( self : Dict , SCREAMING_SNAKE_CASE__ : str ) -> int: return i class __lowerCamelCase : """simple docstring""" def __call__( self : int , SCREAMING_SNAKE_CASE__ : List[str] ) -> int: return {"input_ids": torch.tensor(SCREAMING_SNAKE_CASE__ ), "labels": torch.tensor(SCREAMING_SNAKE_CASE__ )} class __lowerCamelCase ( nn.Module ): """simple docstring""" def __init__( self : Optional[int] ) -> Any: super().__init__() # Add some (unused) params otherwise DDP will complain. lowerCAmelCase__ = nn.Linear(120 , 80 ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[str]=None ) -> Optional[Any]: if labels is not None: return torch.tensor(0.0 , device=input_ids.device ), input_ids else: return input_ids class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" @require_torch_neuroncore def a ( self : Tuple ) -> Optional[Any]: lowerCAmelCase__ = f'--nproc_per_node=2\n --master_port={get_torch_dist_unique_port()}\n {self.test_file_dir}/test_trainer_distributed.py\n '.split() lowerCAmelCase__ = self.get_auto_remove_tmp_dir() lowerCAmelCase__ = f'--output_dir {output_dir}'.split() lowerCAmelCase__ = ["torchrun"] + distributed_args + args execute_subprocess_async(SCREAMING_SNAKE_CASE__ , env=self.get_env() ) # successful return here == success - any errors would have caused an error in the sub-call class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" @require_torch_multi_gpu def a ( self : Dict ) -> List[str]: lowerCAmelCase__ = f'--nproc_per_node={torch.cuda.device_count()}\n --master_port={get_torch_dist_unique_port()}\n {self.test_file_dir}/test_trainer_distributed.py\n '.split() lowerCAmelCase__ = self.get_auto_remove_tmp_dir() lowerCAmelCase__ = f'--output_dir {output_dir}'.split() lowerCAmelCase__ = ["torchrun"] + distributed_args + args execute_subprocess_async(SCREAMING_SNAKE_CASE__ , env=self.get_env() ) # successful return here == success - any errors would have caused an error in the sub-call if __name__ == "__main__": # The script below is meant to be run under torch.distributed, on a machine with multiple GPUs: # # PYTHONPATH="src" python -m torch.distributed.run --nproc_per_node 2 --output_dir output_dir ./tests/test_trainer_distributed.py UpperCamelCase = HfArgumentParser((TrainingArguments,)) UpperCamelCase = parser.parse_args_into_dataclasses()[0] logger.warning( F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}, """ F"""distributed training: {training_args.parallel_mode != ParallelMode.NOT_DISTRIBUTED}""" ) # Essentially, what we want to verify in the distributed case is that we get all samples back, # in the right order. (this is crucial for prediction for instance) for dataset_length in [101, 40, 7]: UpperCamelCase = DummyDataset(dataset_length) def _A ( lowerCAmelCase_ : EvalPrediction ): """simple docstring""" lowerCAmelCase__ = list(range(len(lowerCAmelCase_ ) ) ) lowerCAmelCase__ = p.predictions.tolist() == sequential and p.label_ids.tolist() == sequential if not success and training_args.local_rank == 0: logger.warning( "Predictions and/or labels do not match expected results:\n - predictions: " F'{p.predictions.tolist()}\n - labels: {p.label_ids.tolist()}\n - expected: {sequential}' ) return {"success": success} UpperCamelCase = Trainer( model=DummyModel(), args=training_args, data_collator=DummyDataCollator(), eval_dataset=dataset, compute_metrics=compute_metrics, ) UpperCamelCase = trainer.evaluate() logger.info(metrics) if metrics["eval_success"] is not True: logger.error(metrics) exit(1) UpperCamelCase = trainer.predict(dataset) logger.info(p.metrics) if p.metrics["test_success"] is not True: logger.error(p.metrics) exit(1) UpperCamelCase = 2 UpperCamelCase = trainer.evaluate() logger.info(metrics) if metrics["eval_success"] is not True: logger.error(metrics) exit(1) UpperCamelCase = trainer.predict(dataset) logger.info(p.metrics) if p.metrics["test_success"] is not True: logger.error(p.metrics) exit(1) UpperCamelCase = None
61
import os import re from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'vocab_file': 'spiece.model'} UpperCamelCase = { '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' ), } } UpperCamelCase = { 'google/bigbird-roberta-base': 4096, 'google/bigbird-roberta-large': 4096, 'google/bigbird-base-trivia-itc': 4096, } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ = ["input_ids", "attention_mask"] snake_case__ = [] def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str]="<unk>" , SCREAMING_SNAKE_CASE__ : List[str]="<s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="</s>" , SCREAMING_SNAKE_CASE__ : Tuple="<pad>" , SCREAMING_SNAKE_CASE__ : Any="[SEP]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[MASK]" , SCREAMING_SNAKE_CASE__ : List[Any]="[CLS]" , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None , **SCREAMING_SNAKE_CASE__ : List[Any] , ) -> None: lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else bos_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else eos_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else unk_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else pad_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cls_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else sep_token # Mask token behave like a normal word, i.e. include the space before it lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else mask_token lowerCAmelCase__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = vocab_file lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def a ( self : List[str] ) -> List[str]: return self.sp_model.get_piece_size() def a ( self : List[str] ) -> Dict: lowerCAmelCase__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Optional[int] ) -> Any: lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Any: lowerCAmelCase__ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowerCAmelCase__ = {} lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: return self.sp_model.piece_to_id(SCREAMING_SNAKE_CASE__ ) def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[str]: lowerCAmelCase__ = self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) return token def a ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: lowerCAmelCase__ = [] lowerCAmelCase__ = "" lowerCAmelCase__ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) + token lowerCAmelCase__ = True lowerCAmelCase__ = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) return out_string.strip() def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : bool = True , **SCREAMING_SNAKE_CASE__ : int , ) -> str: lowerCAmelCase__ = kwargs.pop("use_source_tokenizer" , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 lowerCAmelCase__ = [] lowerCAmelCase__ = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = [] sub_texts.append(SCREAMING_SNAKE_CASE__ ) else: current_sub_text.append(SCREAMING_SNAKE_CASE__ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) ) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: lowerCAmelCase__ = re.sub(r" (\[(MASK|SEP)\])" , r"\1" , " ".join(SCREAMING_SNAKE_CASE__ ) ) else: lowerCAmelCase__ = "".join(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: lowerCAmelCase__ = self.clean_up_tokenization(SCREAMING_SNAKE_CASE__ ) return clean_text else: return text def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return lowerCAmelCase__ = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE__ , "wb" ) as fi: lowerCAmelCase__ = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,) def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] lowerCAmelCase__ = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
61
1
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging UpperCamelCase = logging.get_logger(__name__) if is_vision_available(): import PIL class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = ["pixel_values"] def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Union[int, float] = 1 / 255 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : bool = True , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> None: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = size if size is not None else {"shortest_edge": 224} lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = crop_size if crop_size is not None else {"height": 224, "width": 224} lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ , param_name="crop_size" ) lowerCAmelCase__ = do_resize lowerCAmelCase__ = size lowerCAmelCase__ = resample lowerCAmelCase__ = do_center_crop lowerCAmelCase__ = crop_size lowerCAmelCase__ = do_rescale lowerCAmelCase__ = rescale_factor lowerCAmelCase__ = do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else OPENAI_CLIP_MEAN lowerCAmelCase__ = image_std if image_std is not None else OPENAI_CLIP_STD lowerCAmelCase__ = do_convert_rgb def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> np.ndarray: lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) if "shortest_edge" not in size: raise ValueError(f'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) lowerCAmelCase__ = get_resize_output_image_size(SCREAMING_SNAKE_CASE__ , size=size["shortest_edge"] , default_to_square=SCREAMING_SNAKE_CASE__ ) return resize(SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : int , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Dict , ) -> np.ndarray: lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ ) if "height" not in size or "width" not in size: raise ValueError(f'The `size` parameter must contain the keys (height, width). Got {size.keys()}' ) return center_crop(SCREAMING_SNAKE_CASE__ , size=(size["height"], size["width"]) , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[int, float] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Tuple , ) -> str: return rescale(SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : str , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Optional[int] , ) -> np.ndarray: return normalize(SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : ImageInput , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : int = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE__ : Optional[ChannelDimension] = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE__ : List[Any] , ) -> PIL.Image.Image: lowerCAmelCase__ = do_resize if do_resize is not None else self.do_resize lowerCAmelCase__ = size if size is not None else self.size lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , param_name="size" , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = resample if resample is not None else self.resample lowerCAmelCase__ = do_center_crop if do_center_crop is not None else self.do_center_crop lowerCAmelCase__ = crop_size if crop_size is not None else self.crop_size lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , param_name="crop_size" , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = do_rescale if do_rescale is not None else self.do_rescale lowerCAmelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCAmelCase__ = do_normalize if do_normalize is not None else self.do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else self.image_mean lowerCAmelCase__ = image_std if image_std is not None else self.image_std lowerCAmelCase__ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb lowerCAmelCase__ = make_list_of_images(SCREAMING_SNAKE_CASE__ ) if not valid_images(SCREAMING_SNAKE_CASE__ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # PIL RGBA images are converted to RGB if do_convert_rgb: lowerCAmelCase__ = [convert_to_rgb(SCREAMING_SNAKE_CASE__ ) for image in images] # All transformations expect numpy arrays. lowerCAmelCase__ = [to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if do_resize: lowerCAmelCase__ = [self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images] if do_center_crop: lowerCAmelCase__ = [self.center_crop(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ ) for image in images] if do_rescale: lowerCAmelCase__ = [self.rescale(image=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ ) for image in images] if do_normalize: lowerCAmelCase__ = [self.normalize(image=SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = {"pixel_values": images} return BatchFeature(data=SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ )
61
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { 'sayakpaul/vit-msn-base': 'https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json', # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "vit_msn" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple=768 , SCREAMING_SNAKE_CASE__ : Optional[Any]=12 , SCREAMING_SNAKE_CASE__ : List[str]=12 , SCREAMING_SNAKE_CASE__ : Dict=3_072 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.0 , SCREAMING_SNAKE_CASE__ : int=0.0 , SCREAMING_SNAKE_CASE__ : List[str]=0.02 , SCREAMING_SNAKE_CASE__ : List[str]=1e-0_6 , SCREAMING_SNAKE_CASE__ : Dict=224 , SCREAMING_SNAKE_CASE__ : Optional[int]=16 , SCREAMING_SNAKE_CASE__ : Dict=3 , SCREAMING_SNAKE_CASE__ : Dict=True , **SCREAMING_SNAKE_CASE__ : Tuple , ) -> int: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = initializer_range lowerCAmelCase__ = layer_norm_eps lowerCAmelCase__ = image_size lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = qkv_bias
61
1
from __future__ import annotations from collections import deque from collections.abc import Sequence from dataclasses import dataclass from typing import Any @dataclass class __lowerCamelCase : """simple docstring""" snake_case__ = 42 snake_case__ = None snake_case__ = None def _A ( ): """simple docstring""" lowerCAmelCase__ = Node(1 ) lowerCAmelCase__ = Node(2 ) lowerCAmelCase__ = Node(3 ) lowerCAmelCase__ = Node(4 ) lowerCAmelCase__ = Node(5 ) return tree def _A ( lowerCAmelCase_ : Node | None ): """simple docstring""" return [root.data, *preorder(root.left ), *preorder(root.right )] if root else [] def _A ( lowerCAmelCase_ : Node | None ): """simple docstring""" return postorder(root.left ) + postorder(root.right ) + [root.data] if root else [] def _A ( lowerCAmelCase_ : Node | None ): """simple docstring""" return [*inorder(root.left ), root.data, *inorder(root.right )] if root else [] def _A ( lowerCAmelCase_ : Node | None ): """simple docstring""" return (max(height(root.left ) , height(root.right ) ) + 1) if root else 0 def _A ( lowerCAmelCase_ : Node | None ): """simple docstring""" lowerCAmelCase__ = [] if root is None: return output lowerCAmelCase__ = deque([root] ) while process_queue: lowerCAmelCase__ = process_queue.popleft() output.append(node.data ) if node.left: process_queue.append(node.left ) if node.right: process_queue.append(node.right ) return output def _A ( lowerCAmelCase_ : Node | None , lowerCAmelCase_ : int ): """simple docstring""" lowerCAmelCase__ = [] def populate_output(lowerCAmelCase_ : Node | None , lowerCAmelCase_ : int ) -> None: if not root: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.left , level - 1 ) populate_output(root.right , level - 1 ) populate_output(lowerCAmelCase_ , lowerCAmelCase_ ) return output def _A ( lowerCAmelCase_ : Node | None , lowerCAmelCase_ : int ): """simple docstring""" lowerCAmelCase__ = [] def populate_output(lowerCAmelCase_ : Node | None , lowerCAmelCase_ : int ) -> None: if root is None: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.right , level - 1 ) populate_output(root.left , level - 1 ) populate_output(lowerCAmelCase_ , lowerCAmelCase_ ) return output def _A ( lowerCAmelCase_ : Node | None ): """simple docstring""" if root is None: return [] lowerCAmelCase__ = [] lowerCAmelCase__ = 0 lowerCAmelCase__ = height(lowerCAmelCase_ ) for h in range(1 , height_tree + 1 ): if not flag: output.append(get_nodes_from_left_to_right(lowerCAmelCase_ , lowerCAmelCase_ ) ) lowerCAmelCase__ = 1 else: output.append(get_nodes_from_right_to_left(lowerCAmelCase_ , lowerCAmelCase_ ) ) lowerCAmelCase__ = 0 return output def _A ( ): # Main function for testing. """simple docstring""" lowerCAmelCase__ = make_tree() print(F'In-order Traversal: {inorder(lowerCAmelCase_ )}' ) print(F'Pre-order Traversal: {preorder(lowerCAmelCase_ )}' ) print(F'Post-order Traversal: {postorder(lowerCAmelCase_ )}' , "\n" ) print(F'Height of Tree: {height(lowerCAmelCase_ )}' , "\n" ) print("Complete Level Order Traversal: " ) print(level_order(lowerCAmelCase_ ) , "\n" ) print("Level-wise order Traversal: " ) for level in range(1 , height(lowerCAmelCase_ ) + 1 ): print(F'Level {level}:' , get_nodes_from_left_to_right(lowerCAmelCase_ , level=lowerCAmelCase_ ) ) print("\nZigZag order Traversal: " ) print(zigzag(lowerCAmelCase_ ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
61
import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def __init__( self : List[Any] , *SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> None: warnings.warn( "The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use FlavaImageProcessor instead." , SCREAMING_SNAKE_CASE__ , ) super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
61
1
import fire from transformers import AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer def _A ( lowerCAmelCase_ : str , lowerCAmelCase_ : str , **lowerCAmelCase_ : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = AutoConfig.from_pretrained(lowerCAmelCase_ , **lowerCAmelCase_ ) lowerCAmelCase__ = 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)
61
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import ( BaseOutput, OptionalDependencyNotAvailable, is_flax_available, is_k_diffusion_available, is_k_diffusion_version, is_onnx_available, is_torch_available, is_transformers_available, is_transformers_version, ) @dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_cycle_diffusion import CycleDiffusionPipeline from .pipeline_stable_diffusion import StableDiffusionPipeline from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from .pipeline_stable_unclip import StableUnCLIPPipeline from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline from .safety_checker import StableDiffusionSafetyChecker from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.25.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline else: from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.26.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionPixaPixZeroPipeline, ) else: from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline try: if not ( is_torch_available() and is_transformers_available() and is_k_diffusion_available() and is_k_diffusion_version('>=', '0.0.12') ): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline try: if not (is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_onnx_objects import * # noqa F403 else: from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline if is_transformers_available() and is_flax_available(): import flax @flax.struct.dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline from .safety_checker_flax import FlaxStableDiffusionSafetyChecker
61
1
import unittest from typing import Dict, List, Optional, Union import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import BridgeTowerImageProcessor class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : int = 32 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Union[int, float] = 1 / 255 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = [0.48_145_466, 0.4_578_275, 0.40_821_073] , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = [0.26_862_954, 0.26_130_258, 0.27_577_711] , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Dict=7 , SCREAMING_SNAKE_CASE__ : List[Any]=30 , SCREAMING_SNAKE_CASE__ : Optional[Any]=400 , SCREAMING_SNAKE_CASE__ : Any=3 , ) -> Tuple: lowerCAmelCase__ = parent lowerCAmelCase__ = do_resize lowerCAmelCase__ = size if size is not None else {"shortest_edge": 288} lowerCAmelCase__ = size_divisor lowerCAmelCase__ = do_rescale lowerCAmelCase__ = rescale_factor lowerCAmelCase__ = do_normalize lowerCAmelCase__ = do_center_crop lowerCAmelCase__ = image_mean lowerCAmelCase__ = image_std lowerCAmelCase__ = do_pad lowerCAmelCase__ = batch_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = min_resolution lowerCAmelCase__ = max_resolution def a ( self : str ) -> Tuple: return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, "size_divisor": self.size_divisor, } def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Any=False ) -> Optional[Any]: if not batched: lowerCAmelCase__ = self.size["shortest_edge"] lowerCAmelCase__ = image_inputs[0] if isinstance(SCREAMING_SNAKE_CASE__ , Image.Image ): lowerCAmelCase__ , lowerCAmelCase__ = image.size else: lowerCAmelCase__ , lowerCAmelCase__ = image.shape[1], image.shape[2] lowerCAmelCase__ = size / min(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if h < w: lowerCAmelCase__ , lowerCAmelCase__ = size, scale * w else: lowerCAmelCase__ , lowerCAmelCase__ = scale * h, size lowerCAmelCase__ = int((1_333 / 800) * size ) if max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) > max_size: lowerCAmelCase__ = max_size / max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = newh * scale lowerCAmelCase__ = neww * scale lowerCAmelCase__ , lowerCAmelCase__ = int(newh + 0.5 ), int(neww + 0.5 ) lowerCAmelCase__ , lowerCAmelCase__ = ( newh // self.size_divisor * self.size_divisor, neww // self.size_divisor * self.size_divisor, ) else: lowerCAmelCase__ = [] for image in image_inputs: lowerCAmelCase__ , lowerCAmelCase__ = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : item[0] )[0] lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = BridgeTowerImageProcessor if is_vision_available() else None def a ( self : Tuple ) -> int: lowerCAmelCase__ = BridgeTowerImageProcessingTester(self ) @property def a ( self : str ) -> Optional[int]: return self.image_processor_tester.prepare_image_processor_dict() def a ( self : List[Any] ) -> Dict: lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "image_mean" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "image_std" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "do_normalize" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "do_resize" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "size" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "size_divisor" ) ) def a ( self : Any ) -> Tuple: pass def a ( self : Tuple ) -> Any: # Initialize image processor lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input lowerCAmelCase__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values lowerCAmelCase__ , lowerCAmelCase__ = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched lowerCAmelCase__ = image_processing(SCREAMING_SNAKE_CASE__ , return_tensors="pt" ).pixel_values lowerCAmelCase__ , lowerCAmelCase__ = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def a ( self : Optional[Any] ) -> List[Any]: # Initialize image processor lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCAmelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) # Test not batched input lowerCAmelCase__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values lowerCAmelCase__ , lowerCAmelCase__ = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched lowerCAmelCase__ = image_processing(SCREAMING_SNAKE_CASE__ , return_tensors="pt" ).pixel_values lowerCAmelCase__ , lowerCAmelCase__ = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def a ( self : Optional[Any] ) -> Tuple: # Initialize image processor lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCAmelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input lowerCAmelCase__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values lowerCAmelCase__ , lowerCAmelCase__ = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched lowerCAmelCase__ = image_processing(SCREAMING_SNAKE_CASE__ , return_tensors="pt" ).pixel_values lowerCAmelCase__ , lowerCAmelCase__ = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , )
61
def _A ( lowerCAmelCase_ : int ): """simple docstring""" if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("'float' object cannot be interpreted as an integer" ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("'str' object cannot be interpreted as an integer" ) if num == 0: return "0b0" lowerCAmelCase__ = False if num < 0: lowerCAmelCase__ = True lowerCAmelCase__ = -num lowerCAmelCase__ = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(lowerCAmelCase_ ) for e in binary ) return "0b" + "".join(str(lowerCAmelCase_ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
61
1
import shutil import tempfile import unittest import numpy as np import pytest from transformers import is_speech_available, is_vision_available from transformers.testing_utils import require_torch if is_vision_available(): from transformers import TvltImageProcessor if is_speech_available(): from transformers import TvltFeatureExtractor from transformers import TvltProcessor @require_torch class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : Any ) -> int: lowerCAmelCase__ = "ZinengTang/tvlt-base" lowerCAmelCase__ = tempfile.mkdtemp() def a ( self : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: return TvltImageProcessor.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE__ ) def a ( self : int , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> str: return TvltFeatureExtractor.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] ) -> Any: shutil.rmtree(self.tmpdirname ) def a ( self : Any ) -> Union[str, Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) lowerCAmelCase__ = TvltProcessor.from_pretrained(self.tmpdirname ) self.assertIsInstance(processor.feature_extractor , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> List[Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([12_000] ) lowerCAmelCase__ = feature_extractor(SCREAMING_SNAKE_CASE__ , return_tensors="np" ) lowerCAmelCase__ = processor(audio=SCREAMING_SNAKE_CASE__ , return_tensors="np" ) for key in audio_dict.keys(): self.assertAlmostEqual(audio_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a ( self : Dict ) -> str: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([3, 224, 224] ) lowerCAmelCase__ = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors="np" ) lowerCAmelCase__ = processor(images=SCREAMING_SNAKE_CASE__ , return_tensors="np" ) for key in image_dict.keys(): self.assertAlmostEqual(image_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a ( self : int ) -> Any: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([12_000] ) lowerCAmelCase__ = np.ones([3, 224, 224] ) lowerCAmelCase__ = processor(audio=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , ["audio_values", "audio_mask", "pixel_values", "pixel_mask"] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE__ ): processor() def a ( self : Tuple ) -> Optional[Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( processor.model_input_names , image_processor.model_input_names + feature_extractor.model_input_names , msg="`processor` and `image_processor`+`feature_extractor` model input names do not match" , )
61
from __future__ import annotations UpperCamelCase = '#' class __lowerCamelCase : """simple docstring""" def __init__( self : Dict ) -> None: lowerCAmelCase__ = {} def a ( self : Any , SCREAMING_SNAKE_CASE__ : str ) -> None: lowerCAmelCase__ = self._trie for char in text: if char not in trie: lowerCAmelCase__ = {} lowerCAmelCase__ = trie[char] lowerCAmelCase__ = True def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : str ) -> tuple | list: lowerCAmelCase__ = self._trie for char in prefix: if char in trie: lowerCAmelCase__ = trie[char] else: return [] return self._elements(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : dict ) -> tuple: lowerCAmelCase__ = [] for c, v in d.items(): lowerCAmelCase__ = [" "] if c == END else [(c + s) for s in self._elements(SCREAMING_SNAKE_CASE__ )] result.extend(SCREAMING_SNAKE_CASE__ ) return tuple(SCREAMING_SNAKE_CASE__ ) UpperCamelCase = Trie() UpperCamelCase = ('depart', 'detergent', 'daring', 'dog', 'deer', 'deal') for word in words: trie.insert_word(word) def _A ( lowerCAmelCase_ : str ): """simple docstring""" lowerCAmelCase__ = trie.find_word(lowerCAmelCase_ ) return tuple(string + word for word in suffixes ) def _A ( ): """simple docstring""" print(autocomplete_using_trie("de" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
61
1
import os import unittest from transformers.models.phobert.tokenization_phobert import VOCAB_FILES_NAMES, PhobertTokenizer from ...test_tokenization_common import TokenizerTesterMixin class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = PhobertTokenizer snake_case__ = False def a ( self : Union[str, Any] ) -> str: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt lowerCAmelCase__ = ["T@@", "i", "I", "R@@", "r", "e@@"] lowerCAmelCase__ = dict(zip(SCREAMING_SNAKE_CASE__ , range(len(SCREAMING_SNAKE_CASE__ ) ) ) ) lowerCAmelCase__ = ["#version: 0.2", "l à</w>"] lowerCAmelCase__ = {"unk_token": "<unk>"} lowerCAmelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) lowerCAmelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: for token in vocab_tokens: fp.write(f'{token} {vocab_tokens[token]}\n' ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(SCREAMING_SNAKE_CASE__ ) ) def a ( self : Tuple , **SCREAMING_SNAKE_CASE__ : int ) -> List[Any]: kwargs.update(self.special_tokens_map ) return PhobertTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Optional[int]: lowerCAmelCase__ = "Tôi là VinAI Research" lowerCAmelCase__ = "T<unk> i <unk> <unk> <unk> <unk> <unk> <unk> I Re<unk> e<unk> <unk> <unk> <unk>" return input_text, output_text def a ( self : List[str] ) -> str: lowerCAmelCase__ = PhobertTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) lowerCAmelCase__ = "Tôi là VinAI Research" lowerCAmelCase__ = "T@@ ô@@ i l@@ à V@@ i@@ n@@ A@@ I R@@ e@@ s@@ e@@ a@@ r@@ c@@ h".split() lowerCAmelCase__ = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) print(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokens + [tokenizer.unk_token] lowerCAmelCase__ = [4, 3, 5, 3, 3, 3, 3, 3, 3, 6, 7, 9, 3, 9, 3, 3, 3, 3, 3] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ )
61
import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, TimesformerForVideoClassification, TimesformerModel, ) from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class __lowerCamelCase : """simple docstring""" def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple=13 , SCREAMING_SNAKE_CASE__ : Optional[Any]=10 , SCREAMING_SNAKE_CASE__ : Optional[int]=3 , SCREAMING_SNAKE_CASE__ : List[str]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=2 , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : Optional[int]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : List[Any]=37 , SCREAMING_SNAKE_CASE__ : int="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Any=10 , SCREAMING_SNAKE_CASE__ : int=0.02 , SCREAMING_SNAKE_CASE__ : Tuple="divided_space_time" , SCREAMING_SNAKE_CASE__ : Optional[int]=None , ) -> List[str]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = image_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_frames lowerCAmelCase__ = is_training lowerCAmelCase__ = use_labels lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = attention_type lowerCAmelCase__ = initializer_range lowerCAmelCase__ = scope lowerCAmelCase__ = num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token lowerCAmelCase__ = (image_size // patch_size) ** 2 lowerCAmelCase__ = (num_frames) * self.num_patches_per_frame + 1 def a ( self : int ) -> Tuple: lowerCAmelCase__ = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase__ = None if self.use_labels: lowerCAmelCase__ = ids_tensor([self.batch_size] , self.num_labels ) lowerCAmelCase__ = self.get_config() return config, pixel_values, labels def a ( self : List[Any] ) -> Any: lowerCAmelCase__ = TimesformerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , initializer_range=self.initializer_range , attention_type=self.attention_type , ) lowerCAmelCase__ = self.num_labels return config def a ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: lowerCAmelCase__ = TimesformerModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple ) -> Tuple: lowerCAmelCase__ = TimesformerForVideoClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) # verify the logits shape lowerCAmelCase__ = torch.Size((self.batch_size, self.num_labels) ) self.parent.assertEqual(result.logits.shape , SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> Dict: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else () snake_case__ = ( {"feature-extraction": TimesformerModel, "video-classification": TimesformerForVideoClassification} if is_torch_available() else {} ) snake_case__ = False snake_case__ = False snake_case__ = False snake_case__ = False def a ( self : List[str] ) -> List[Any]: lowerCAmelCase__ = TimesformerModelTester(self ) lowerCAmelCase__ = ConfigTester( self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ , hidden_size=37 ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple=False ) -> str: lowerCAmelCase__ = copy.deepcopy(SCREAMING_SNAKE_CASE__ ) if return_labels: if model_class in get_values(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) return inputs_dict def a ( self : Optional[Any] ) -> List[str]: self.config_tester.run_common_tests() @unittest.skip(reason="TimeSformer does not use inputs_embeds" ) def a ( self : Union[str, Any] ) -> Tuple: pass def a ( self : Dict ) -> List[str]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowerCAmelCase__ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__ , nn.Linear ) ) def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase__ = [*signature.parameters.keys()] lowerCAmelCase__ = ["pixel_values"] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] ) -> Tuple: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*SCREAMING_SNAKE_CASE__ ) @slow def a ( self : str ) -> Tuple: for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase__ = TimesformerModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Dict: if not self.has_attentions: pass else: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ = True for model_class in self.all_model_classes: lowerCAmelCase__ = self.model_tester.seq_length lowerCAmelCase__ = self.model_tester.num_frames lowerCAmelCase__ = True lowerCAmelCase__ = False lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) lowerCAmelCase__ = len(SCREAMING_SNAKE_CASE__ ) # Check attention is always last and order is fine lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(out_len + 1 , len(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) def a ( self : List[str] ) -> Any: def check_hidden_states_output(SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] ): lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.hidden_states lowerCAmelCase__ = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _A ( ): """simple docstring""" lowerCAmelCase__ = hf_hub_download( repo_id="hf-internal-testing/spaghetti-video" , filename="eating_spaghetti.npy" , repo_type="dataset" ) lowerCAmelCase__ = np.load(lowerCAmelCase_ ) return list(lowerCAmelCase_ ) @require_torch @require_vision class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @cached_property def a ( self : Optional[Any] ) -> Union[str, Any]: # logits were tested with a different mean and std, so we use the same here return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) if is_vision_available() else None ) @slow def a ( self : Optional[Any] ) -> str: lowerCAmelCase__ = TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400" ).to( SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.default_image_processor lowerCAmelCase__ = prepare_video() lowerCAmelCase__ = image_processor(video[:8] , return_tensors="pt" ).to(SCREAMING_SNAKE_CASE__ ) # forward pass with torch.no_grad(): lowerCAmelCase__ = model(**SCREAMING_SNAKE_CASE__ ) # verify the logits lowerCAmelCase__ = torch.Size((1, 400) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = torch.tensor([-0.3_016, -0.7_713, -0.4_205] ).to(SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
1
import re from filelock import FileLock try: import nltk UpperCamelCase = True except (ImportError, ModuleNotFoundError): UpperCamelCase = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def _A ( lowerCAmelCase_ : str ): """simple docstring""" re.sub("<n>" , "" , lowerCAmelCase_ ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(lowerCAmelCase_ ) )
61
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _A ( ): """simple docstring""" lowerCAmelCase__ = ArgumentParser( description=( "PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes" ) ) # Optional arguments for the launch helper parser.add_argument("--num_cores" , type=lowerCAmelCase_ , default=1 , help="Number of TPU cores to use (1 or 8)." ) # positional parser.add_argument( "training_script" , type=lowerCAmelCase_ , help=( "The full path to the single TPU training " "program/script to be launched in parallel, " "followed by all the arguments for the " "training script" ) , ) # rest from the training program parser.add_argument("training_script_args" , nargs=lowerCAmelCase_ ) return parser.parse_args() def _A ( ): """simple docstring""" lowerCAmelCase__ = parse_args() # Import training_script as a module. lowerCAmelCase__ = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) lowerCAmelCase__ = script_fpath.stem lowerCAmelCase__ = importlib.import_module(lowerCAmelCase_ ) # Patch sys.argv lowerCAmelCase__ = [args.training_script] + args.training_script_args + ["--tpu_num_cores", str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
61
1
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel from transformers.utils import logging logging.set_verbosity_info() UpperCamelCase = logging.get_logger(__name__) def _A ( lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Union[str, Any]=False ): """simple docstring""" lowerCAmelCase__ = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F'blocks.{i}.norm1.weight', F'vit.encoder.layer.{i}.layernorm_before.weight') ) rename_keys.append((F'blocks.{i}.norm1.bias', F'vit.encoder.layer.{i}.layernorm_before.bias') ) rename_keys.append((F'blocks.{i}.attn.proj.weight', F'vit.encoder.layer.{i}.attention.output.dense.weight') ) rename_keys.append((F'blocks.{i}.attn.proj.bias', F'vit.encoder.layer.{i}.attention.output.dense.bias') ) rename_keys.append((F'blocks.{i}.norm2.weight', F'vit.encoder.layer.{i}.layernorm_after.weight') ) rename_keys.append((F'blocks.{i}.norm2.bias', F'vit.encoder.layer.{i}.layernorm_after.bias') ) rename_keys.append((F'blocks.{i}.mlp.fc1.weight', F'vit.encoder.layer.{i}.intermediate.dense.weight') ) rename_keys.append((F'blocks.{i}.mlp.fc1.bias', F'vit.encoder.layer.{i}.intermediate.dense.bias') ) rename_keys.append((F'blocks.{i}.mlp.fc2.weight', F'vit.encoder.layer.{i}.output.dense.weight') ) rename_keys.append((F'blocks.{i}.mlp.fc2.bias', F'vit.encoder.layer.{i}.output.dense.bias') ) # projection layer + position embeddings rename_keys.extend( [ ("cls_token", "vit.embeddings.cls_token"), ("patch_embed.proj.weight", "vit.embeddings.patch_embeddings.projection.weight"), ("patch_embed.proj.bias", "vit.embeddings.patch_embeddings.projection.bias"), ("pos_embed", "vit.embeddings.position_embeddings"), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("norm.weight", "layernorm.weight"), ("norm.bias", "layernorm.bias"), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" lowerCAmelCase__ = [(pair[0], pair[1][4:]) if pair[1].startswith("vit" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("norm.weight", "vit.layernorm.weight"), ("norm.bias", "vit.layernorm.bias"), ("head.weight", "classifier.weight"), ("head.bias", "classifier.bias"), ] ) return rename_keys def _A ( lowerCAmelCase_ : str , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : str=False ): """simple docstring""" for i in range(config.num_hidden_layers ): if base_model: lowerCAmelCase__ = "" else: lowerCAmelCase__ = "vit." # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) lowerCAmelCase__ = state_dict.pop(F'blocks.{i}.attn.qkv.weight' ) lowerCAmelCase__ = state_dict.pop(F'blocks.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict lowerCAmelCase__ = in_proj_weight[ : config.hidden_size, : ] lowerCAmelCase__ = in_proj_bias[: config.hidden_size] lowerCAmelCase__ = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] lowerCAmelCase__ = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] lowerCAmelCase__ = in_proj_weight[ -config.hidden_size :, : ] lowerCAmelCase__ = in_proj_bias[-config.hidden_size :] def _A ( lowerCAmelCase_ : List[str] ): """simple docstring""" lowerCAmelCase__ = ["head.weight", "head.bias"] for k in ignore_keys: state_dict.pop(lowerCAmelCase_ , lowerCAmelCase_ ) def _A ( lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : int ): """simple docstring""" lowerCAmelCase__ = dct.pop(lowerCAmelCase_ ) lowerCAmelCase__ = val def _A ( ): """simple docstring""" lowerCAmelCase__ = "http://images.cocodataset.org/val2017/000000039769.jpg" lowerCAmelCase__ = Image.open(requests.get(lowerCAmelCase_ , stream=lowerCAmelCase_ ).raw ) return im @torch.no_grad() def _A ( lowerCAmelCase_ : Tuple , lowerCAmelCase_ : str , lowerCAmelCase_ : Any=True ): """simple docstring""" lowerCAmelCase__ = ViTConfig() # patch_size if model_name[-1] == "8": lowerCAmelCase__ = 8 # set labels if required if not base_model: lowerCAmelCase__ = 1000 lowerCAmelCase__ = "huggingface/label-files" lowerCAmelCase__ = "imagenet-1k-id2label.json" lowerCAmelCase__ = json.load(open(hf_hub_download(lowerCAmelCase_ , lowerCAmelCase_ , repo_type="dataset" ) , "r" ) ) lowerCAmelCase__ = {int(lowerCAmelCase_ ): v for k, v in idalabel.items()} lowerCAmelCase__ = idalabel lowerCAmelCase__ = {v: k for k, v in idalabel.items()} # size of the architecture if model_name in ["dino_vits8", "dino_vits16"]: lowerCAmelCase__ = 384 lowerCAmelCase__ = 1536 lowerCAmelCase__ = 12 lowerCAmelCase__ = 6 # load original model from torch hub lowerCAmelCase__ = torch.hub.load("facebookresearch/dino:main" , lowerCAmelCase_ ) original_model.eval() # load state_dict of original model, remove and rename some keys lowerCAmelCase__ = original_model.state_dict() if base_model: remove_classification_head_(lowerCAmelCase_ ) lowerCAmelCase__ = create_rename_keys(lowerCAmelCase_ , base_model=lowerCAmelCase_ ) for src, dest in rename_keys: rename_key(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) read_in_q_k_v(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # load HuggingFace model if base_model: lowerCAmelCase__ = ViTModel(lowerCAmelCase_ , add_pooling_layer=lowerCAmelCase_ ).eval() else: lowerCAmelCase__ = ViTForImageClassification(lowerCAmelCase_ ).eval() model.load_state_dict(lowerCAmelCase_ ) # Check outputs on an image, prepared by ViTImageProcessor lowerCAmelCase__ = ViTImageProcessor() lowerCAmelCase__ = image_processor(images=prepare_img() , return_tensors="pt" ) lowerCAmelCase__ = encoding["pixel_values"] lowerCAmelCase__ = model(lowerCAmelCase_ ) if base_model: lowerCAmelCase__ = original_model(lowerCAmelCase_ ) assert torch.allclose(lowerCAmelCase_ , outputs.last_hidden_state[:, 0, :] , atol=1E-1 ) else: lowerCAmelCase__ = original_model(lowerCAmelCase_ ) assert logits.shape == outputs.logits.shape assert torch.allclose(lowerCAmelCase_ , outputs.logits , atol=1E-3 ) Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) print(F'Saving model {model_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(lowerCAmelCase_ ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='dino_vitb16', type=str, help='Name of the model trained with DINO you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--base_model', action='store_true', help='Whether to only convert the base model (no projection head weights).', ) parser.set_defaults(base_model=True) UpperCamelCase = parser.parse_args() convert_vit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.base_model)
61
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool UpperCamelCase = { 'Acehnese Arabic': 'ace_Arab', 'Acehnese Latin': 'ace_Latn', 'Mesopotamian Arabic': 'acm_Arab', 'Ta\'izzi-Adeni Arabic': 'acq_Arab', 'Tunisian Arabic': 'aeb_Arab', 'Afrikaans': 'afr_Latn', 'South Levantine Arabic': 'ajp_Arab', 'Akan': 'aka_Latn', 'Amharic': 'amh_Ethi', 'North Levantine Arabic': 'apc_Arab', 'Modern Standard Arabic': 'arb_Arab', 'Modern Standard Arabic Romanized': 'arb_Latn', 'Najdi Arabic': 'ars_Arab', 'Moroccan Arabic': 'ary_Arab', 'Egyptian Arabic': 'arz_Arab', 'Assamese': 'asm_Beng', 'Asturian': 'ast_Latn', 'Awadhi': 'awa_Deva', 'Central Aymara': 'ayr_Latn', 'South Azerbaijani': 'azb_Arab', 'North Azerbaijani': 'azj_Latn', 'Bashkir': 'bak_Cyrl', 'Bambara': 'bam_Latn', 'Balinese': 'ban_Latn', 'Belarusian': 'bel_Cyrl', 'Bemba': 'bem_Latn', 'Bengali': 'ben_Beng', 'Bhojpuri': 'bho_Deva', 'Banjar Arabic': 'bjn_Arab', 'Banjar Latin': 'bjn_Latn', 'Standard Tibetan': 'bod_Tibt', 'Bosnian': 'bos_Latn', 'Buginese': 'bug_Latn', 'Bulgarian': 'bul_Cyrl', 'Catalan': 'cat_Latn', 'Cebuano': 'ceb_Latn', 'Czech': 'ces_Latn', 'Chokwe': 'cjk_Latn', 'Central Kurdish': 'ckb_Arab', 'Crimean Tatar': 'crh_Latn', 'Welsh': 'cym_Latn', 'Danish': 'dan_Latn', 'German': 'deu_Latn', 'Southwestern Dinka': 'dik_Latn', 'Dyula': 'dyu_Latn', 'Dzongkha': 'dzo_Tibt', 'Greek': 'ell_Grek', 'English': 'eng_Latn', 'Esperanto': 'epo_Latn', 'Estonian': 'est_Latn', 'Basque': 'eus_Latn', 'Ewe': 'ewe_Latn', 'Faroese': 'fao_Latn', 'Fijian': 'fij_Latn', 'Finnish': 'fin_Latn', 'Fon': 'fon_Latn', 'French': 'fra_Latn', 'Friulian': 'fur_Latn', 'Nigerian Fulfulde': 'fuv_Latn', 'Scottish Gaelic': 'gla_Latn', 'Irish': 'gle_Latn', 'Galician': 'glg_Latn', 'Guarani': 'grn_Latn', 'Gujarati': 'guj_Gujr', 'Haitian Creole': 'hat_Latn', 'Hausa': 'hau_Latn', 'Hebrew': 'heb_Hebr', 'Hindi': 'hin_Deva', 'Chhattisgarhi': 'hne_Deva', 'Croatian': 'hrv_Latn', 'Hungarian': 'hun_Latn', 'Armenian': 'hye_Armn', 'Igbo': 'ibo_Latn', 'Ilocano': 'ilo_Latn', 'Indonesian': 'ind_Latn', 'Icelandic': 'isl_Latn', 'Italian': 'ita_Latn', 'Javanese': 'jav_Latn', 'Japanese': 'jpn_Jpan', 'Kabyle': 'kab_Latn', 'Jingpho': 'kac_Latn', 'Kamba': 'kam_Latn', 'Kannada': 'kan_Knda', 'Kashmiri Arabic': 'kas_Arab', 'Kashmiri Devanagari': 'kas_Deva', 'Georgian': 'kat_Geor', 'Central Kanuri Arabic': 'knc_Arab', 'Central Kanuri Latin': 'knc_Latn', 'Kazakh': 'kaz_Cyrl', 'Kabiyè': 'kbp_Latn', 'Kabuverdianu': 'kea_Latn', 'Khmer': 'khm_Khmr', 'Kikuyu': 'kik_Latn', 'Kinyarwanda': 'kin_Latn', 'Kyrgyz': 'kir_Cyrl', 'Kimbundu': 'kmb_Latn', 'Northern Kurdish': 'kmr_Latn', 'Kikongo': 'kon_Latn', 'Korean': 'kor_Hang', 'Lao': 'lao_Laoo', 'Ligurian': 'lij_Latn', 'Limburgish': 'lim_Latn', 'Lingala': 'lin_Latn', 'Lithuanian': 'lit_Latn', 'Lombard': 'lmo_Latn', 'Latgalian': 'ltg_Latn', 'Luxembourgish': 'ltz_Latn', 'Luba-Kasai': 'lua_Latn', 'Ganda': 'lug_Latn', 'Luo': 'luo_Latn', 'Mizo': 'lus_Latn', 'Standard Latvian': 'lvs_Latn', 'Magahi': 'mag_Deva', 'Maithili': 'mai_Deva', 'Malayalam': 'mal_Mlym', 'Marathi': 'mar_Deva', 'Minangkabau Arabic ': 'min_Arab', 'Minangkabau Latin': 'min_Latn', 'Macedonian': 'mkd_Cyrl', 'Plateau Malagasy': 'plt_Latn', 'Maltese': 'mlt_Latn', 'Meitei Bengali': 'mni_Beng', 'Halh Mongolian': 'khk_Cyrl', 'Mossi': 'mos_Latn', 'Maori': 'mri_Latn', 'Burmese': 'mya_Mymr', 'Dutch': 'nld_Latn', 'Norwegian Nynorsk': 'nno_Latn', 'Norwegian Bokmål': 'nob_Latn', 'Nepali': 'npi_Deva', 'Northern Sotho': 'nso_Latn', 'Nuer': 'nus_Latn', 'Nyanja': 'nya_Latn', 'Occitan': 'oci_Latn', 'West Central Oromo': 'gaz_Latn', 'Odia': 'ory_Orya', 'Pangasinan': 'pag_Latn', 'Eastern Panjabi': 'pan_Guru', 'Papiamento': 'pap_Latn', 'Western Persian': 'pes_Arab', 'Polish': 'pol_Latn', 'Portuguese': 'por_Latn', 'Dari': 'prs_Arab', 'Southern Pashto': 'pbt_Arab', 'Ayacucho Quechua': 'quy_Latn', 'Romanian': 'ron_Latn', 'Rundi': 'run_Latn', 'Russian': 'rus_Cyrl', 'Sango': 'sag_Latn', 'Sanskrit': 'san_Deva', 'Santali': 'sat_Olck', 'Sicilian': 'scn_Latn', 'Shan': 'shn_Mymr', 'Sinhala': 'sin_Sinh', 'Slovak': 'slk_Latn', 'Slovenian': 'slv_Latn', 'Samoan': 'smo_Latn', 'Shona': 'sna_Latn', 'Sindhi': 'snd_Arab', 'Somali': 'som_Latn', 'Southern Sotho': 'sot_Latn', 'Spanish': 'spa_Latn', 'Tosk Albanian': 'als_Latn', 'Sardinian': 'srd_Latn', 'Serbian': 'srp_Cyrl', 'Swati': 'ssw_Latn', 'Sundanese': 'sun_Latn', 'Swedish': 'swe_Latn', 'Swahili': 'swh_Latn', 'Silesian': 'szl_Latn', 'Tamil': 'tam_Taml', 'Tatar': 'tat_Cyrl', 'Telugu': 'tel_Telu', 'Tajik': 'tgk_Cyrl', 'Tagalog': 'tgl_Latn', 'Thai': 'tha_Thai', 'Tigrinya': 'tir_Ethi', 'Tamasheq Latin': 'taq_Latn', 'Tamasheq Tifinagh': 'taq_Tfng', 'Tok Pisin': 'tpi_Latn', 'Tswana': 'tsn_Latn', 'Tsonga': 'tso_Latn', 'Turkmen': 'tuk_Latn', 'Tumbuka': 'tum_Latn', 'Turkish': 'tur_Latn', 'Twi': 'twi_Latn', 'Central Atlas Tamazight': 'tzm_Tfng', 'Uyghur': 'uig_Arab', 'Ukrainian': 'ukr_Cyrl', 'Umbundu': 'umb_Latn', 'Urdu': 'urd_Arab', 'Northern Uzbek': 'uzn_Latn', 'Venetian': 'vec_Latn', 'Vietnamese': 'vie_Latn', 'Waray': 'war_Latn', 'Wolof': 'wol_Latn', 'Xhosa': 'xho_Latn', 'Eastern Yiddish': 'ydd_Hebr', 'Yoruba': 'yor_Latn', 'Yue Chinese': 'yue_Hant', 'Chinese Simplified': 'zho_Hans', 'Chinese Traditional': 'zho_Hant', 'Standard Malay': 'zsm_Latn', 'Zulu': 'zul_Latn', } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "facebook/nllb-200-distilled-600M" snake_case__ = ( "This is a tool that translates text from a language to another. It takes three inputs: `text`, which should " "be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, " "which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in " "plain English, such as 'Romanian', or 'Albanian'. It returns the text translated in `tgt_lang`." ) snake_case__ = "translator" snake_case__ = AutoTokenizer snake_case__ = AutoModelForSeqaSeqLM snake_case__ = LANGUAGE_CODES snake_case__ = ["text", "text", "text"] snake_case__ = ["text"] def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: if src_lang not in self.lang_to_code: raise ValueError(f'{src_lang} is not a supported language.' ) if tgt_lang not in self.lang_to_code: raise ValueError(f'{tgt_lang} is not a supported language.' ) lowerCAmelCase__ = self.lang_to_code[src_lang] lowerCAmelCase__ = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( SCREAMING_SNAKE_CASE__ , return_tensors="pt" , src_lang=SCREAMING_SNAKE_CASE__ , tgt_lang=SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: return self.model.generate(**SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[str]: return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=SCREAMING_SNAKE_CASE__ )
61
1
import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, ) class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=13 , SCREAMING_SNAKE_CASE__ : int=7 , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=99 , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : List[str]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : Optional[Any]=37 , SCREAMING_SNAKE_CASE__ : Optional[int]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE__ : Tuple=512 , SCREAMING_SNAKE_CASE__ : Tuple=16 , SCREAMING_SNAKE_CASE__ : Optional[Any]=2 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 , SCREAMING_SNAKE_CASE__ : Dict=4 , ) -> Optional[int]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = seq_length lowerCAmelCase__ = is_training lowerCAmelCase__ = use_attention_mask lowerCAmelCase__ = use_token_type_ids lowerCAmelCase__ = use_labels lowerCAmelCase__ = vocab_size lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = type_vocab_size lowerCAmelCase__ = type_sequence_label_size lowerCAmelCase__ = initializer_range lowerCAmelCase__ = num_choices def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase__ = None if self.use_attention_mask: lowerCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase__ = None if self.use_token_type_ids: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCAmelCase__ = RobertaPreLayerNormConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def a ( self : List[str] ) -> Union[str, Any]: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict def a ( self : Optional[Any] ) -> Dict: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = True lowerCAmelCase__ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax # Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40 class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = True snake_case__ = ( ( FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, ) if is_flax_available() else () ) def a ( self : int ) -> Dict: lowerCAmelCase__ = FlaxRobertaPreLayerNormModelTester(self ) @slow def a ( self : Tuple ) -> Union[str, Any]: for model_class_name in self.all_model_classes: lowerCAmelCase__ = model_class_name.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(np.ones((1, 1) ) ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_flax class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @slow def a ( self : int ) -> Dict: lowerCAmelCase__ = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ )[0] lowerCAmelCase__ = [1, 11, 50_265] self.assertEqual(list(output.shape ) , SCREAMING_SNAKE_CASE__ ) # compare the actual values for a slice. lowerCAmelCase__ = np.array( [[[40.4_880, 18.0_199, -5.2_367], [-1.8_877, -4.0_885, 10.7_085], [-2.2_613, -5.6_110, 7.2_665]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) @slow def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = FlaxRobertaPreLayerNormModel.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ )[0] # compare the actual values for a slice. lowerCAmelCase__ = np.array( [[[0.0_208, -0.0_356, 0.0_237], [-0.1_569, -0.0_411, -0.2_626], [0.1_879, 0.0_125, -0.0_089]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = VideoToVideoSDPipeline snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"video"} ) - {"image", "width", "height"} snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"video"} ) - {"image"} snake_case__ = PipelineTesterMixin.required_optional_params - {"latents"} snake_case__ = False # No `output_type`. snake_case__ = frozenset( [ "num_inference_steps", "generator", "latents", "return_dict", "callback", "callback_steps", ] ) def a ( self : int ) -> Optional[int]: torch.manual_seed(0 ) lowerCAmelCase__ = 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 , ) lowerCAmelCase__ = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=SCREAMING_SNAKE_CASE__ , set_alpha_to_one=SCREAMING_SNAKE_CASE__ , ) torch.manual_seed(0 ) lowerCAmelCase__ = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) lowerCAmelCase__ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="gelu" , projection_dim=512 , ) lowerCAmelCase__ = CLIPTextModel(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) lowerCAmelCase__ = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, } return components def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Dict=0 ) -> Tuple: # 3 frames lowerCAmelCase__ = floats_tensor((1, 3, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) if str(SCREAMING_SNAKE_CASE__ ).startswith("mps" ): lowerCAmelCase__ = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: lowerCAmelCase__ = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = { "prompt": "A painting of a squirrel eating a burger", "video": video, "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "pt", } return inputs def a ( self : Union[str, Any] ) -> str: lowerCAmelCase__ = "cpu" # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ = self.get_dummy_components() lowerCAmelCase__ = VideoToVideoSDPipeline(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = "np" lowerCAmelCase__ = sd_pipe(**SCREAMING_SNAKE_CASE__ ).frames lowerCAmelCase__ = frames[0][-3:, -3:, -1] assert frames[0].shape == (32, 32, 3) lowerCAmelCase__ = np.array([106, 117, 113, 174, 137, 112, 148, 151, 131] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def a ( self : List[Any] ) -> str: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE__ , expected_max_diff=5e-3 ) @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a ( self : List[Any] ) -> str: pass @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a ( self : int ) -> Optional[Any]: pass @unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline." ) def a ( self : List[str] ) -> Optional[int]: pass def a ( self : Optional[Any] ) -> Tuple: return super().test_progress_bar() @slow @skip_mps class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : str ) -> int: lowerCAmelCase__ = VideoToVideoSDPipeline.from_pretrained("cerspense/zeroscope_v2_XL" , torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames lowerCAmelCase__ = torch.Generator(device="cpu" ).manual_seed(0 ) lowerCAmelCase__ = torch.randn((1, 10, 3, 1_024, 576) , generator=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = video.to("cuda" ) lowerCAmelCase__ = "Spiderman is surfing" lowerCAmelCase__ = pipe(SCREAMING_SNAKE_CASE__ , video=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=3 , output_type="pt" ).frames lowerCAmelCase__ = np.array([-1.0_458_984, -1.1_279_297, -0.9_663_086, -0.91_503_906, -0.75_097_656] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1e-2
61
1
def _A ( lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : str , lowerCAmelCase_ : List[str] ): """simple docstring""" if index == r: for j in range(lowerCAmelCase_ ): print(data[j] , end=" " ) print(" " ) return # When no more elements are there to put in data[] if i >= n: return # current is included, put next at next location lowerCAmelCase__ = arr[i] combination_util(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , index + 1 , lowerCAmelCase_ , i + 1 ) # current is excluded, replace it with # next (Note that i+1 is passed, but # index is not changed) combination_util(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , i + 1 ) # The main function that prints all combinations # of size r in arr[] of size n. This function # mainly uses combinationUtil() def _A ( lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : int , lowerCAmelCase_ : Tuple ): """simple docstring""" lowerCAmelCase__ = [0] * r # Print all combination using temporary array 'data[]' combination_util(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , 0 , lowerCAmelCase_ , 0 ) if __name__ == "__main__": # Driver code to check the function above UpperCamelCase = [10, 20, 30, 40, 50] print_combination(arr, len(arr), 3) # This code is contributed by Ambuj sahu
61
from __future__ import annotations def _A ( lowerCAmelCase_ : list , lowerCAmelCase_ : int , lowerCAmelCase_ : int , lowerCAmelCase_ : int ): """simple docstring""" lowerCAmelCase__ = [] lowerCAmelCase__ , lowerCAmelCase__ = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0 ) ) lowerCAmelCase__ = result + left + right return input_list def _A ( lowerCAmelCase_ : list ): """simple docstring""" if len(lowerCAmelCase_ ) <= 1: return input_list lowerCAmelCase__ = list(lowerCAmelCase_ ) # iteration for two-way merging lowerCAmelCase__ = 2 while p <= len(lowerCAmelCase_ ): # getting low, high and middle value for merge-sort of single list for i in range(0 , len(lowerCAmelCase_ ) , lowerCAmelCase_ ): lowerCAmelCase__ = i lowerCAmelCase__ = i + p - 1 lowerCAmelCase__ = (low + high + 1) // 2 lowerCAmelCase__ = merge(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # final merge of last two parts if p * 2 >= len(lowerCAmelCase_ ): lowerCAmelCase__ = i lowerCAmelCase__ = merge(lowerCAmelCase_ , 0 , lowerCAmelCase_ , len(lowerCAmelCase_ ) - 1 ) break p *= 2 return input_list if __name__ == "__main__": UpperCamelCase = input('Enter numbers separated by a comma:\n').strip() if user_input == "": UpperCamelCase = [] else: UpperCamelCase = [int(item.strip()) for item in user_input.split(',')] print(iter_merge_sort(unsorted))
61
1
import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'vocab_file': 'sentencepiece.model'} UpperCamelCase = { 'vocab_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model', }, } UpperCamelCase = { 'google/rembert': 256, } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int]=False , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : Any="[CLS]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" , SCREAMING_SNAKE_CASE__ : Dict="[UNK]" , SCREAMING_SNAKE_CASE__ : Optional[Any]="[SEP]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[PAD]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[CLS]" , SCREAMING_SNAKE_CASE__ : List[Any]="[MASK]" , **SCREAMING_SNAKE_CASE__ : str , ) -> Dict: super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ , remove_space=SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = do_lower_case lowerCAmelCase__ = remove_space lowerCAmelCase__ = keep_accents lowerCAmelCase__ = vocab_file lowerCAmelCase__ = spm.SentencePieceProcessor() self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def a ( self : int ) -> Union[str, Any]: return len(self.sp_model ) def a ( self : Any ) -> str: lowerCAmelCase__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Union[str, Any] ) -> List[str]: lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = d lowerCAmelCase__ = spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int=False ) -> Optional[int]: lowerCAmelCase__ = self.sp_model.EncodeAsPieces(SCREAMING_SNAKE_CASE__ ) return pieces def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> List[Any]: return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Dict: return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : int ) -> int: lowerCAmelCase__ = self.sp_model.decode_pieces(SCREAMING_SNAKE_CASE__ ) return out_string def a ( self : int , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: 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 not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error("Vocabulary path ({}) should be a directory".format(SCREAMING_SNAKE_CASE__ ) ) return lowerCAmelCase__ = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
61
import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, ) class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=13 , SCREAMING_SNAKE_CASE__ : int=7 , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=99 , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : List[str]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : Optional[Any]=37 , SCREAMING_SNAKE_CASE__ : Optional[int]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE__ : Tuple=512 , SCREAMING_SNAKE_CASE__ : Tuple=16 , SCREAMING_SNAKE_CASE__ : Optional[Any]=2 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 , SCREAMING_SNAKE_CASE__ : Dict=4 , ) -> Optional[int]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = seq_length lowerCAmelCase__ = is_training lowerCAmelCase__ = use_attention_mask lowerCAmelCase__ = use_token_type_ids lowerCAmelCase__ = use_labels lowerCAmelCase__ = vocab_size lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = type_vocab_size lowerCAmelCase__ = type_sequence_label_size lowerCAmelCase__ = initializer_range lowerCAmelCase__ = num_choices def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase__ = None if self.use_attention_mask: lowerCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase__ = None if self.use_token_type_ids: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCAmelCase__ = RobertaPreLayerNormConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def a ( self : List[str] ) -> Union[str, Any]: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict def a ( self : Optional[Any] ) -> Dict: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = True lowerCAmelCase__ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax # Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40 class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = True snake_case__ = ( ( FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, ) if is_flax_available() else () ) def a ( self : int ) -> Dict: lowerCAmelCase__ = FlaxRobertaPreLayerNormModelTester(self ) @slow def a ( self : Tuple ) -> Union[str, Any]: for model_class_name in self.all_model_classes: lowerCAmelCase__ = model_class_name.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(np.ones((1, 1) ) ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_flax class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @slow def a ( self : int ) -> Dict: lowerCAmelCase__ = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ )[0] lowerCAmelCase__ = [1, 11, 50_265] self.assertEqual(list(output.shape ) , SCREAMING_SNAKE_CASE__ ) # compare the actual values for a slice. lowerCAmelCase__ = np.array( [[[40.4_880, 18.0_199, -5.2_367], [-1.8_877, -4.0_885, 10.7_085], [-2.2_613, -5.6_110, 7.2_665]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) @slow def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = FlaxRobertaPreLayerNormModel.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ )[0] # compare the actual values for a slice. lowerCAmelCase__ = np.array( [[[0.0_208, -0.0_356, 0.0_237], [-0.1_569, -0.0_411, -0.2_626], [0.1_879, 0.0_125, -0.0_089]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
1
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 _A ( lowerCAmelCase_ : Any ): """simple docstring""" lowerCAmelCase__ = VideoMAEConfig() set_architecture_configs(lowerCAmelCase_ , lowerCAmelCase_ ) if "finetuned" not in model_name: lowerCAmelCase__ = False if "finetuned" in model_name: lowerCAmelCase__ = "huggingface/label-files" if "kinetics" in model_name: lowerCAmelCase__ = 400 lowerCAmelCase__ = "kinetics400-id2label.json" elif "ssv2" in model_name: lowerCAmelCase__ = 174 lowerCAmelCase__ = "something-something-v2-id2label.json" else: raise ValueError("Model name should either contain 'kinetics' or 'ssv2' in case it's fine-tuned." ) lowerCAmelCase__ = json.load(open(hf_hub_download(lowerCAmelCase_ , lowerCAmelCase_ , repo_type="dataset" ) , "r" ) ) lowerCAmelCase__ = {int(lowerCAmelCase_ ): v for k, v in idalabel.items()} lowerCAmelCase__ = idalabel lowerCAmelCase__ = {v: k for k, v in idalabel.items()} return config def _A ( lowerCAmelCase_ : str , lowerCAmelCase_ : int ): """simple docstring""" if "small" in model_name: lowerCAmelCase__ = 384 lowerCAmelCase__ = 1536 lowerCAmelCase__ = 12 lowerCAmelCase__ = 16 lowerCAmelCase__ = 12 lowerCAmelCase__ = 3 lowerCAmelCase__ = 192 lowerCAmelCase__ = 768 elif "large" in model_name: lowerCAmelCase__ = 1024 lowerCAmelCase__ = 4096 lowerCAmelCase__ = 24 lowerCAmelCase__ = 16 lowerCAmelCase__ = 12 lowerCAmelCase__ = 8 lowerCAmelCase__ = 512 lowerCAmelCase__ = 2048 elif "huge" in model_name: lowerCAmelCase__ = 1280 lowerCAmelCase__ = 5120 lowerCAmelCase__ = 32 lowerCAmelCase__ = 16 lowerCAmelCase__ = 12 lowerCAmelCase__ = 8 lowerCAmelCase__ = 640 lowerCAmelCase__ = 2560 elif "base" not in model_name: raise ValueError("Model name should include either \"small\", \"base\", \"large\", or \"huge\"" ) def _A ( lowerCAmelCase_ : Union[str, Any] ): """simple docstring""" if "encoder." in name: lowerCAmelCase__ = name.replace("encoder." , "" ) if "cls_token" in name: lowerCAmelCase__ = name.replace("cls_token" , "videomae.embeddings.cls_token" ) if "decoder_pos_embed" in name: lowerCAmelCase__ = name.replace("decoder_pos_embed" , "decoder.decoder_pos_embed" ) if "pos_embed" in name and "decoder" not in name: lowerCAmelCase__ = name.replace("pos_embed" , "videomae.embeddings.position_embeddings" ) if "patch_embed.proj" in name: lowerCAmelCase__ = name.replace("patch_embed.proj" , "videomae.embeddings.patch_embeddings.projection" ) if "patch_embed.norm" in name: lowerCAmelCase__ = name.replace("patch_embed.norm" , "videomae.embeddings.norm" ) if "decoder.blocks" in name: lowerCAmelCase__ = name.replace("decoder.blocks" , "decoder.decoder_layers" ) if "blocks" in name: lowerCAmelCase__ = name.replace("blocks" , "videomae.encoder.layer" ) if "attn.proj" in name: lowerCAmelCase__ = name.replace("attn.proj" , "attention.output.dense" ) if "attn" in name and "bias" not in name: lowerCAmelCase__ = name.replace("attn" , "attention.self" ) if "attn" in name: lowerCAmelCase__ = name.replace("attn" , "attention.attention" ) if "norm1" in name: lowerCAmelCase__ = name.replace("norm1" , "layernorm_before" ) if "norm2" in name: lowerCAmelCase__ = name.replace("norm2" , "layernorm_after" ) if "mlp.fc1" in name: lowerCAmelCase__ = name.replace("mlp.fc1" , "intermediate.dense" ) if "mlp.fc2" in name: lowerCAmelCase__ = name.replace("mlp.fc2" , "output.dense" ) if "decoder_embed" in name: lowerCAmelCase__ = name.replace("decoder_embed" , "decoder.decoder_embed" ) if "decoder_norm" in name: lowerCAmelCase__ = name.replace("decoder_norm" , "decoder.decoder_norm" ) if "decoder_pred" in name: lowerCAmelCase__ = name.replace("decoder_pred" , "decoder.decoder_pred" ) if "norm.weight" in name and "decoder" not in name and "fc" not in name: lowerCAmelCase__ = name.replace("norm.weight" , "videomae.layernorm.weight" ) if "norm.bias" in name and "decoder" not in name and "fc" not in name: lowerCAmelCase__ = name.replace("norm.bias" , "videomae.layernorm.bias" ) if "head" in name and "decoder" not in name: lowerCAmelCase__ = name.replace("head" , "classifier" ) return name def _A ( lowerCAmelCase_ : Dict , lowerCAmelCase_ : Dict ): """simple docstring""" for key in orig_state_dict.copy().keys(): lowerCAmelCase__ = orig_state_dict.pop(lowerCAmelCase_ ) if key.startswith("encoder." ): lowerCAmelCase__ = key.replace("encoder." , "" ) if "qkv" in key: lowerCAmelCase__ = key.split("." ) if key.startswith("decoder.blocks" ): lowerCAmelCase__ = config.decoder_hidden_size lowerCAmelCase__ = int(key_split[2] ) lowerCAmelCase__ = "decoder.decoder_layers." if "weight" in key: lowerCAmelCase__ = val[:dim, :] lowerCAmelCase__ = val[dim : dim * 2, :] lowerCAmelCase__ = val[-dim:, :] else: lowerCAmelCase__ = config.hidden_size lowerCAmelCase__ = int(key_split[1] ) lowerCAmelCase__ = "videomae.encoder.layer." if "weight" in key: lowerCAmelCase__ = val[:dim, :] lowerCAmelCase__ = val[dim : dim * 2, :] lowerCAmelCase__ = val[-dim:, :] else: lowerCAmelCase__ = val return orig_state_dict def _A ( ): """simple docstring""" lowerCAmelCase__ = hf_hub_download( repo_id="hf-internal-testing/spaghetti-video" , filename="eating_spaghetti.npy" , repo_type="dataset" ) lowerCAmelCase__ = np.load(lowerCAmelCase_ ) return list(lowerCAmelCase_ ) def _A ( lowerCAmelCase_ : List[str] , lowerCAmelCase_ : str , lowerCAmelCase_ : Dict , lowerCAmelCase_ : str ): """simple docstring""" lowerCAmelCase__ = get_videomae_config(lowerCAmelCase_ ) if "finetuned" in model_name: lowerCAmelCase__ = VideoMAEForVideoClassification(lowerCAmelCase_ ) else: lowerCAmelCase__ = VideoMAEForPreTraining(lowerCAmelCase_ ) # download original checkpoint, hosted on Google Drive lowerCAmelCase__ = "pytorch_model.bin" gdown.cached_download(lowerCAmelCase_ , lowerCAmelCase_ , quiet=lowerCAmelCase_ ) lowerCAmelCase__ = torch.load(lowerCAmelCase_ , map_location="cpu" ) if "model" in files: lowerCAmelCase__ = files["model"] else: lowerCAmelCase__ = files["module"] lowerCAmelCase__ = convert_state_dict(lowerCAmelCase_ , lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) model.eval() # verify model on basic input lowerCAmelCase__ = VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) lowerCAmelCase__ = prepare_video() lowerCAmelCase__ = image_processor(lowerCAmelCase_ , return_tensors="pt" ) if "finetuned" not in model_name: lowerCAmelCase__ = hf_hub_download(repo_id="hf-internal-testing/bool-masked-pos" , filename="bool_masked_pos.pt" ) lowerCAmelCase__ = torch.load(lowerCAmelCase_ ) lowerCAmelCase__ = model(**lowerCAmelCase_ ) lowerCAmelCase__ = outputs.logits lowerCAmelCase__ = [ "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": lowerCAmelCase__ = torch.Size([1, 400] ) lowerCAmelCase__ = torch.tensor([-0.9291, -0.4061, -0.9307] ) elif model_name == "videomae-small-finetuned-ssv2": lowerCAmelCase__ = torch.Size([1, 174] ) lowerCAmelCase__ = torch.tensor([0.2671, -0.4689, -0.8235] ) elif model_name == "videomae-base": lowerCAmelCase__ = torch.Size([1, 1408, 1536] ) lowerCAmelCase__ = 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": lowerCAmelCase__ = torch.Size([1, 1408, 1536] ) lowerCAmelCase__ = 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 lowerCAmelCase__ = torch.tensor([0.5142] ) if config.norm_pix_loss else torch.tensor([0.6469] ) elif model_name == "videomae-large": lowerCAmelCase__ = torch.Size([1, 1408, 1536] ) lowerCAmelCase__ = 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": lowerCAmelCase__ = torch.Size([1, 400] ) lowerCAmelCase__ = torch.tensor([0.0771, 0.0011, -0.3625] ) elif model_name == "videomae-huge-finetuned-kinetics": lowerCAmelCase__ = torch.Size([1, 400] ) lowerCAmelCase__ = torch.tensor([0.2433, 0.1632, -0.4894] ) elif model_name == "videomae-base-short-finetuned-kinetics": lowerCAmelCase__ = torch.Size([1, 400] ) lowerCAmelCase__ = torch.tensor([0.6588, 0.0990, -0.2493] ) elif model_name == "videomae-base-finetuned-kinetics": lowerCAmelCase__ = torch.Size([1, 400] ) lowerCAmelCase__ = torch.tensor([0.3669, -0.0688, -0.2421] ) elif model_name == "videomae-base-short-ssv2": lowerCAmelCase__ = torch.Size([1, 1408, 1536] ) lowerCAmelCase__ = 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": lowerCAmelCase__ = torch.Size([1, 174] ) lowerCAmelCase__ = torch.tensor([-0.0537, -0.1539, -0.3266] ) elif model_name == "videomae-base-ssv2": lowerCAmelCase__ = torch.Size([1, 1408, 1536] ) lowerCAmelCase__ = 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": lowerCAmelCase__ = torch.Size([1, 174] ) lowerCAmelCase__ = 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": lowerCAmelCase__ = 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__": UpperCamelCase = 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.' ) UpperCamelCase = parser.parse_args() convert_videomae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)
61
class __lowerCamelCase : """simple docstring""" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = size lowerCAmelCase__ = [0] * size lowerCAmelCase__ = [0] * size @staticmethod def a ( SCREAMING_SNAKE_CASE__ : int ) -> int: return index | (index + 1) @staticmethod def a ( SCREAMING_SNAKE_CASE__ : int ) -> int: return (index & (index + 1)) - 1 def a ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = value while index < self.size: lowerCAmelCase__ = self.get_prev(SCREAMING_SNAKE_CASE__ ) + 1 if current_left_border == index: lowerCAmelCase__ = value else: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_next(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> int: right -= 1 # Because of right is exclusive lowerCAmelCase__ = 0 while left <= right: lowerCAmelCase__ = self.get_prev(SCREAMING_SNAKE_CASE__ ) if left <= current_left: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , self.tree[right] ) lowerCAmelCase__ = current_left else: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
61
1
from ....configuration_utils import PretrainedConfig from ....utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { 'speechbrain/m-ctc-t-large': 'https://huggingface.co/speechbrain/m-ctc-t-large/resolve/main/config.json', # See all M-CTC-T models at https://huggingface.co/models?filter=mctct } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "mctct" def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[int]=8_065 , SCREAMING_SNAKE_CASE__ : Tuple=1_536 , SCREAMING_SNAKE_CASE__ : int=36 , SCREAMING_SNAKE_CASE__ : List[Any]=6_144 , SCREAMING_SNAKE_CASE__ : Any=4 , SCREAMING_SNAKE_CASE__ : Optional[int]=384 , SCREAMING_SNAKE_CASE__ : Optional[Any]=920 , SCREAMING_SNAKE_CASE__ : Optional[int]=1e-5 , SCREAMING_SNAKE_CASE__ : str=0.3 , SCREAMING_SNAKE_CASE__ : Optional[Any]="relu" , SCREAMING_SNAKE_CASE__ : Dict=0.02 , SCREAMING_SNAKE_CASE__ : str=0.3 , SCREAMING_SNAKE_CASE__ : List[Any]=0.3 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0 , SCREAMING_SNAKE_CASE__ : str=2 , SCREAMING_SNAKE_CASE__ : Dict=1 , SCREAMING_SNAKE_CASE__ : Any=0.3 , SCREAMING_SNAKE_CASE__ : int=1 , SCREAMING_SNAKE_CASE__ : Tuple=(7,) , SCREAMING_SNAKE_CASE__ : List[str]=(3,) , SCREAMING_SNAKE_CASE__ : Union[str, Any]=80 , SCREAMING_SNAKE_CASE__ : Optional[Any]=1 , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : str="sum" , SCREAMING_SNAKE_CASE__ : Dict=False , **SCREAMING_SNAKE_CASE__ : str , ) -> int: super().__init__(**SCREAMING_SNAKE_CASE__ , pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = vocab_size lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = attention_head_dim lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = layer_norm_eps lowerCAmelCase__ = layerdrop lowerCAmelCase__ = hidden_act lowerCAmelCase__ = initializer_range lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = pad_token_id lowerCAmelCase__ = bos_token_id lowerCAmelCase__ = eos_token_id lowerCAmelCase__ = conv_glu_dim lowerCAmelCase__ = conv_dropout lowerCAmelCase__ = num_conv_layers lowerCAmelCase__ = input_feat_per_channel lowerCAmelCase__ = input_channels lowerCAmelCase__ = conv_channels lowerCAmelCase__ = ctc_loss_reduction lowerCAmelCase__ = ctc_zero_infinity # prevents config testing fail with exporting to json lowerCAmelCase__ = list(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = list(SCREAMING_SNAKE_CASE__ ) if len(self.conv_kernel ) != self.num_conv_layers: raise ValueError( "Configuration for convolutional module is incorrect. " "It is required that `len(config.conv_kernel)` == `config.num_conv_layers` " f'but is `len(config.conv_kernel) = {len(self.conv_kernel )}`, ' f'`config.num_conv_layers = {self.num_conv_layers}`.' )
61
import unittest from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin UpperCamelCase = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = XLNetTokenizer snake_case__ = XLNetTokenizerFast snake_case__ = True snake_case__ = True def a ( self : str ) -> str: super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) tokenizer.sanitize_special_tokens() tokenizer.save_pretrained(self.tmpdirname ) def a ( self : List[str] ) -> List[Any]: lowerCAmelCase__ = "<s>" lowerCAmelCase__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def a ( self : Union[str, Any] ) -> str: lowerCAmelCase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "<eod>" ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 1_006 ) def a ( self : int ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 1_000 ) def a ( self : List[str] ) -> Any: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("This is a test" ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [285, 46, 10, 170, 382] ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) lowerCAmelCase__ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] ) lowerCAmelCase__ = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) def a ( self : Optional[int] ) -> Optional[Any]: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "", "i", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "se", ".", ] , ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["▁he", "ll", "o"] ) def a ( self : List[Any] ) -> Optional[int]: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "se", ".", ] , ) @slow def a ( self : Any ) -> Any: lowerCAmelCase__ = XLNetTokenizer.from_pretrained("xlnet-base-cased" ) lowerCAmelCase__ = tokenizer.encode("sequence builders" , add_special_tokens=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.encode("multi-sequence build" , add_special_tokens=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert encoded_sentence == text + [4, 3] assert encoded_pair == text + [4] + text_a + [4, 3] @slow def a ( self : Union[str, Any] ) -> Any: # fmt: off lowerCAmelCase__ = {"input_ids": [[17, 21_442, 270, 17, 10, 14_645, 318, 34, 17, 4_546, 3_145, 787, 13, 7_752, 22_018, 23, 21, 17, 4_546, 3_145, 787, 13, 3_352, 14_431, 13, 5_500, 11, 1_176, 580, 13, 16_819, 4_797, 23, 17, 10, 17_135, 658, 19, 457, 7_932, 13, 184, 19, 3_154, 17_135, 6_468, 19, 1_404, 12_269, 19, 4_229, 5_356, 16_264, 46, 19, 17, 20_545, 10_395, 9, 9, 9, 11, 28, 6_421, 9_531, 20_729, 17, 10, 353, 17_022, 11, 21, 6_421, 9_531, 16_949, 17, 10, 11_509, 753, 11, 33, 95, 2_421, 7_385, 956, 14_431, 2_626, 25, 842, 7_385, 4_836, 21, 1_429, 2_272, 9_855, 3_120, 161, 24_738, 19, 13_203, 658, 218, 787, 21, 430, 18_482, 847, 2_637, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 322, 22_178, 27, 1_064, 22, 956, 13, 11_101, 1_429, 5_854, 24_313, 18_953, 40, 422, 24_366, 68, 1_758, 37, 10_483, 14_257, 31, 207, 263, 21, 203, 3_773, 25, 71, 9_735, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 32, 2_049, 3_442, 17, 13_894, 3_380, 23, 95, 18, 17_634, 2_288, 9, 4, 3]], "token_type_ids": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=SCREAMING_SNAKE_CASE__ , model_name="xlnet-base-cased" , revision="c841166438c31ec7ca9a106dee7bb312b73ae511" , )
61
1
import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = VideoToVideoSDPipeline snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"video"} ) - {"image", "width", "height"} snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"video"} ) - {"image"} snake_case__ = PipelineTesterMixin.required_optional_params - {"latents"} snake_case__ = False # No `output_type`. snake_case__ = frozenset( [ "num_inference_steps", "generator", "latents", "return_dict", "callback", "callback_steps", ] ) def a ( self : int ) -> Optional[int]: torch.manual_seed(0 ) lowerCAmelCase__ = 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 , ) lowerCAmelCase__ = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=SCREAMING_SNAKE_CASE__ , set_alpha_to_one=SCREAMING_SNAKE_CASE__ , ) torch.manual_seed(0 ) lowerCAmelCase__ = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) lowerCAmelCase__ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="gelu" , projection_dim=512 , ) lowerCAmelCase__ = CLIPTextModel(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) lowerCAmelCase__ = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, } return components def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Dict=0 ) -> Tuple: # 3 frames lowerCAmelCase__ = floats_tensor((1, 3, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) if str(SCREAMING_SNAKE_CASE__ ).startswith("mps" ): lowerCAmelCase__ = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: lowerCAmelCase__ = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = { "prompt": "A painting of a squirrel eating a burger", "video": video, "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "pt", } return inputs def a ( self : Union[str, Any] ) -> str: lowerCAmelCase__ = "cpu" # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ = self.get_dummy_components() lowerCAmelCase__ = VideoToVideoSDPipeline(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = "np" lowerCAmelCase__ = sd_pipe(**SCREAMING_SNAKE_CASE__ ).frames lowerCAmelCase__ = frames[0][-3:, -3:, -1] assert frames[0].shape == (32, 32, 3) lowerCAmelCase__ = np.array([106, 117, 113, 174, 137, 112, 148, 151, 131] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def a ( self : List[Any] ) -> str: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE__ , expected_max_diff=5e-3 ) @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a ( self : List[Any] ) -> str: pass @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a ( self : int ) -> Optional[Any]: pass @unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline." ) def a ( self : List[str] ) -> Optional[int]: pass def a ( self : Optional[Any] ) -> Tuple: return super().test_progress_bar() @slow @skip_mps class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : str ) -> int: lowerCAmelCase__ = VideoToVideoSDPipeline.from_pretrained("cerspense/zeroscope_v2_XL" , torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames lowerCAmelCase__ = torch.Generator(device="cpu" ).manual_seed(0 ) lowerCAmelCase__ = torch.randn((1, 10, 3, 1_024, 576) , generator=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = video.to("cuda" ) lowerCAmelCase__ = "Spiderman is surfing" lowerCAmelCase__ = pipe(SCREAMING_SNAKE_CASE__ , video=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=3 , output_type="pt" ).frames lowerCAmelCase__ = np.array([-1.0_458_984, -1.1_279_297, -0.9_663_086, -0.91_503_906, -0.75_097_656] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1e-2
61
import operator as op UpperCamelCase = 'scaler.pt' UpperCamelCase = 'pytorch_model' UpperCamelCase = 'random_states' UpperCamelCase = 'optimizer' UpperCamelCase = 'scheduler' UpperCamelCase = 'pytorch_model.bin' UpperCamelCase = 'pytorch_model.bin.index.json' UpperCamelCase = 'model.safetensors' UpperCamelCase = 'model.safetensors.index.json' UpperCamelCase = '1.10.2' UpperCamelCase = 'py38' UpperCamelCase = '4.17.0' UpperCamelCase = ['ml.p3.16xlarge', 'ml.p3dn.24xlarge', 'ml.p4dn.24xlarge'] UpperCamelCase = ['FULL_SHARD', 'SHARD_GRAD_OP', 'NO_SHARD', 'HYBRID_SHARD', 'HYBRID_SHARD_ZERO2'] UpperCamelCase = ['TRANSFORMER_BASED_WRAP', 'SIZE_BASED_WRAP', 'NO_WRAP'] UpperCamelCase = ['BACKWARD_PRE', 'BACKWARD_POST', 'NO_PREFETCH'] UpperCamelCase = ['FULL_STATE_DICT', 'LOCAL_STATE_DICT', 'SHARDED_STATE_DICT'] UpperCamelCase = '2.0.1' UpperCamelCase = ['pdsh', 'standard', 'openmpi', 'mvapich'] UpperCamelCase = ['default', 'reduce-overhead', 'max-autotune'] UpperCamelCase = {'>': op.gt, '>=': op.ge, '==': op.eq, '!=': op.ne, '<=': op.le, '<': op.lt} # These are the args for `torch.distributed.launch` for pytorch < 1.9 UpperCamelCase = [ 'nnodes', 'nproc_per_node', 'rdzv_backend', 'rdzv_endpoint', 'rdzv_id', 'rdzv_conf', 'standalone', 'max_restarts', 'monitor_interval', 'start_method', 'role', 'module', 'm', 'no_python', 'run_path', 'log_dir', 'r', 'redirects', 't', 'tee', 'node_rank', 'master_addr', 'master_port', ] UpperCamelCase = ['DEEPSPEED', 'MULTI_GPU', 'FSDP', 'MEGATRON_LM'] UpperCamelCase = ['DEEPSPEED', 'MULTI_XPU', 'FSDP']
61
1
def _A ( lowerCAmelCase_ : list[int] , lowerCAmelCase_ : list[int] , lowerCAmelCase_ : int ): """simple docstring""" return not any( neighbour == 1 and colored_vertices[i] == color for i, neighbour in enumerate(lowerCAmelCase_ ) ) def _A ( lowerCAmelCase_ : list[list[int]] , lowerCAmelCase_ : int , lowerCAmelCase_ : list[int] , lowerCAmelCase_ : int ): """simple docstring""" if index == len(lowerCAmelCase_ ): return True # Recursive Step for i in range(lowerCAmelCase_ ): if valid_coloring(graph[index] , lowerCAmelCase_ , lowerCAmelCase_ ): # Color current vertex lowerCAmelCase__ = i # Validate coloring if util_color(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , index + 1 ): return True # Backtrack lowerCAmelCase__ = -1 return False def _A ( lowerCAmelCase_ : list[list[int]] , lowerCAmelCase_ : int ): """simple docstring""" lowerCAmelCase__ = [-1] * len(lowerCAmelCase_ ) if util_color(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , 0 ): return colored_vertices return []
61
import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'vocab_file': 'sentencepiece.model'} UpperCamelCase = { 'vocab_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model', }, } UpperCamelCase = { 'google/rembert': 256, } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int]=False , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : Any="[CLS]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" , SCREAMING_SNAKE_CASE__ : Dict="[UNK]" , SCREAMING_SNAKE_CASE__ : Optional[Any]="[SEP]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[PAD]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[CLS]" , SCREAMING_SNAKE_CASE__ : List[Any]="[MASK]" , **SCREAMING_SNAKE_CASE__ : str , ) -> Dict: super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ , remove_space=SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = do_lower_case lowerCAmelCase__ = remove_space lowerCAmelCase__ = keep_accents lowerCAmelCase__ = vocab_file lowerCAmelCase__ = spm.SentencePieceProcessor() self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def a ( self : int ) -> Union[str, Any]: return len(self.sp_model ) def a ( self : Any ) -> str: lowerCAmelCase__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Union[str, Any] ) -> List[str]: lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = d lowerCAmelCase__ = spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int=False ) -> Optional[int]: lowerCAmelCase__ = self.sp_model.EncodeAsPieces(SCREAMING_SNAKE_CASE__ ) return pieces def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> List[Any]: return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Dict: return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : int ) -> int: lowerCAmelCase__ = self.sp_model.decode_pieces(SCREAMING_SNAKE_CASE__ ) return out_string def a ( self : int , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: 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 not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error("Vocabulary path ({}) should be a directory".format(SCREAMING_SNAKE_CASE__ ) ) return lowerCAmelCase__ = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
61
1
import argparse import json import os from pathlib import Path import requests import torch from transformers import JukeboxConfig, JukeboxModel from transformers.utils import logging logging.set_verbosity_info() UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = 'https://openaipublic.azureedge.net/jukebox/models/' UpperCamelCase = { 'jukebox-1b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '1b_lyrics/prior_level_2.pth.tar', ], 'jukebox-5b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '5b_lyrics/prior_level_2.pth.tar', ], } def _A ( lowerCAmelCase_ : Any ): """simple docstring""" if key.endswith(".model.1.bias" ) and len(key.split("." ) ) > 10: lowerCAmelCase__ = key.replace(".model.1.bias" , ".conv1d_1.bias" ) elif key.endswith(".model.1.weight" ) and len(key.split("." ) ) > 10: lowerCAmelCase__ = key.replace(".model.1.weight" , ".conv1d_1.weight" ) elif key.endswith(".model.3.bias" ) and len(key.split("." ) ) > 10: lowerCAmelCase__ = key.replace(".model.3.bias" , ".conv1d_2.bias" ) elif key.endswith(".model.3.weight" ) and len(key.split("." ) ) > 10: lowerCAmelCase__ = key.replace(".model.3.weight" , ".conv1d_2.weight" ) if "conditioner_blocks.0." in key: lowerCAmelCase__ = key.replace("conditioner_blocks.0" , "conditioner_blocks" ) if "prime_prior" in key: lowerCAmelCase__ = key.replace("prime_prior" , "encoder" ) if ".emb." in key and "total" not in key and "absolute" not in key and "relative" not in key: lowerCAmelCase__ = key.replace(".emb." , "." ) if key.endswith("k" ): # replace vqvae.X.k with vqvae.X.codebook return key.replace(".k" , ".codebook" ) if "y_emb." in key: return key.replace("y_emb." , "metadata_embedding." ) if "x_emb.emb." in key: lowerCAmelCase__ = key.replace("0.x_emb.emb" , "embed_tokens" ) if "prime_state_ln" in key: return key.replace("prime_state_ln" , "encoder.final_layer_norm" ) if ".ln" in key: return key.replace(".ln" , ".layer_norm" ) if "_ln" in key: return key.replace("_ln" , "_layer_norm" ) if "prime_state_proj" in key: return key.replace("prime_state_proj" , "encoder.proj_in" ) if "prime_x_out" in key: return key.replace("prime_x_out" , "encoder.lm_head" ) if "prior.x_out" in key: return key.replace("x_out" , "fc_proj_out" ) if "x_emb" in key: return key.replace("x_emb" , "embed_tokens" ) return key def _A ( lowerCAmelCase_ : Tuple , lowerCAmelCase_ : int , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Dict ): """simple docstring""" lowerCAmelCase__ = {} import re lowerCAmelCase__ = re.compile(r"encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)" ) lowerCAmelCase__ = re.compile( r"encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)" ) lowerCAmelCase__ = re.compile(r"encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)" ) lowerCAmelCase__ = re.compile(r"decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)" ) lowerCAmelCase__ = re.compile( r"decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)" ) lowerCAmelCase__ = re.compile(r"decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)" ) lowerCAmelCase__ = re.compile(r"conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)" ) lowerCAmelCase__ = re.compile( r"conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)" ) lowerCAmelCase__ = re.compile(r"conditioner_blocks.(\d*).cond.model.(\d*).(bias|weight)" ) for original_key, value in state_dict.items(): # rename vqvae.encoder keys if re_encoder_block_conv_in.fullmatch(lowerCAmelCase_ ): lowerCAmelCase__ = re_encoder_block_conv_in.match(lowerCAmelCase_ ) lowerCAmelCase__ = regex_match.groups() lowerCAmelCase__ = int(groups[2] ) * 2 + int(groups[3] ) lowerCAmelCase__ = F'encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}' lowerCAmelCase__ = re_encoder_block_conv_in.sub(lowerCAmelCase_ , lowerCAmelCase_ ) elif re_encoder_block_resnet.fullmatch(lowerCAmelCase_ ): lowerCAmelCase__ = re_encoder_block_resnet.match(lowerCAmelCase_ ) lowerCAmelCase__ = regex_match.groups() lowerCAmelCase__ = int(groups[2] ) * 2 + int(groups[3] ) lowerCAmelCase__ = {"1": 1, "3": 2}[groups[-2]] lowerCAmelCase__ = F'encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.' lowerCAmelCase__ = F'resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}' lowerCAmelCase__ = prefix + resnet_block lowerCAmelCase__ = re_encoder_block_resnet.sub(lowerCAmelCase_ , lowerCAmelCase_ ) elif re_encoder_block_proj_out.fullmatch(lowerCAmelCase_ ): lowerCAmelCase__ = re_encoder_block_proj_out.match(lowerCAmelCase_ ) lowerCAmelCase__ = regex_match.groups() lowerCAmelCase__ = F'encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}' lowerCAmelCase__ = re_encoder_block_proj_out.sub(lowerCAmelCase_ , lowerCAmelCase_ ) # rename vqvae.decoder keys elif re_decoder_block_conv_out.fullmatch(lowerCAmelCase_ ): lowerCAmelCase__ = re_decoder_block_conv_out.match(lowerCAmelCase_ ) lowerCAmelCase__ = regex_match.groups() lowerCAmelCase__ = int(groups[2] ) * 2 + int(groups[3] ) - 2 lowerCAmelCase__ = F'decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}' lowerCAmelCase__ = re_decoder_block_conv_out.sub(lowerCAmelCase_ , lowerCAmelCase_ ) elif re_decoder_block_resnet.fullmatch(lowerCAmelCase_ ): lowerCAmelCase__ = re_decoder_block_resnet.match(lowerCAmelCase_ ) lowerCAmelCase__ = regex_match.groups() lowerCAmelCase__ = int(groups[2] ) * 2 + int(groups[3] ) - 2 lowerCAmelCase__ = {"1": 1, "3": 2}[groups[-2]] lowerCAmelCase__ = F'decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.' lowerCAmelCase__ = F'resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}' lowerCAmelCase__ = prefix + resnet_block lowerCAmelCase__ = re_decoder_block_resnet.sub(lowerCAmelCase_ , lowerCAmelCase_ ) elif re_decoder_block_proj_in.fullmatch(lowerCAmelCase_ ): lowerCAmelCase__ = re_decoder_block_proj_in.match(lowerCAmelCase_ ) lowerCAmelCase__ = regex_match.groups() lowerCAmelCase__ = F'decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}' lowerCAmelCase__ = re_decoder_block_proj_in.sub(lowerCAmelCase_ , lowerCAmelCase_ ) # rename prior cond.model to upsampler.upsample_block and resnet elif re_prior_cond_conv_out.fullmatch(lowerCAmelCase_ ): lowerCAmelCase__ = re_prior_cond_conv_out.match(lowerCAmelCase_ ) lowerCAmelCase__ = regex_match.groups() lowerCAmelCase__ = int(groups[1] ) * 2 + int(groups[2] ) - 2 lowerCAmelCase__ = F'conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}' lowerCAmelCase__ = re_prior_cond_conv_out.sub(lowerCAmelCase_ , lowerCAmelCase_ ) elif re_prior_cond_resnet.fullmatch(lowerCAmelCase_ ): lowerCAmelCase__ = re_prior_cond_resnet.match(lowerCAmelCase_ ) lowerCAmelCase__ = regex_match.groups() lowerCAmelCase__ = int(groups[1] ) * 2 + int(groups[2] ) - 2 lowerCAmelCase__ = {"1": 1, "3": 2}[groups[-2]] lowerCAmelCase__ = F'conditioner_blocks.upsampler.upsample_block.{block_index}.' lowerCAmelCase__ = F'resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}' lowerCAmelCase__ = prefix + resnet_block lowerCAmelCase__ = re_prior_cond_resnet.sub(lowerCAmelCase_ , lowerCAmelCase_ ) elif re_prior_cond_proj_in.fullmatch(lowerCAmelCase_ ): lowerCAmelCase__ = re_prior_cond_proj_in.match(lowerCAmelCase_ ) lowerCAmelCase__ = regex_match.groups() lowerCAmelCase__ = F'conditioner_blocks.upsampler.proj_in.{groups[-1]}' lowerCAmelCase__ = re_prior_cond_proj_in.sub(lowerCAmelCase_ , lowerCAmelCase_ ) # keep original key else: lowerCAmelCase__ = original_key lowerCAmelCase__ = replace_key(lowerCAmelCase_ ) if F'{key_prefix}.{key}' not in model_state_dict or key is None: print(F'failed converting {original_key} to {key}, does not match' ) # handle missmatched shape elif value.shape != model_state_dict[F'{key_prefix}.{key}'].shape: lowerCAmelCase__ = model_state_dict[F'{key_prefix}.{key}'] print(F'{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match' ) lowerCAmelCase__ = original_key lowerCAmelCase__ = original_key lowerCAmelCase__ = value return new_dict @torch.no_grad() def _A ( lowerCAmelCase_ : int=None , lowerCAmelCase_ : List[Any]=None ): """simple docstring""" for file in MODEL_MAPPING[model_name]: if not os.path.isfile(F'{pytorch_dump_folder_path}/{file.split("/" )[-1]}' ): lowerCAmelCase__ = requests.get(F'{PREFIX}{file}' , allow_redirects=lowerCAmelCase_ ) os.makedirs(F'{pytorch_dump_folder_path}/' , exist_ok=lowerCAmelCase_ ) open(F'{pytorch_dump_folder_path}/{file.split("/" )[-1]}' , "wb" ).write(r.content ) lowerCAmelCase__ = MODEL_MAPPING[model_name.split("/" )[-1]] lowerCAmelCase__ = JukeboxConfig.from_pretrained(lowerCAmelCase_ ) lowerCAmelCase__ = JukeboxModel(lowerCAmelCase_ ) lowerCAmelCase__ = [] lowerCAmelCase__ = {} for i, dict_name in enumerate(lowerCAmelCase_ ): lowerCAmelCase__ = torch.load(F'{pytorch_dump_folder_path}/{dict_name.split("/" )[-1]}' )["model"] lowerCAmelCase__ = {} for k in old_dic.keys(): if k.endswith(".b" ): lowerCAmelCase__ = old_dic[k] elif k.endswith(".w" ): lowerCAmelCase__ = old_dic[k] elif "level_2" not in dict_name and "cond.model." in k: lowerCAmelCase__ = old_dic[k] else: lowerCAmelCase__ = old_dic[k] lowerCAmelCase__ = "vqvae" if i == 0 else F'priors.{3 - i}' lowerCAmelCase__ = fix_jukebox_keys(lowerCAmelCase_ , model.state_dict() , lowerCAmelCase_ , lowerCAmelCase_ ) weight_dict.append(lowerCAmelCase_ ) lowerCAmelCase__ = weight_dict.pop(0 ) model.vqvae.load_state_dict(lowerCAmelCase_ ) for i in range(len(lowerCAmelCase_ ) ): model.priors[i].load_state_dict(weight_dict[2 - i] ) Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) with open(F'{pytorch_dump_folder_path}/mapping.json' , "w" ) as txtfile: json.dump(lowerCAmelCase_ , lowerCAmelCase_ ) print(F'Saving model {model_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(lowerCAmelCase_ ) return weight_dict if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='jukebox-5b-lyrics', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default='jukebox-5b-lyrics-converted', type=str, help='Path to the output PyTorch model directory.', ) UpperCamelCase = parser.parse_args() convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
61
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
61
1
from typing import List from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : int = { """snap-research/efficientformer-l1-300""": ( """https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json""" ), } class lowerCamelCase_ ( lowerCamelCase ): a__ = '''efficientformer''' def __init__( self , __lowerCAmelCase = [3, 2, 6, 4] , __lowerCAmelCase = [4_8, 9_6, 2_2_4, 4_4_8] , __lowerCAmelCase = [True, True, True, True] , __lowerCAmelCase = 4_4_8 , __lowerCAmelCase = 3_2 , __lowerCAmelCase = 4 , __lowerCAmelCase = 7 , __lowerCAmelCase = 5 , __lowerCAmelCase = 8 , __lowerCAmelCase = 4 , __lowerCAmelCase = 0.0 , __lowerCAmelCase = 1_6 , __lowerCAmelCase = 3 , __lowerCAmelCase = 3 , __lowerCAmelCase = 3 , __lowerCAmelCase = 2 , __lowerCAmelCase = 1 , __lowerCAmelCase = 0.0 , __lowerCAmelCase = 1 , __lowerCAmelCase = True , __lowerCAmelCase = True , __lowerCAmelCase = 1E-5 , __lowerCAmelCase = "gelu" , __lowerCAmelCase = 0.02 , __lowerCAmelCase = 1E-12 , __lowerCAmelCase = 2_2_4 , __lowerCAmelCase = 1E-05 , **__lowerCAmelCase , ): """simple docstring""" super().__init__(**__lowerCAmelCase ) __magic_name__ :Union[str, Any] = hidden_act __magic_name__ :int = hidden_dropout_prob __magic_name__ :List[Any] = hidden_sizes __magic_name__ :Optional[Any] = num_hidden_layers __magic_name__ :str = num_attention_heads __magic_name__ :int = initializer_range __magic_name__ :Optional[Any] = layer_norm_eps __magic_name__ :Optional[Any] = patch_size __magic_name__ :int = num_channels __magic_name__ :Optional[int] = depths __magic_name__ :List[Any] = mlp_expansion_ratio __magic_name__ :int = downsamples __magic_name__ :Dict = dim __magic_name__ :List[Any] = key_dim __magic_name__ :List[Any] = attention_ratio __magic_name__ :str = resolution __magic_name__ :Optional[int] = pool_size __magic_name__ :List[Any] = downsample_patch_size __magic_name__ :int = downsample_stride __magic_name__ :Any = downsample_pad __magic_name__ :Optional[Any] = drop_path_rate __magic_name__ :List[str] = num_metaad_blocks __magic_name__ :Any = distillation __magic_name__ :Tuple = use_layer_scale __magic_name__ :Dict = layer_scale_init_value __magic_name__ :List[Any] = image_size __magic_name__ :Optional[Any] = batch_norm_eps
0
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = ["pixel_values"] def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Union[int, float] = 1 / 255 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> None: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = size if size is not None else {"shortest_edge": 384} lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = do_resize lowerCAmelCase__ = size # Default value set here for backwards compatibility where the value in config is None lowerCAmelCase__ = crop_pct if crop_pct is not None else 224 / 256 lowerCAmelCase__ = resample lowerCAmelCase__ = do_rescale lowerCAmelCase__ = rescale_factor lowerCAmelCase__ = do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN lowerCAmelCase__ = image_std if image_std is not None else IMAGENET_STANDARD_STD def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : int , ) -> np.ndarray: lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) if "shortest_edge" not in size: raise ValueError(f'Size dictionary must contain \'shortest_edge\' key. Got {size.keys()}' ) lowerCAmelCase__ = size["shortest_edge"] if shortest_edge < 384: # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct lowerCAmelCase__ = int(shortest_edge / crop_pct ) lowerCAmelCase__ = get_resize_output_image_size(SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # then crop to (shortest_edge, shortest_edge) return center_crop(image=SCREAMING_SNAKE_CASE__ , size=(shortest_edge, shortest_edge) , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) else: # warping (no cropping) when evaluated at 384 or larger return resize( SCREAMING_SNAKE_CASE__ , size=(shortest_edge, shortest_edge) , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : int , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[int, float] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> List[Any]: return rescale(SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Optional[int] , ) -> np.ndarray: return normalize(SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : ImageInput , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE__ : ChannelDimension = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE__ : Dict , ) -> PIL.Image.Image: lowerCAmelCase__ = do_resize if do_resize is not None else self.do_resize lowerCAmelCase__ = crop_pct if crop_pct is not None else self.crop_pct lowerCAmelCase__ = resample if resample is not None else self.resample lowerCAmelCase__ = do_rescale if do_rescale is not None else self.do_rescale lowerCAmelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCAmelCase__ = do_normalize if do_normalize is not None else self.do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else self.image_mean lowerCAmelCase__ = image_std if image_std is not None else self.image_std lowerCAmelCase__ = size if size is not None else self.size lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = make_list_of_images(SCREAMING_SNAKE_CASE__ ) if not valid_images(SCREAMING_SNAKE_CASE__ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_resize and size["shortest_edge"] < 384 and crop_pct is None: raise ValueError("crop_pct must be specified if size < 384." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. lowerCAmelCase__ = [to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if do_resize: lowerCAmelCase__ = [self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , crop_pct=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images] if do_rescale: lowerCAmelCase__ = [self.rescale(image=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ ) for image in images] if do_normalize: lowerCAmelCase__ = [self.normalize(image=SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = {"pixel_values": images} return BatchFeature(data=SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ )
61
0
import argparse import tensorflow as tf import torch from transformers import BertConfig, BertForMaskedLM from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertPooler, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging logging.set_verbosity_info() def _A ( _lowercase , _lowercase , _lowercase ) -> Union[str, Any]: """simple docstring""" def get_masked_lm_array(_lowercase ): __UpperCamelCase = f'''masked_lm/{name}/.ATTRIBUTES/VARIABLE_VALUE''' __UpperCamelCase = tf.train.load_variable(_lowercase , _lowercase ) if "kernel" in name: __UpperCamelCase = array.transpose() return torch.from_numpy(_lowercase ) def get_encoder_array(_lowercase ): __UpperCamelCase = f'''encoder/{name}/.ATTRIBUTES/VARIABLE_VALUE''' __UpperCamelCase = tf.train.load_variable(_lowercase , _lowercase ) if "kernel" in name: __UpperCamelCase = array.transpose() return torch.from_numpy(_lowercase ) def get_encoder_layer_array(_lowercase , _lowercase ): __UpperCamelCase = f'''encoder/_transformer_layers/{layer_index}/{name}/.ATTRIBUTES/VARIABLE_VALUE''' __UpperCamelCase = tf.train.load_variable(_lowercase , _lowercase ) if "kernel" in name: __UpperCamelCase = array.transpose() return torch.from_numpy(_lowercase ) def get_encoder_attention_layer_array(_lowercase , _lowercase , _lowercase ): __UpperCamelCase = f'''encoder/_transformer_layers/{layer_index}/_attention_layer/{name}/.ATTRIBUTES/VARIABLE_VALUE''' __UpperCamelCase = tf.train.load_variable(_lowercase , _lowercase ) __UpperCamelCase = array.reshape(_lowercase ) if "kernel" in name: __UpperCamelCase = array.transpose() return torch.from_numpy(_lowercase ) print(f'''Loading model based on config from {config_path}...''' ) __UpperCamelCase = BertConfig.from_json_file(_lowercase ) __UpperCamelCase = BertForMaskedLM(_lowercase ) # Layers for layer_index in range(0 , config.num_hidden_layers ): __UpperCamelCase = model.bert.encoder.layer[layer_index] # Self-attention __UpperCamelCase = layer.attention.self __UpperCamelCase = get_encoder_attention_layer_array( _lowercase , '_query_dense/kernel' , self_attn.query.weight.data.shape ) __UpperCamelCase = get_encoder_attention_layer_array( _lowercase , '_query_dense/bias' , self_attn.query.bias.data.shape ) __UpperCamelCase = get_encoder_attention_layer_array( _lowercase , '_key_dense/kernel' , self_attn.key.weight.data.shape ) __UpperCamelCase = get_encoder_attention_layer_array( _lowercase , '_key_dense/bias' , self_attn.key.bias.data.shape ) __UpperCamelCase = get_encoder_attention_layer_array( _lowercase , '_value_dense/kernel' , self_attn.value.weight.data.shape ) __UpperCamelCase = get_encoder_attention_layer_array( _lowercase , '_value_dense/bias' , self_attn.value.bias.data.shape ) # Self-attention Output __UpperCamelCase = layer.attention.output __UpperCamelCase = get_encoder_attention_layer_array( _lowercase , '_output_dense/kernel' , self_output.dense.weight.data.shape ) __UpperCamelCase = get_encoder_attention_layer_array( _lowercase , '_output_dense/bias' , self_output.dense.bias.data.shape ) __UpperCamelCase = get_encoder_layer_array(_lowercase , '_attention_layer_norm/gamma' ) __UpperCamelCase = get_encoder_layer_array(_lowercase , '_attention_layer_norm/beta' ) # Intermediate __UpperCamelCase = layer.intermediate __UpperCamelCase = get_encoder_layer_array(_lowercase , '_intermediate_dense/kernel' ) __UpperCamelCase = get_encoder_layer_array(_lowercase , '_intermediate_dense/bias' ) # Output __UpperCamelCase = layer.output __UpperCamelCase = get_encoder_layer_array(_lowercase , '_output_dense/kernel' ) __UpperCamelCase = get_encoder_layer_array(_lowercase , '_output_dense/bias' ) __UpperCamelCase = get_encoder_layer_array(_lowercase , '_output_layer_norm/gamma' ) __UpperCamelCase = get_encoder_layer_array(_lowercase , '_output_layer_norm/beta' ) # Embeddings __UpperCamelCase = get_encoder_array('_position_embedding_layer/embeddings' ) __UpperCamelCase = get_encoder_array('_type_embedding_layer/embeddings' ) __UpperCamelCase = get_encoder_array('_embedding_norm_layer/gamma' ) __UpperCamelCase = get_encoder_array('_embedding_norm_layer/beta' ) # LM Head __UpperCamelCase = model.cls.predictions.transform __UpperCamelCase = get_masked_lm_array('dense/kernel' ) __UpperCamelCase = get_masked_lm_array('dense/bias' ) __UpperCamelCase = get_masked_lm_array('layer_norm/gamma' ) __UpperCamelCase = get_masked_lm_array('layer_norm/beta' ) __UpperCamelCase = get_masked_lm_array('embedding_table' ) # Pooling __UpperCamelCase = BertPooler(config=_lowercase ) __UpperCamelCase = get_encoder_array('_pooler_layer/kernel' ) __UpperCamelCase = get_encoder_array('_pooler_layer/bias' ) # Export final model model.save_pretrained(_lowercase ) # Integration test - should load without any errors ;) __UpperCamelCase = BertForMaskedLM.from_pretrained(_lowercase ) print(new_model.eval() ) print('Model conversion was done sucessfully!' ) if __name__ == "__main__": __snake_case = argparse.ArgumentParser() parser.add_argument( '''--tf_checkpoint_path''', type=str, required=True, help='''Path to the TensorFlow Token Dropping checkpoint path.''' ) parser.add_argument( '''--bert_config_file''', type=str, required=True, help='''The config json file corresponding to the BERT model. This specifies the model architecture.''', ) parser.add_argument( '''--pytorch_dump_path''', type=str, required=True, help='''Path to the output PyTorch model.''', ) __snake_case = parser.parse_args() convert_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
1
import shutil import tempfile import unittest import numpy as np import pytest from transformers import is_speech_available, is_vision_available from transformers.testing_utils import require_torch if is_vision_available(): from transformers import TvltImageProcessor if is_speech_available(): from transformers import TvltFeatureExtractor from transformers import TvltProcessor @require_torch class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : Any ) -> int: lowerCAmelCase__ = "ZinengTang/tvlt-base" lowerCAmelCase__ = tempfile.mkdtemp() def a ( self : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: return TvltImageProcessor.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE__ ) def a ( self : int , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> str: return TvltFeatureExtractor.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] ) -> Any: shutil.rmtree(self.tmpdirname ) def a ( self : Any ) -> Union[str, Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) lowerCAmelCase__ = TvltProcessor.from_pretrained(self.tmpdirname ) self.assertIsInstance(processor.feature_extractor , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> List[Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([12_000] ) lowerCAmelCase__ = feature_extractor(SCREAMING_SNAKE_CASE__ , return_tensors="np" ) lowerCAmelCase__ = processor(audio=SCREAMING_SNAKE_CASE__ , return_tensors="np" ) for key in audio_dict.keys(): self.assertAlmostEqual(audio_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a ( self : Dict ) -> str: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([3, 224, 224] ) lowerCAmelCase__ = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors="np" ) lowerCAmelCase__ = processor(images=SCREAMING_SNAKE_CASE__ , return_tensors="np" ) for key in image_dict.keys(): self.assertAlmostEqual(image_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a ( self : int ) -> Any: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([12_000] ) lowerCAmelCase__ = np.ones([3, 224, 224] ) lowerCAmelCase__ = processor(audio=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , ["audio_values", "audio_mask", "pixel_values", "pixel_mask"] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE__ ): processor() def a ( self : Tuple ) -> Optional[Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( processor.model_input_names , image_processor.model_input_names + feature_extractor.model_input_names , msg="`processor` and `image_processor`+`feature_extractor` model input names do not match" , )
61
0
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import AlignProcessor, EfficientNetImageProcessor @require_vision class lowerCamelCase__ ( unittest.TestCase): """simple docstring""" def snake_case_ ( self : Tuple ) -> Optional[int]: _A = tempfile.mkdtemp() _A = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] _A = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) _A = { '''do_resize''': True, '''size''': 20, '''do_center_crop''': True, '''crop_size''': 18, '''do_normalize''': True, '''image_mean''': [0.4814_5466, 0.457_8275, 0.4082_1073], '''image_std''': [0.2686_2954, 0.2613_0258, 0.2757_7711], } _A = os.path.join(self.tmpdirname , __lowerCAmelCase ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(__lowerCAmelCase , __lowerCAmelCase ) def snake_case_ ( self : Dict , **__lowerCAmelCase : int ) -> Optional[int]: return BertTokenizer.from_pretrained(self.tmpdirname , **__lowerCAmelCase ) def snake_case_ ( self : str , **__lowerCAmelCase : Optional[Any] ) -> Tuple: return BertTokenizerFast.from_pretrained(self.tmpdirname , **__lowerCAmelCase ) def snake_case_ ( self : Tuple , **__lowerCAmelCase : str ) -> Union[str, Any]: return EfficientNetImageProcessor.from_pretrained(self.tmpdirname , **__lowerCAmelCase ) def snake_case_ ( self : Optional[Any] ) -> Optional[int]: shutil.rmtree(self.tmpdirname ) def snake_case_ ( self : int ) -> Optional[Any]: _A = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] _A = [Image.fromarray(np.moveaxis(__lowerCAmelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def snake_case_ ( self : Dict ) -> List[str]: _A = self.get_tokenizer() _A = self.get_rust_tokenizer() _A = self.get_image_processor() _A = AlignProcessor(tokenizer=__lowerCAmelCase , image_processor=__lowerCAmelCase ) processor_slow.save_pretrained(self.tmpdirname ) _A = AlignProcessor.from_pretrained(self.tmpdirname , use_fast=__lowerCAmelCase ) _A = AlignProcessor(tokenizer=__lowerCAmelCase , image_processor=__lowerCAmelCase ) processor_fast.save_pretrained(self.tmpdirname ) _A = AlignProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __lowerCAmelCase ) self.assertIsInstance(processor_fast.tokenizer , __lowerCAmelCase ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __lowerCAmelCase ) self.assertIsInstance(processor_fast.image_processor , __lowerCAmelCase ) def snake_case_ ( self : List[Any] ) -> List[str]: _A = AlignProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) _A = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) _A = self.get_image_processor(do_normalize=__lowerCAmelCase , padding_value=1.0 ) _A = AlignProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=__lowerCAmelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __lowerCAmelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __lowerCAmelCase ) def snake_case_ ( self : str ) -> List[Any]: _A = self.get_image_processor() _A = self.get_tokenizer() _A = AlignProcessor(tokenizer=__lowerCAmelCase , image_processor=__lowerCAmelCase ) _A = self.prepare_image_inputs() _A = image_processor(__lowerCAmelCase , return_tensors='''np''' ) _A = processor(images=__lowerCAmelCase , return_tensors='''np''' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def snake_case_ ( self : Union[str, Any] ) -> Dict: _A = self.get_image_processor() _A = self.get_tokenizer() _A = AlignProcessor(tokenizer=__lowerCAmelCase , image_processor=__lowerCAmelCase ) _A = '''lower newer''' _A = processor(text=__lowerCAmelCase ) _A = tokenizer(__lowerCAmelCase , padding='''max_length''' , max_length=64 ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def snake_case_ ( self : List[str] ) -> Any: _A = self.get_image_processor() _A = self.get_tokenizer() _A = AlignProcessor(tokenizer=__lowerCAmelCase , image_processor=__lowerCAmelCase ) _A = '''lower newer''' _A = self.prepare_image_inputs() _A = processor(text=__lowerCAmelCase , images=__lowerCAmelCase ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(__lowerCAmelCase ): processor() def snake_case_ ( self : Optional[Any] ) -> str: _A = self.get_image_processor() _A = self.get_tokenizer() _A = AlignProcessor(tokenizer=__lowerCAmelCase , image_processor=__lowerCAmelCase ) _A = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] _A = processor.batch_decode(__lowerCAmelCase ) _A = tokenizer.batch_decode(__lowerCAmelCase ) self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase ) def snake_case_ ( self : str ) -> str: _A = self.get_image_processor() _A = self.get_tokenizer() _A = AlignProcessor(tokenizer=__lowerCAmelCase , image_processor=__lowerCAmelCase ) _A = '''lower newer''' _A = self.prepare_image_inputs() _A = processor(text=__lowerCAmelCase , images=__lowerCAmelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
2
import os # Precomputes a list of the 100 first triangular numbers UpperCamelCase = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def _A ( ): """simple docstring""" lowerCAmelCase__ = os.path.dirname(os.path.realpath(lowerCAmelCase_ ) ) lowerCAmelCase__ = os.path.join(lowerCAmelCase_ , "words.txt" ) lowerCAmelCase__ = "" with open(lowerCAmelCase_ ) as f: lowerCAmelCase__ = f.readline() lowerCAmelCase__ = [word.strip("\"" ) for word in words.strip("\r\n" ).split("," )] lowerCAmelCase__ = [ word for word in [sum(ord(lowerCAmelCase_ ) - 64 for x in word ) for word in words] if word in TRIANGULAR_NUMBERS ] return len(lowerCAmelCase_ ) if __name__ == "__main__": print(solution())
61
0
'''simple docstring''' import time from dataclasses import dataclass from multiprocessing import Pool from unittest import TestCase from unittest.mock import patch import multiprocess import numpy as np import pytest from datasets.utils.py_utils import ( NestedDataStructure, asdict, iflatmap_unordered, map_nested, temp_seed, temporary_assignment, zip_dict, ) from .utils import require_tf, require_torch def A_( A : str): # picklable for multiprocessing return x.sum() def A_( A : Union[str, Any]): # picklable for multiprocessing return i + 1 @dataclass class SCREAMING_SNAKE_CASE__ : lowerCAmelCase_ = 42 lowerCAmelCase_ = 42 class SCREAMING_SNAKE_CASE__ ( snake_case_): def UpperCAmelCase_ ( self )-> Any: '''simple docstring''' UpperCamelCase = {} UpperCamelCase = [] UpperCamelCase = 1 UpperCamelCase = [1, 2] UpperCamelCase = {'a': 1, 'b': 2} UpperCamelCase = {'a': [1, 2], 'b': [3, 4]} UpperCamelCase = {'a': {'1': 1}, 'b': 2} UpperCamelCase = {'a': 1, 'b': 2, 'c': 3, 'd': 4} UpperCamelCase = {} UpperCamelCase = [] UpperCamelCase = 2 UpperCamelCase = [2, 3] UpperCamelCase = {'a': 2, 'b': 3} UpperCamelCase = {'a': [2, 3], 'b': [4, 5]} UpperCamelCase = {'a': {'1': 2}, 'b': 3} UpperCamelCase = {'a': 2, 'b': 3, 'c': 4, 'd': 5} self.assertEqual(map_nested(A_ , A_ ) , A_ ) self.assertEqual(map_nested(A_ , A_ ) , A_ ) self.assertEqual(map_nested(A_ , A_ ) , A_ ) self.assertEqual(map_nested(A_ , A_ ) , A_ ) self.assertEqual(map_nested(A_ , A_ ) , A_ ) self.assertEqual(map_nested(A_ , A_ ) , A_ ) self.assertEqual(map_nested(A_ , A_ ) , A_ ) self.assertEqual(map_nested(A_ , A_ ) , A_ ) UpperCamelCase = 2 self.assertEqual(map_nested(A_ , A_ , num_proc=A_ ) , A_ ) self.assertEqual(map_nested(A_ , A_ , num_proc=A_ ) , A_ ) self.assertEqual(map_nested(A_ , A_ , num_proc=A_ ) , A_ ) self.assertEqual(map_nested(A_ , A_ , num_proc=A_ ) , A_ ) self.assertEqual(map_nested(A_ , A_ , num_proc=A_ ) , A_ ) self.assertEqual(map_nested(A_ , A_ , num_proc=A_ ) , A_ ) self.assertEqual(map_nested(A_ , A_ , num_proc=A_ ) , A_ ) self.assertEqual(map_nested(A_ , A_ , num_proc=A_ ) , A_ ) UpperCamelCase = {'a': np.eye(2 ), 'b': np.zeros(3 ), 'c': np.ones(2 )} UpperCamelCase = {'a': 2, 'b': 0, 'c': 2} UpperCamelCase = { 'a': np.eye(2 ).astype(A_ ), 'b': np.zeros(3 ).astype(A_ ), 'c': np.ones(2 ).astype(A_ ), } self.assertEqual(map_nested(A_ , A_ , map_numpy=A_ ) , A_ ) self.assertEqual( {k: v.tolist() for k, v in map_nested(A_ , A_ , map_numpy=A_ ).items()} , {k: v.tolist() for k, v in expected_map_nested_sna_int.items()} , ) self.assertEqual(map_nested(A_ , A_ , map_numpy=A_ , num_proc=A_ ) , A_ ) self.assertEqual( {k: v.tolist() for k, v in map_nested(A_ , A_ , map_numpy=A_ , num_proc=A_ ).items()} , {k: v.tolist() for k, v in expected_map_nested_sna_int.items()} , ) with self.assertRaises(A_ ): # can't pickle a local lambda map_nested(lambda A_ : x + 1 , A_ , num_proc=A_ ) def UpperCAmelCase_ ( self )-> Tuple: '''simple docstring''' UpperCamelCase = {'a': 1, 'b': 2} UpperCamelCase = {'a': 3, 'b': 4} UpperCamelCase = {'a': 5, 'b': 6} UpperCamelCase = sorted([('a', (1, 3, 5)), ('b', (2, 4, 6))] ) self.assertEqual(sorted(zip_dict(A_ , A_ , A_ ) ) , A_ ) def UpperCAmelCase_ ( self )-> Optional[int]: '''simple docstring''' class SCREAMING_SNAKE_CASE__ : lowerCAmelCase_ = """bar""" UpperCamelCase = Foo() self.assertEqual(foo.my_attr , 'bar' ) with temporary_assignment(A_ , 'my_attr' , 'BAR' ): self.assertEqual(foo.my_attr , 'BAR' ) self.assertEqual(foo.my_attr , 'bar' ) @pytest.mark.parametrize( 'iterable_length, num_proc, expected_num_proc' , [ (1, None, 1), (1, 1, 1), (2, None, 1), (2, 1, 1), (2, 2, 1), (2, 3, 1), (3, 2, 1), (16, 16, 16), (16, 17, 16), (17, 16, 16), ] , ) def A_( A : Optional[Any] , A : str , A : Optional[Any]): with patch('datasets.utils.py_utils._single_map_nested') as mock_single_map_nested, patch( 'datasets.parallel.parallel.Pool') as mock_multiprocessing_pool: UpperCamelCase = {f'''{i}''': i for i in range(A)} UpperCamelCase = map_nested(lambda A: x + 10 , A , num_proc=A , parallel_min_length=16) if expected_num_proc == 1: assert mock_single_map_nested.called assert not mock_multiprocessing_pool.called else: assert not mock_single_map_nested.called assert mock_multiprocessing_pool.called assert mock_multiprocessing_pool.call_args[0][0] == expected_num_proc class SCREAMING_SNAKE_CASE__ ( snake_case_): @require_tf def UpperCAmelCase_ ( self )-> List[str]: '''simple docstring''' import tensorflow as tf from tensorflow.keras import layers UpperCamelCase = layers.Dense(2 ) def gen_random_output(): UpperCamelCase = tf.random.uniform((1, 3) ) return model(A_ ).numpy() with temp_seed(42 , set_tensorflow=A_ ): UpperCamelCase = gen_random_output() with temp_seed(42 , set_tensorflow=A_ ): UpperCamelCase = gen_random_output() UpperCamelCase = gen_random_output() np.testing.assert_equal(A_ , A_ ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) @require_torch def UpperCAmelCase_ ( self )-> int: '''simple docstring''' import torch def gen_random_output(): UpperCamelCase = torch.nn.Linear(3 , 2 ) UpperCamelCase = torch.rand(1 , 3 ) return model(A_ ).detach().numpy() with temp_seed(42 , set_pytorch=A_ ): UpperCamelCase = gen_random_output() with temp_seed(42 , set_pytorch=A_ ): UpperCamelCase = gen_random_output() UpperCamelCase = gen_random_output() np.testing.assert_equal(A_ , A_ ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) def UpperCAmelCase_ ( self )-> Union[str, Any]: '''simple docstring''' def gen_random_output(): return np.random.rand(1 , 3 ) with temp_seed(42 ): UpperCamelCase = gen_random_output() with temp_seed(42 ): UpperCamelCase = gen_random_output() UpperCamelCase = gen_random_output() np.testing.assert_equal(A_ , A_ ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) @pytest.mark.parametrize('input_data' , [{}]) def A_( A : Any): UpperCamelCase = NestedDataStructure(A).data assert output_data == input_data @pytest.mark.parametrize( 'data, expected_output' , [ ({}, []), ([], []), ('foo', ['foo']), (['foo', 'bar'], ['foo', 'bar']), ([['foo', 'bar']], ['foo', 'bar']), ([[['foo'], ['bar']]], ['foo', 'bar']), ([[['foo'], 'bar']], ['foo', 'bar']), ({'a': 1, 'b': 2}, [1, 2]), ({'a': [1, 2], 'b': [3, 4]}, [1, 2, 3, 4]), ({'a': [[1, 2]], 'b': [[3, 4]]}, [1, 2, 3, 4]), ({'a': [[1, 2]], 'b': [3, 4]}, [1, 2, 3, 4]), ({'a': [[[1], [2]]], 'b': [[[3], [4]]]}, [1, 2, 3, 4]), ({'a': [[[1], [2]]], 'b': [[3, 4]]}, [1, 2, 3, 4]), ({'a': [[[1], [2]]], 'b': [3, 4]}, [1, 2, 3, 4]), ({'a': [[[1], [2]]], 'b': [3, [4]]}, [1, 2, 3, 4]), ({'a': {'1': 1}, 'b': 2}, [1, 2]), ({'a': {'1': [1]}, 'b': 2}, [1, 2]), ({'a': {'1': [1]}, 'b': [2]}, [1, 2]), ] , ) def A_( A : Optional[Any] , A : Optional[int]): UpperCamelCase = NestedDataStructure(A).flatten() assert output == expected_output def A_( ): UpperCamelCase = A(x=1 , y='foobar') UpperCamelCase = {'x': 1, 'y': 'foobar'} assert asdict(A) == expected_output UpperCamelCase = {'a': {'b': A(x=10 , y='foo')}, 'c': [A(x=20 , y='bar')]} UpperCamelCase = {'a': {'b': {'x': 10, 'y': 'foo'}}, 'c': [{'x': 20, 'y': 'bar'}]} assert asdict(A) == expected_output with pytest.raises(A): asdict([1, A(x=10 , y='foo')]) def A_( A : str): return text.split() def A_( A : Optional[int]): yield (time.time(), content) time.sleep(2) yield (time.time(), content) def A_( ): with Pool(2) as pool: UpperCamelCase = list(iflatmap_unordered(A , _split_text , kwargs_iterable=[{'text': 'hello there'}] * 10)) assert out.count('hello') == 10 assert out.count('there') == 10 assert len(A) == 20 # check multiprocess from pathos (uses dill for pickling) with multiprocess.Pool(2) as pool: UpperCamelCase = list(iflatmap_unordered(A , _split_text , kwargs_iterable=[{'text': 'hello there'}] * 10)) assert out.count('hello') == 10 assert out.count('there') == 10 assert len(A) == 20 # check that we get items as fast as possible with Pool(2) as pool: UpperCamelCase = [] for yield_time, content in iflatmap_unordered( A , _aseconds_generator_of_aitems_with_timing , kwargs_iterable=[{'content': 'a'}, {'content': 'b'}]): assert yield_time < time.time() + 0.1, "we should each item directly after it was yielded" out.append(A) assert out.count('a') == 2 assert out.count('b') == 2 assert len(A) == 4
3
import random def _A ( lowerCAmelCase_ : Dict , lowerCAmelCase_ : int , lowerCAmelCase_ : Any ): """simple docstring""" lowerCAmelCase__ = a[left_index] lowerCAmelCase__ = left_index + 1 for j in range(left_index + 1 , lowerCAmelCase_ ): if a[j] < pivot: lowerCAmelCase__ , lowerCAmelCase__ = a[i], a[j] i += 1 lowerCAmelCase__ , lowerCAmelCase__ = a[i - 1], a[left_index] return i - 1 def _A ( lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : str ): """simple docstring""" if left < right: lowerCAmelCase__ = random.randint(lowerCAmelCase_ , right - 1 ) lowerCAmelCase__ , lowerCAmelCase__ = ( a[left], a[pivot], ) # switches the pivot with the left most bound lowerCAmelCase__ = partition(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) quick_sort_random( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # recursive quicksort to the left of the pivot point quick_sort_random( lowerCAmelCase_ , pivot_index + 1 , lowerCAmelCase_ ) # recursive quicksort to the right of the pivot point def _A ( ): """simple docstring""" lowerCAmelCase__ = input("Enter numbers separated by a comma:\n" ).strip() lowerCAmelCase__ = [int(lowerCAmelCase_ ) for item in user_input.split("," )] quick_sort_random(lowerCAmelCase_ , 0 , len(lowerCAmelCase_ ) ) print(lowerCAmelCase_ ) if __name__ == "__main__": main()
61
0
"""simple docstring""" import argparse import json import os import time import zipfile from get_ci_error_statistics import download_artifact, get_artifacts_links from transformers import logging __UpperCamelCase : int = logging.get_logger(__name__) def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : Any , _UpperCAmelCase : Optional[int] ): lowerCAmelCase = set() lowerCAmelCase = [] def parse_line(_UpperCAmelCase : str ): for line in fp: if isinstance(_UpperCAmelCase , _UpperCAmelCase ): lowerCAmelCase = line.decode('UTF-8' ) if "warnings summary (final)" in line: continue # This means we are outside the body of a warning elif not line.startswith(' ' ): # process a single warning and move it to `selected_warnings`. if len(_UpperCAmelCase ) > 0: lowerCAmelCase = '\n'.join(_UpperCAmelCase ) # Only keep the warnings specified in `targets` if any(F': {x}: ' in warning for x in targets ): selected_warnings.add(_UpperCAmelCase ) buffer.clear() continue else: lowerCAmelCase = line.strip() buffer.append(_UpperCAmelCase ) if from_gh: for filename in os.listdir(_UpperCAmelCase ): lowerCAmelCase = os.path.join(_UpperCAmelCase , _UpperCAmelCase ) if not os.path.isdir(_UpperCAmelCase ): # read the file if filename != "warnings.txt": continue with open(_UpperCAmelCase ) as fp: parse_line(_UpperCAmelCase ) else: try: with zipfile.ZipFile(_UpperCAmelCase ) as z: for filename in z.namelist(): if not os.path.isdir(_UpperCAmelCase ): # read the file if filename != "warnings.txt": continue with z.open(_UpperCAmelCase ) as fp: parse_line(_UpperCAmelCase ) except Exception: logger.warning( F'{artifact_path} is either an invalid zip file or something else wrong. This file is skipped.' ) return selected_warnings def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : int ): lowerCAmelCase = set() lowerCAmelCase = [os.path.join(_UpperCAmelCase , _UpperCAmelCase ) for p in os.listdir(_UpperCAmelCase ) if (p.endswith('.zip' ) or from_gh)] for p in paths: selected_warnings.update(extract_warnings_from_single_artifact(_UpperCAmelCase , _UpperCAmelCase ) ) return selected_warnings if __name__ == "__main__": def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : Optional[Any] ): return values.split(',' ) __UpperCamelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument('''--workflow_run_id''', type=str, required=True, help='''A GitHub Actions workflow run id.''') parser.add_argument( '''--output_dir''', type=str, required=True, help='''Where to store the downloaded artifacts and other result files.''', ) parser.add_argument('''--token''', default=None, type=str, help='''A token that has actions:read permission.''') # optional parameters parser.add_argument( '''--targets''', default='''DeprecationWarning,UserWarning,FutureWarning''', type=list_str, help='''Comma-separated list of target warning(s) which we want to extract.''', ) parser.add_argument( '''--from_gh''', action='''store_true''', help='''If running from a GitHub action workflow and collecting warnings from its artifacts.''', ) __UpperCamelCase : List[str] = parser.parse_args() __UpperCamelCase : Optional[Any] = args.from_gh if from_gh: # The artifacts have to be downloaded using `actions/download-artifact@v3` pass else: os.makedirs(args.output_dir, exist_ok=True) # get download links __UpperCamelCase : Optional[Any] = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, '''artifacts.json'''), '''w''', encoding='''UTF-8''') as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) # download artifacts for idx, (name, url) in enumerate(artifacts.items()): print(name) print(url) print('''=''' * 80) download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) # extract warnings from artifacts __UpperCamelCase : Any = extract_warnings(args.output_dir, args.targets) __UpperCamelCase : Tuple = sorted(selected_warnings) with open(os.path.join(args.output_dir, '''selected_warnings.json'''), '''w''', encoding='''UTF-8''') as fp: json.dump(selected_warnings, fp, ensure_ascii=False, indent=4)
4
import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process UpperCamelCase = logging.getLogger(__name__) @dataclass class __lowerCamelCase : """simple docstring""" snake_case__ = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) snake_case__ = field( default="NER" , metadata={"help": "Task type to fine tune in training (e.g. NER, POS, etc)"} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) snake_case__ = field(default=UpperCamelCase__ , metadata={"help": "Set this flag to use fast tokenization."} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) @dataclass class __lowerCamelCase : """simple docstring""" snake_case__ = field( metadata={"help": "The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."} , ) snake_case__ = field( default=1_2_8 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Overwrite the cached training and evaluation sets"} ) def _A ( ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. Use' " --overwrite_output_dir to overcome." ) lowerCAmelCase__ = import_module("tasks" ) try: lowerCAmelCase__ = getattr(lowerCAmelCase_ , model_args.task_type ) lowerCAmelCase__ = token_classification_task_clazz() except AttributeError: raise ValueError( F'Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. ' F'Available tasks classes are: {TokenClassificationTask.__subclasses__()}' ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("Training/evaluation parameters %s" , lowerCAmelCase_ ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task lowerCAmelCase__ = token_classification_task.get_labels(data_args.labels ) lowerCAmelCase__ = dict(enumerate(lowerCAmelCase_ ) ) lowerCAmelCase__ = len(lowerCAmelCase_ ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowerCAmelCase__ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=lowerCAmelCase_ , idalabel=lowerCAmelCase_ , labelaid={label: i for i, label in enumerate(lowerCAmelCase_ )} , cache_dir=model_args.cache_dir , ) lowerCAmelCase__ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast , ) lowerCAmelCase__ = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , ) # Get datasets lowerCAmelCase__ = ( TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) lowerCAmelCase__ = ( TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def align_predictions(lowerCAmelCase_ : np.ndarray , lowerCAmelCase_ : np.ndarray ) -> Tuple[List[int], List[int]]: lowerCAmelCase__ = np.argmax(lowerCAmelCase_ , axis=2 ) lowerCAmelCase__ , lowerCAmelCase__ = preds.shape lowerCAmelCase__ = [[] for _ in range(lowerCAmelCase_ )] lowerCAmelCase__ = [[] for _ in range(lowerCAmelCase_ )] for i in range(lowerCAmelCase_ ): for j in range(lowerCAmelCase_ ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(lowerCAmelCase_ : EvalPrediction ) -> Dict: lowerCAmelCase__ , lowerCAmelCase__ = align_predictions(p.predictions , p.label_ids ) return { "accuracy_score": accuracy_score(lowerCAmelCase_ , lowerCAmelCase_ ), "precision": precision_score(lowerCAmelCase_ , lowerCAmelCase_ ), "recall": recall_score(lowerCAmelCase_ , lowerCAmelCase_ ), "f1": fa_score(lowerCAmelCase_ , lowerCAmelCase_ ), } # Data collator lowerCAmelCase__ = DataCollatorWithPadding(lowerCAmelCase_ , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer lowerCAmelCase__ = Trainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , train_dataset=lowerCAmelCase_ , eval_dataset=lowerCAmelCase_ , compute_metrics=lowerCAmelCase_ , data_collator=lowerCAmelCase_ , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation lowerCAmelCase__ = {} if training_args.do_eval: logger.info("*** Evaluate ***" ) lowerCAmelCase__ = trainer.evaluate() lowerCAmelCase__ = os.path.join(training_args.output_dir , "eval_results.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: logger.info("***** Eval results *****" ) for key, value in result.items(): logger.info(" %s = %s" , lowerCAmelCase_ , lowerCAmelCase_ ) writer.write("%s = %s\n" % (key, value) ) results.update(lowerCAmelCase_ ) # Predict if training_args.do_predict: lowerCAmelCase__ = TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = trainer.predict(lowerCAmelCase_ ) lowerCAmelCase__ , lowerCAmelCase__ = align_predictions(lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ = os.path.join(training_args.output_dir , "test_results.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: for key, value in metrics.items(): logger.info(" %s = %s" , lowerCAmelCase_ , lowerCAmelCase_ ) writer.write("%s = %s\n" % (key, value) ) # Save predictions lowerCAmelCase__ = os.path.join(training_args.output_dir , "test_predictions.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: with open(os.path.join(data_args.data_dir , "test.txt" ) , "r" ) as f: token_classification_task.write_predictions_to_file(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return results def _A ( lowerCAmelCase_ : Tuple ): """simple docstring""" main() if __name__ == "__main__": main()
61
0
'''simple docstring''' import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoFeatureExtractor, WavaVecaFeatureExtractor from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test sys.path.append(str(Path(__file__).parent.parent / """utils""")) from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 _lowercase = get_tests_dir("""fixtures""") class UpperCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = mock.Mock() _lowerCAmelCase = 500 _lowerCAmelCase = {} _lowerCAmelCase = HTTPError _lowerCAmelCase = {} # Download this model to make sure it's in the cache. _lowerCAmelCase = WavaVecaFeatureExtractor.from_pretrained("""hf-internal-testing/tiny-random-wav2vec2""" ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch("""requests.Session.request""" , return_value=_lowercase ) as mock_head: _lowerCAmelCase = WavaVecaFeatureExtractor.from_pretrained("""hf-internal-testing/tiny-random-wav2vec2""" ) # This check we did call the fake head request mock_head.assert_called() def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = WavaVecaFeatureExtractor.from_pretrained( """https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json""" ) @is_staging_test class UpperCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @classmethod def _lowercase ( cls ): """simple docstring""" _lowerCAmelCase = TOKEN HfFolder.save_token(_lowercase ) @classmethod def _lowercase ( cls ): """simple docstring""" try: delete_repo(token=cls._token , repo_id="""test-feature-extractor""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""valid_org/test-feature-extractor-org""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""test-dynamic-feature-extractor""" ) except HTTPError: pass def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = WavaVecaFeatureExtractor.from_pretrained(_lowercase ) feature_extractor.push_to_hub("""test-feature-extractor""" , use_auth_token=self._token ) _lowerCAmelCase = WavaVecaFeatureExtractor.from_pretrained(F'{USER}/test-feature-extractor' ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(_lowercase , getattr(_lowercase , _lowercase ) ) # Reset repo delete_repo(token=self._token , repo_id="""test-feature-extractor""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained( _lowercase , repo_id="""test-feature-extractor""" , push_to_hub=_lowercase , use_auth_token=self._token ) _lowerCAmelCase = WavaVecaFeatureExtractor.from_pretrained(F'{USER}/test-feature-extractor' ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(_lowercase , getattr(_lowercase , _lowercase ) ) def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = WavaVecaFeatureExtractor.from_pretrained(_lowercase ) feature_extractor.push_to_hub("""valid_org/test-feature-extractor""" , use_auth_token=self._token ) _lowerCAmelCase = WavaVecaFeatureExtractor.from_pretrained("""valid_org/test-feature-extractor""" ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(_lowercase , getattr(_lowercase , _lowercase ) ) # Reset repo delete_repo(token=self._token , repo_id="""valid_org/test-feature-extractor""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained( _lowercase , repo_id="""valid_org/test-feature-extractor-org""" , push_to_hub=_lowercase , use_auth_token=self._token ) _lowerCAmelCase = WavaVecaFeatureExtractor.from_pretrained("""valid_org/test-feature-extractor-org""" ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(_lowercase , getattr(_lowercase , _lowercase ) ) def _lowercase ( self ): """simple docstring""" CustomFeatureExtractor.register_for_auto_class() _lowerCAmelCase = CustomFeatureExtractor.from_pretrained(_lowercase ) feature_extractor.push_to_hub("""test-dynamic-feature-extractor""" , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual( feature_extractor.auto_map , {"""AutoFeatureExtractor""": """custom_feature_extraction.CustomFeatureExtractor"""} , ) _lowerCAmelCase = AutoFeatureExtractor.from_pretrained( F'{USER}/test-dynamic-feature-extractor' , trust_remote_code=_lowercase ) # Can't make an isinstance check because the new_feature_extractor is from the CustomFeatureExtractor class of a dynamic module self.assertEqual(new_feature_extractor.__class__.__name__ , """CustomFeatureExtractor""" )
5
import os import re from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'vocab_file': 'spiece.model'} UpperCamelCase = { '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' ), } } UpperCamelCase = { 'google/bigbird-roberta-base': 4096, 'google/bigbird-roberta-large': 4096, 'google/bigbird-base-trivia-itc': 4096, } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ = ["input_ids", "attention_mask"] snake_case__ = [] def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str]="<unk>" , SCREAMING_SNAKE_CASE__ : List[str]="<s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="</s>" , SCREAMING_SNAKE_CASE__ : Tuple="<pad>" , SCREAMING_SNAKE_CASE__ : Any="[SEP]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[MASK]" , SCREAMING_SNAKE_CASE__ : List[Any]="[CLS]" , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None , **SCREAMING_SNAKE_CASE__ : List[Any] , ) -> None: lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else bos_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else eos_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else unk_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else pad_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cls_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else sep_token # Mask token behave like a normal word, i.e. include the space before it lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else mask_token lowerCAmelCase__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = vocab_file lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def a ( self : List[str] ) -> List[str]: return self.sp_model.get_piece_size() def a ( self : List[str] ) -> Dict: lowerCAmelCase__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Optional[int] ) -> Any: lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Any: lowerCAmelCase__ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowerCAmelCase__ = {} lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: return self.sp_model.piece_to_id(SCREAMING_SNAKE_CASE__ ) def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[str]: lowerCAmelCase__ = self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) return token def a ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: lowerCAmelCase__ = [] lowerCAmelCase__ = "" lowerCAmelCase__ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) + token lowerCAmelCase__ = True lowerCAmelCase__ = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) return out_string.strip() def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : bool = True , **SCREAMING_SNAKE_CASE__ : int , ) -> str: lowerCAmelCase__ = kwargs.pop("use_source_tokenizer" , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 lowerCAmelCase__ = [] lowerCAmelCase__ = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = [] sub_texts.append(SCREAMING_SNAKE_CASE__ ) else: current_sub_text.append(SCREAMING_SNAKE_CASE__ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) ) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: lowerCAmelCase__ = re.sub(r" (\[(MASK|SEP)\])" , r"\1" , " ".join(SCREAMING_SNAKE_CASE__ ) ) else: lowerCAmelCase__ = "".join(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: lowerCAmelCase__ = self.clean_up_tokenization(SCREAMING_SNAKE_CASE__ ) return clean_text else: return text def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return lowerCAmelCase__ = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE__ , "wb" ) as fi: lowerCAmelCase__ = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,) def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] lowerCAmelCase__ = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
61
0
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = ["image_processor", "tokenizer"] lowerCamelCase_ = "AutoImageProcessor" lowerCamelCase_ = "AutoTokenizer" def __init__( self :Optional[int] , __A :Optional[Any] , __A :Dict ) -> Dict: """simple docstring""" super().__init__(__A , __A ) SCREAMING_SNAKE_CASE__ = self.image_processor def __call__( self :int , __A :str=None , __A :int=None , __A :Union[str, Any]=None , **__A :str ) -> Optional[Any]: """simple docstring""" if text is None and images is None: raise ValueError("""You have to specify either text or images. Both cannot be none.""" ) if text is not None: SCREAMING_SNAKE_CASE__ = self.tokenizer(__A , return_tensors=__A , **__A ) if images is not None: SCREAMING_SNAKE_CASE__ = self.image_processor(__A , return_tensors=__A , **__A ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__A ) , tensor_type=__A ) def _snake_case ( self :str , *__A :List[str] , **__A :List[str] ) -> List[Any]: """simple docstring""" return self.tokenizer.batch_decode(*__A , **__A ) def _snake_case ( self :List[str] , *__A :Any , **__A :Any ) -> Tuple: """simple docstring""" return self.tokenizer.decode(*__A , **__A ) @property def _snake_case ( self :Dict ) -> List[Any]: """simple docstring""" return ["input_ids", "attention_mask", "pixel_values"]
6
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { 'sayakpaul/vit-msn-base': 'https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json', # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "vit_msn" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple=768 , SCREAMING_SNAKE_CASE__ : Optional[Any]=12 , SCREAMING_SNAKE_CASE__ : List[str]=12 , SCREAMING_SNAKE_CASE__ : Dict=3_072 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.0 , SCREAMING_SNAKE_CASE__ : int=0.0 , SCREAMING_SNAKE_CASE__ : List[str]=0.02 , SCREAMING_SNAKE_CASE__ : List[str]=1e-0_6 , SCREAMING_SNAKE_CASE__ : Dict=224 , SCREAMING_SNAKE_CASE__ : Optional[int]=16 , SCREAMING_SNAKE_CASE__ : Dict=3 , SCREAMING_SNAKE_CASE__ : Dict=True , **SCREAMING_SNAKE_CASE__ : Tuple , ) -> int: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = initializer_range lowerCAmelCase__ = layer_norm_eps lowerCAmelCase__ = image_size lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = qkv_bias
61
0
"""simple docstring""" import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_inverse_sqrt_schedule, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) def _snake_case ( _snake_case : Optional[int] , _snake_case : Optional[Any]=10 ) -> Optional[int]: '''simple docstring''' _A = [] for _ in range(_snake_case ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() return lrs def _snake_case ( _snake_case : Optional[Any] , _snake_case : Union[str, Any]=10 ) -> List[str]: '''simple docstring''' _A = [] for step in range(_snake_case ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() if step == num_steps // 2: with tempfile.TemporaryDirectory() as tmpdirname: _A = os.path.join(_snake_case , 'schedule.bin' ) torch.save(scheduler.state_dict() , _snake_case ) _A = torch.load(_snake_case ) scheduler.load_state_dict(_snake_case ) return lrs @require_torch class lowercase_ ( unittest.TestCase ): '''simple docstring''' def lowerCAmelCase_ ( self : List[Any] , _UpperCAmelCase : List[Any] , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : Tuple ): self.assertEqual(len(_UpperCAmelCase ) , len(_UpperCAmelCase ) ) for a, b in zip(_UpperCAmelCase , _UpperCAmelCase ): self.assertAlmostEqual(_UpperCAmelCase , _UpperCAmelCase , delta=_UpperCAmelCase ) def lowerCAmelCase_ ( self : Any ): _A = torch.tensor([0.1, -0.2, -0.1] , requires_grad=_UpperCAmelCase ) _A = torch.tensor([0.4, 0.2, -0.5] ) _A = nn.MSELoss() # No warmup, constant schedule, no gradient clipping _A = AdamW(params=[w] , lr=2E-1 , weight_decay=0.0 ) for _ in range(100 ): _A = criterion(_UpperCAmelCase , _UpperCAmelCase ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1E-2 ) def lowerCAmelCase_ ( self : int ): _A = torch.tensor([0.1, -0.2, -0.1] , requires_grad=_UpperCAmelCase ) _A = torch.tensor([0.4, 0.2, -0.5] ) _A = nn.MSELoss() # No warmup, constant schedule, no gradient clipping _A = Adafactor( params=[w] , lr=1E-2 , eps=(1E-3_0, 1E-3) , clip_threshold=1.0 , decay_rate=-0.8 , betaa=_UpperCAmelCase , weight_decay=0.0 , relative_step=_UpperCAmelCase , scale_parameter=_UpperCAmelCase , warmup_init=_UpperCAmelCase , ) for _ in range(1_000 ): _A = criterion(_UpperCAmelCase , _UpperCAmelCase ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1E-2 ) @require_torch class lowercase_ ( unittest.TestCase ): '''simple docstring''' UpperCAmelCase : List[str] = nn.Linear(50 , 50 ) if is_torch_available() else None UpperCAmelCase : Tuple = AdamW(m.parameters() , lr=10.0 ) if is_torch_available() else None UpperCAmelCase : Dict = 10 def lowerCAmelCase_ ( self : Any , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : str , _UpperCAmelCase : List[Any] , _UpperCAmelCase : List[Any]=None ): self.assertEqual(len(_UpperCAmelCase ) , len(_UpperCAmelCase ) ) for a, b in zip(_UpperCAmelCase , _UpperCAmelCase ): self.assertAlmostEqual(_UpperCAmelCase , _UpperCAmelCase , delta=_UpperCAmelCase , msg=_UpperCAmelCase ) def lowerCAmelCase_ ( self : List[Any] ): _A = {'num_warmup_steps': 2, 'num_training_steps': 10} # schedulers doct format # function: (sched_args_dict, expected_learning_rates) _A = { get_constant_schedule: ({}, [10.0] * self.num_steps), get_constant_schedule_with_warmup: ( {'num_warmup_steps': 4}, [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0], ), get_linear_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25], ), get_cosine_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38], ), get_cosine_with_hard_restarts_schedule_with_warmup: ( {**common_kwargs, 'num_cycles': 2}, [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46], ), get_polynomial_decay_schedule_with_warmup: ( {**common_kwargs, 'power': 2.0, 'lr_end': 1E-7}, [0.0, 5.0, 10.0, 7.656, 5.625, 3.906, 2.5, 1.406, 0.625, 0.156], ), get_inverse_sqrt_schedule: ( {'num_warmup_steps': 2}, [0.0, 5.0, 10.0, 8.165, 7.071, 6.325, 5.774, 5.345, 5.0, 4.714], ), } for scheduler_func, data in scheds.items(): _A , _A = data _A = scheduler_func(self.optimizer , **_UpperCAmelCase ) self.assertEqual(len([scheduler.get_lr()[0]] ) , 1 ) _A = unwrap_schedule(_UpperCAmelCase , self.num_steps ) self.assertListAlmostEqual( _UpperCAmelCase , _UpperCAmelCase , tol=1E-2 , msg=F'''failed for {scheduler_func} in normal scheduler''' , ) _A = scheduler_func(self.optimizer , **_UpperCAmelCase ) if scheduler_func.__name__ != "get_constant_schedule": LambdaScheduleWrapper.wrap_scheduler(_UpperCAmelCase ) # wrap to test picklability of the schedule _A = unwrap_and_save_reload_schedule(_UpperCAmelCase , self.num_steps ) self.assertListEqual(_UpperCAmelCase , _UpperCAmelCase , msg=F'''failed for {scheduler_func} in save and reload''' ) class lowercase_ : '''simple docstring''' def __init__( self : Union[str, Any] , _UpperCAmelCase : Optional[int] ): _A = fn def __call__( self : Tuple , *_UpperCAmelCase : List[str] , **_UpperCAmelCase : List[str] ): return self.fn(*_UpperCAmelCase , **_UpperCAmelCase ) @classmethod def lowerCAmelCase_ ( self : Union[str, Any] , _UpperCAmelCase : Any ): _A = list(map(self , scheduler.lr_lambdas ) )
7
import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def __init__( self : List[Any] , *SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> None: warnings.warn( "The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use FlavaImageProcessor instead." , SCREAMING_SNAKE_CASE__ , ) super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
61
0
'''simple docstring''' import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class SCREAMING_SNAKE_CASE (unittest.TestCase ): @require_torch def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : List[str] = pipeline( task='zero-shot-audio-classification' , model='hf-internal-testing/tiny-clap-htsat-unfused') __A : str = load_dataset('ashraq/esc50') __A : str = dataset['train']['audio'][-1]['array'] __A : Union[str, Any] = audio_classifier(_UpperCAmelCase , candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner']) self.assertEqual( nested_simplify(_UpperCAmelCase) , [{'score': 0.501, 'label': 'Sound of a dog'}, {'score': 0.499, 'label': 'Sound of vaccum cleaner'}] , ) @unittest.skip('No models are available in TF') def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' pass @slow @require_torch def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : List[str] = pipeline( task='zero-shot-audio-classification' , model='laion/clap-htsat-unfused' , ) # This is an audio of a dog __A : Any = load_dataset('ashraq/esc50') __A : Dict = dataset['train']['audio'][-1]['array'] __A : Tuple = audio_classifier(_UpperCAmelCase , candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner']) self.assertEqual( nested_simplify(_UpperCAmelCase) , [ {'score': 0.999, 'label': 'Sound of a dog'}, {'score': 0.001, 'label': 'Sound of vaccum cleaner'}, ] , ) __A : Tuple = audio_classifier([audio] * 5 , candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner']) self.assertEqual( nested_simplify(_UpperCAmelCase) , [ [ {'score': 0.999, 'label': 'Sound of a dog'}, {'score': 0.001, 'label': 'Sound of vaccum cleaner'}, ], ] * 5 , ) __A : List[str] = audio_classifier( [audio] * 5 , candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner'] , batch_size=5) self.assertEqual( nested_simplify(_UpperCAmelCase) , [ [ {'score': 0.999, 'label': 'Sound of a dog'}, {'score': 0.001, 'label': 'Sound of vaccum cleaner'}, ], ] * 5 , ) @unittest.skip('No models are available in TF') def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' pass
8
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import ( BaseOutput, OptionalDependencyNotAvailable, is_flax_available, is_k_diffusion_available, is_k_diffusion_version, is_onnx_available, is_torch_available, is_transformers_available, is_transformers_version, ) @dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_cycle_diffusion import CycleDiffusionPipeline from .pipeline_stable_diffusion import StableDiffusionPipeline from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from .pipeline_stable_unclip import StableUnCLIPPipeline from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline from .safety_checker import StableDiffusionSafetyChecker from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.25.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline else: from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.26.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionPixaPixZeroPipeline, ) else: from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline try: if not ( is_torch_available() and is_transformers_available() and is_k_diffusion_available() and is_k_diffusion_version('>=', '0.0.12') ): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline try: if not (is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_onnx_objects import * # noqa F403 else: from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline if is_transformers_available() and is_flax_available(): import flax @flax.struct.dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline from .safety_checker_flax import FlaxStableDiffusionSafetyChecker
61
0
from datetime import datetime import matplotlib.pyplot as plt import torch def A ( __UpperCamelCase ) -> Any: for param in module.parameters(): A__ = False def A ( ) -> str: A__ = 'cuda' if torch.cuda.is_available() else 'cpu' if torch.backends.mps.is_available() and torch.backends.mps.is_built(): A__ = '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 A ( __UpperCamelCase ) -> int: A__ = plt.imshow(__UpperCamelCase ) fig.axes.get_xaxis().set_visible(__UpperCamelCase ) fig.axes.get_yaxis().set_visible(__UpperCamelCase ) plt.show() def A ( ) -> Optional[Any]: A__ = datetime.now() A__ = current_time.strftime('%H:%M:%S' ) return timestamp
9
def _A ( lowerCAmelCase_ : int ): """simple docstring""" if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("'float' object cannot be interpreted as an integer" ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("'str' object cannot be interpreted as an integer" ) if num == 0: return "0b0" lowerCAmelCase__ = False if num < 0: lowerCAmelCase__ = True lowerCAmelCase__ = -num lowerCAmelCase__ = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(lowerCAmelCase_ ) for e in binary ) return "0b" + "".join(str(lowerCAmelCase_ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
61
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowerCAmelCase = { "configuration_blenderbot_small": [ "BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlenderbotSmallConfig", "BlenderbotSmallOnnxConfig", ], "tokenization_blenderbot_small": ["BlenderbotSmallTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = ["BlenderbotSmallTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = [ "BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST", "BlenderbotSmallForCausalLM", "BlenderbotSmallForConditionalGeneration", "BlenderbotSmallModel", "BlenderbotSmallPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = [ "TFBlenderbotSmallForConditionalGeneration", "TFBlenderbotSmallModel", "TFBlenderbotSmallPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = [ "FlaxBlenderbotSmallForConditionalGeneration", "FlaxBlenderbotSmallModel", "FlaxBlenderbotSmallPreTrainedModel", ] if TYPE_CHECKING: from .configuration_blenderbot_small import ( BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotSmallConfig, BlenderbotSmallOnnxConfig, ) from .tokenization_blenderbot_small import BlenderbotSmallTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_small_fast import BlenderbotSmallTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot_small import ( BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotSmallForCausalLM, BlenderbotSmallForConditionalGeneration, BlenderbotSmallModel, BlenderbotSmallPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot_small import ( TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel, TFBlenderbotSmallPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot_small import ( FlaxBlenderbotSmallForConditionalGeneration, FlaxBlenderbotSmallModel, FlaxBlenderbotSmallPreTrainedModel, ) else: import sys _lowerCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
10
from __future__ import annotations UpperCamelCase = '#' class __lowerCamelCase : """simple docstring""" def __init__( self : Dict ) -> None: lowerCAmelCase__ = {} def a ( self : Any , SCREAMING_SNAKE_CASE__ : str ) -> None: lowerCAmelCase__ = self._trie for char in text: if char not in trie: lowerCAmelCase__ = {} lowerCAmelCase__ = trie[char] lowerCAmelCase__ = True def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : str ) -> tuple | list: lowerCAmelCase__ = self._trie for char in prefix: if char in trie: lowerCAmelCase__ = trie[char] else: return [] return self._elements(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : dict ) -> tuple: lowerCAmelCase__ = [] for c, v in d.items(): lowerCAmelCase__ = [" "] if c == END else [(c + s) for s in self._elements(SCREAMING_SNAKE_CASE__ )] result.extend(SCREAMING_SNAKE_CASE__ ) return tuple(SCREAMING_SNAKE_CASE__ ) UpperCamelCase = Trie() UpperCamelCase = ('depart', 'detergent', 'daring', 'dog', 'deer', 'deal') for word in words: trie.insert_word(word) def _A ( lowerCAmelCase_ : str ): """simple docstring""" lowerCAmelCase__ = trie.find_word(lowerCAmelCase_ ) return tuple(string + word for word in suffixes ) def _A ( ): """simple docstring""" print(autocomplete_using_trie("de" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
61
0
'''simple docstring''' def lowerCAmelCase (__A = 600_851_475_143): """simple docstring""" try: _a = int(__A) except (TypeError, ValueError): raise TypeError('''Parameter n must be int or castable to int.''') if n <= 0: raise ValueError('''Parameter n must be greater than or equal to one.''') _a = 2 _a = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 _a = i while n % i == 0: _a = n // i i += 1 return int(__A) if __name__ == "__main__": print(F"""{solution() = }""")
11
import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, TimesformerForVideoClassification, TimesformerModel, ) from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class __lowerCamelCase : """simple docstring""" def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple=13 , SCREAMING_SNAKE_CASE__ : Optional[Any]=10 , SCREAMING_SNAKE_CASE__ : Optional[int]=3 , SCREAMING_SNAKE_CASE__ : List[str]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=2 , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : Optional[int]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : List[Any]=37 , SCREAMING_SNAKE_CASE__ : int="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Any=10 , SCREAMING_SNAKE_CASE__ : int=0.02 , SCREAMING_SNAKE_CASE__ : Tuple="divided_space_time" , SCREAMING_SNAKE_CASE__ : Optional[int]=None , ) -> List[str]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = image_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_frames lowerCAmelCase__ = is_training lowerCAmelCase__ = use_labels lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = attention_type lowerCAmelCase__ = initializer_range lowerCAmelCase__ = scope lowerCAmelCase__ = num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token lowerCAmelCase__ = (image_size // patch_size) ** 2 lowerCAmelCase__ = (num_frames) * self.num_patches_per_frame + 1 def a ( self : int ) -> Tuple: lowerCAmelCase__ = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase__ = None if self.use_labels: lowerCAmelCase__ = ids_tensor([self.batch_size] , self.num_labels ) lowerCAmelCase__ = self.get_config() return config, pixel_values, labels def a ( self : List[Any] ) -> Any: lowerCAmelCase__ = TimesformerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , initializer_range=self.initializer_range , attention_type=self.attention_type , ) lowerCAmelCase__ = self.num_labels return config def a ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: lowerCAmelCase__ = TimesformerModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple ) -> Tuple: lowerCAmelCase__ = TimesformerForVideoClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) # verify the logits shape lowerCAmelCase__ = torch.Size((self.batch_size, self.num_labels) ) self.parent.assertEqual(result.logits.shape , SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> Dict: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else () snake_case__ = ( {"feature-extraction": TimesformerModel, "video-classification": TimesformerForVideoClassification} if is_torch_available() else {} ) snake_case__ = False snake_case__ = False snake_case__ = False snake_case__ = False def a ( self : List[str] ) -> List[Any]: lowerCAmelCase__ = TimesformerModelTester(self ) lowerCAmelCase__ = ConfigTester( self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ , hidden_size=37 ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple=False ) -> str: lowerCAmelCase__ = copy.deepcopy(SCREAMING_SNAKE_CASE__ ) if return_labels: if model_class in get_values(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) return inputs_dict def a ( self : Optional[Any] ) -> List[str]: self.config_tester.run_common_tests() @unittest.skip(reason="TimeSformer does not use inputs_embeds" ) def a ( self : Union[str, Any] ) -> Tuple: pass def a ( self : Dict ) -> List[str]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowerCAmelCase__ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__ , nn.Linear ) ) def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase__ = [*signature.parameters.keys()] lowerCAmelCase__ = ["pixel_values"] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] ) -> Tuple: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*SCREAMING_SNAKE_CASE__ ) @slow def a ( self : str ) -> Tuple: for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase__ = TimesformerModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Dict: if not self.has_attentions: pass else: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ = True for model_class in self.all_model_classes: lowerCAmelCase__ = self.model_tester.seq_length lowerCAmelCase__ = self.model_tester.num_frames lowerCAmelCase__ = True lowerCAmelCase__ = False lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) lowerCAmelCase__ = len(SCREAMING_SNAKE_CASE__ ) # Check attention is always last and order is fine lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(out_len + 1 , len(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) def a ( self : List[str] ) -> Any: def check_hidden_states_output(SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] ): lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.hidden_states lowerCAmelCase__ = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _A ( ): """simple docstring""" lowerCAmelCase__ = hf_hub_download( repo_id="hf-internal-testing/spaghetti-video" , filename="eating_spaghetti.npy" , repo_type="dataset" ) lowerCAmelCase__ = np.load(lowerCAmelCase_ ) return list(lowerCAmelCase_ ) @require_torch @require_vision class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @cached_property def a ( self : Optional[Any] ) -> Union[str, Any]: # logits were tested with a different mean and std, so we use the same here return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) if is_vision_available() else None ) @slow def a ( self : Optional[Any] ) -> str: lowerCAmelCase__ = TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400" ).to( SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.default_image_processor lowerCAmelCase__ = prepare_video() lowerCAmelCase__ = image_processor(video[:8] , return_tensors="pt" ).to(SCREAMING_SNAKE_CASE__ ) # forward pass with torch.no_grad(): lowerCAmelCase__ = model(**SCREAMING_SNAKE_CASE__ ) # verify the logits lowerCAmelCase__ = torch.Size((1, 400) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = torch.tensor([-0.3_016, -0.7_713, -0.4_205] ).to(SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
0
from typing import TYPE_CHECKING from ...utils import _LazyModule lowerCamelCase__ : int = {"""processing_wav2vec2_with_lm""": ["""Wav2Vec2ProcessorWithLM"""]} if TYPE_CHECKING: from .processing_wavaveca_with_lm import WavaVecaProcessorWithLM else: import sys lowerCamelCase__ : List[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
12
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _A ( ): """simple docstring""" lowerCAmelCase__ = ArgumentParser( description=( "PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes" ) ) # Optional arguments for the launch helper parser.add_argument("--num_cores" , type=lowerCAmelCase_ , default=1 , help="Number of TPU cores to use (1 or 8)." ) # positional parser.add_argument( "training_script" , type=lowerCAmelCase_ , help=( "The full path to the single TPU training " "program/script to be launched in parallel, " "followed by all the arguments for the " "training script" ) , ) # rest from the training program parser.add_argument("training_script_args" , nargs=lowerCAmelCase_ ) return parser.parse_args() def _A ( ): """simple docstring""" lowerCAmelCase__ = parse_args() # Import training_script as a module. lowerCAmelCase__ = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) lowerCAmelCase__ = script_fpath.stem lowerCAmelCase__ = importlib.import_module(lowerCAmelCase_ ) # Patch sys.argv lowerCAmelCase__ = [args.training_script] + args.training_script_args + ["--tpu_num_cores", str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
61
0
'''simple docstring''' from __future__ import annotations A__ : int = 10 def UpperCAmelCase__ ( UpperCAmelCase_ : list[int] ) -> list[int]: __lowerCamelCase : List[Any] = 1 __lowerCamelCase : Any = max(UpperCAmelCase_ ) while placement <= max_digit: # declare and initialize empty buckets __lowerCamelCase : list[list] = [[] for _ in range(UpperCAmelCase_ )] # split list_of_ints between the buckets for i in list_of_ints: __lowerCamelCase : List[Any] = int((i / placement) % RADIX ) buckets[tmp].append(UpperCAmelCase_ ) # put each buckets' contents into list_of_ints __lowerCamelCase : Tuple = 0 for b in range(UpperCAmelCase_ ): for i in buckets[b]: __lowerCamelCase : List[Any] = i a += 1 # move to next placement *= RADIX return list_of_ints if __name__ == "__main__": import doctest doctest.testmod()
13
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool UpperCamelCase = { 'Acehnese Arabic': 'ace_Arab', 'Acehnese Latin': 'ace_Latn', 'Mesopotamian Arabic': 'acm_Arab', 'Ta\'izzi-Adeni Arabic': 'acq_Arab', 'Tunisian Arabic': 'aeb_Arab', 'Afrikaans': 'afr_Latn', 'South Levantine Arabic': 'ajp_Arab', 'Akan': 'aka_Latn', 'Amharic': 'amh_Ethi', 'North Levantine Arabic': 'apc_Arab', 'Modern Standard Arabic': 'arb_Arab', 'Modern Standard Arabic Romanized': 'arb_Latn', 'Najdi Arabic': 'ars_Arab', 'Moroccan Arabic': 'ary_Arab', 'Egyptian Arabic': 'arz_Arab', 'Assamese': 'asm_Beng', 'Asturian': 'ast_Latn', 'Awadhi': 'awa_Deva', 'Central Aymara': 'ayr_Latn', 'South Azerbaijani': 'azb_Arab', 'North Azerbaijani': 'azj_Latn', 'Bashkir': 'bak_Cyrl', 'Bambara': 'bam_Latn', 'Balinese': 'ban_Latn', 'Belarusian': 'bel_Cyrl', 'Bemba': 'bem_Latn', 'Bengali': 'ben_Beng', 'Bhojpuri': 'bho_Deva', 'Banjar Arabic': 'bjn_Arab', 'Banjar Latin': 'bjn_Latn', 'Standard Tibetan': 'bod_Tibt', 'Bosnian': 'bos_Latn', 'Buginese': 'bug_Latn', 'Bulgarian': 'bul_Cyrl', 'Catalan': 'cat_Latn', 'Cebuano': 'ceb_Latn', 'Czech': 'ces_Latn', 'Chokwe': 'cjk_Latn', 'Central Kurdish': 'ckb_Arab', 'Crimean Tatar': 'crh_Latn', 'Welsh': 'cym_Latn', 'Danish': 'dan_Latn', 'German': 'deu_Latn', 'Southwestern Dinka': 'dik_Latn', 'Dyula': 'dyu_Latn', 'Dzongkha': 'dzo_Tibt', 'Greek': 'ell_Grek', 'English': 'eng_Latn', 'Esperanto': 'epo_Latn', 'Estonian': 'est_Latn', 'Basque': 'eus_Latn', 'Ewe': 'ewe_Latn', 'Faroese': 'fao_Latn', 'Fijian': 'fij_Latn', 'Finnish': 'fin_Latn', 'Fon': 'fon_Latn', 'French': 'fra_Latn', 'Friulian': 'fur_Latn', 'Nigerian Fulfulde': 'fuv_Latn', 'Scottish Gaelic': 'gla_Latn', 'Irish': 'gle_Latn', 'Galician': 'glg_Latn', 'Guarani': 'grn_Latn', 'Gujarati': 'guj_Gujr', 'Haitian Creole': 'hat_Latn', 'Hausa': 'hau_Latn', 'Hebrew': 'heb_Hebr', 'Hindi': 'hin_Deva', 'Chhattisgarhi': 'hne_Deva', 'Croatian': 'hrv_Latn', 'Hungarian': 'hun_Latn', 'Armenian': 'hye_Armn', 'Igbo': 'ibo_Latn', 'Ilocano': 'ilo_Latn', 'Indonesian': 'ind_Latn', 'Icelandic': 'isl_Latn', 'Italian': 'ita_Latn', 'Javanese': 'jav_Latn', 'Japanese': 'jpn_Jpan', 'Kabyle': 'kab_Latn', 'Jingpho': 'kac_Latn', 'Kamba': 'kam_Latn', 'Kannada': 'kan_Knda', 'Kashmiri Arabic': 'kas_Arab', 'Kashmiri Devanagari': 'kas_Deva', 'Georgian': 'kat_Geor', 'Central Kanuri Arabic': 'knc_Arab', 'Central Kanuri Latin': 'knc_Latn', 'Kazakh': 'kaz_Cyrl', 'Kabiyè': 'kbp_Latn', 'Kabuverdianu': 'kea_Latn', 'Khmer': 'khm_Khmr', 'Kikuyu': 'kik_Latn', 'Kinyarwanda': 'kin_Latn', 'Kyrgyz': 'kir_Cyrl', 'Kimbundu': 'kmb_Latn', 'Northern Kurdish': 'kmr_Latn', 'Kikongo': 'kon_Latn', 'Korean': 'kor_Hang', 'Lao': 'lao_Laoo', 'Ligurian': 'lij_Latn', 'Limburgish': 'lim_Latn', 'Lingala': 'lin_Latn', 'Lithuanian': 'lit_Latn', 'Lombard': 'lmo_Latn', 'Latgalian': 'ltg_Latn', 'Luxembourgish': 'ltz_Latn', 'Luba-Kasai': 'lua_Latn', 'Ganda': 'lug_Latn', 'Luo': 'luo_Latn', 'Mizo': 'lus_Latn', 'Standard Latvian': 'lvs_Latn', 'Magahi': 'mag_Deva', 'Maithili': 'mai_Deva', 'Malayalam': 'mal_Mlym', 'Marathi': 'mar_Deva', 'Minangkabau Arabic ': 'min_Arab', 'Minangkabau Latin': 'min_Latn', 'Macedonian': 'mkd_Cyrl', 'Plateau Malagasy': 'plt_Latn', 'Maltese': 'mlt_Latn', 'Meitei Bengali': 'mni_Beng', 'Halh Mongolian': 'khk_Cyrl', 'Mossi': 'mos_Latn', 'Maori': 'mri_Latn', 'Burmese': 'mya_Mymr', 'Dutch': 'nld_Latn', 'Norwegian Nynorsk': 'nno_Latn', 'Norwegian Bokmål': 'nob_Latn', 'Nepali': 'npi_Deva', 'Northern Sotho': 'nso_Latn', 'Nuer': 'nus_Latn', 'Nyanja': 'nya_Latn', 'Occitan': 'oci_Latn', 'West Central Oromo': 'gaz_Latn', 'Odia': 'ory_Orya', 'Pangasinan': 'pag_Latn', 'Eastern Panjabi': 'pan_Guru', 'Papiamento': 'pap_Latn', 'Western Persian': 'pes_Arab', 'Polish': 'pol_Latn', 'Portuguese': 'por_Latn', 'Dari': 'prs_Arab', 'Southern Pashto': 'pbt_Arab', 'Ayacucho Quechua': 'quy_Latn', 'Romanian': 'ron_Latn', 'Rundi': 'run_Latn', 'Russian': 'rus_Cyrl', 'Sango': 'sag_Latn', 'Sanskrit': 'san_Deva', 'Santali': 'sat_Olck', 'Sicilian': 'scn_Latn', 'Shan': 'shn_Mymr', 'Sinhala': 'sin_Sinh', 'Slovak': 'slk_Latn', 'Slovenian': 'slv_Latn', 'Samoan': 'smo_Latn', 'Shona': 'sna_Latn', 'Sindhi': 'snd_Arab', 'Somali': 'som_Latn', 'Southern Sotho': 'sot_Latn', 'Spanish': 'spa_Latn', 'Tosk Albanian': 'als_Latn', 'Sardinian': 'srd_Latn', 'Serbian': 'srp_Cyrl', 'Swati': 'ssw_Latn', 'Sundanese': 'sun_Latn', 'Swedish': 'swe_Latn', 'Swahili': 'swh_Latn', 'Silesian': 'szl_Latn', 'Tamil': 'tam_Taml', 'Tatar': 'tat_Cyrl', 'Telugu': 'tel_Telu', 'Tajik': 'tgk_Cyrl', 'Tagalog': 'tgl_Latn', 'Thai': 'tha_Thai', 'Tigrinya': 'tir_Ethi', 'Tamasheq Latin': 'taq_Latn', 'Tamasheq Tifinagh': 'taq_Tfng', 'Tok Pisin': 'tpi_Latn', 'Tswana': 'tsn_Latn', 'Tsonga': 'tso_Latn', 'Turkmen': 'tuk_Latn', 'Tumbuka': 'tum_Latn', 'Turkish': 'tur_Latn', 'Twi': 'twi_Latn', 'Central Atlas Tamazight': 'tzm_Tfng', 'Uyghur': 'uig_Arab', 'Ukrainian': 'ukr_Cyrl', 'Umbundu': 'umb_Latn', 'Urdu': 'urd_Arab', 'Northern Uzbek': 'uzn_Latn', 'Venetian': 'vec_Latn', 'Vietnamese': 'vie_Latn', 'Waray': 'war_Latn', 'Wolof': 'wol_Latn', 'Xhosa': 'xho_Latn', 'Eastern Yiddish': 'ydd_Hebr', 'Yoruba': 'yor_Latn', 'Yue Chinese': 'yue_Hant', 'Chinese Simplified': 'zho_Hans', 'Chinese Traditional': 'zho_Hant', 'Standard Malay': 'zsm_Latn', 'Zulu': 'zul_Latn', } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "facebook/nllb-200-distilled-600M" snake_case__ = ( "This is a tool that translates text from a language to another. It takes three inputs: `text`, which should " "be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, " "which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in " "plain English, such as 'Romanian', or 'Albanian'. It returns the text translated in `tgt_lang`." ) snake_case__ = "translator" snake_case__ = AutoTokenizer snake_case__ = AutoModelForSeqaSeqLM snake_case__ = LANGUAGE_CODES snake_case__ = ["text", "text", "text"] snake_case__ = ["text"] def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: if src_lang not in self.lang_to_code: raise ValueError(f'{src_lang} is not a supported language.' ) if tgt_lang not in self.lang_to_code: raise ValueError(f'{tgt_lang} is not a supported language.' ) lowerCAmelCase__ = self.lang_to_code[src_lang] lowerCAmelCase__ = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( SCREAMING_SNAKE_CASE__ , return_tensors="pt" , src_lang=SCREAMING_SNAKE_CASE__ , tgt_lang=SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: return self.model.generate(**SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[str]: return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=SCREAMING_SNAKE_CASE__ )
61
0
import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def __UpperCAmelCase ( __a : Tuple ,__a : Dict ,__a : List[str] ,__a : Optional[Any] ,__a : Tuple ) -> Dict: """simple docstring""" with open(__a ) as metadata_file: _a : Optional[Any] = json.load(__a ) _a : List[Any] = LukeConfig(use_entity_aware_attention=__a ,**metadata['''model_config'''] ) # Load in the weights from the checkpoint_path _a : Optional[Any] = torch.load(__a ,map_location='''cpu''' )['''module'''] # Load the entity vocab file _a : Any = load_original_entity_vocab(__a ) # add an entry for [MASK2] _a : Union[str, Any] = max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 _a : Dict = XLMRobertaTokenizer.from_pretrained(metadata['''model_config''']['''bert_model_name'''] ) # Add special tokens to the token vocabulary for downstream tasks _a : Optional[int] = AddedToken('''<ent>''' ,lstrip=__a ,rstrip=__a ) _a : Tuple = AddedToken('''<ent2>''' ,lstrip=__a ,rstrip=__a ) tokenizer.add_special_tokens({'''additional_special_tokens''': [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(F"""Saving tokenizer to {pytorch_dump_folder_path}""" ) tokenizer.save_pretrained(__a ) with open(os.path.join(__a ,'''tokenizer_config.json''' ) ,'''r''' ) as f: _a : List[str] = json.load(__a ) _a : Tuple = '''MLukeTokenizer''' with open(os.path.join(__a ,'''tokenizer_config.json''' ) ,'''w''' ) as f: json.dump(__a ,__a ) with open(os.path.join(__a ,MLukeTokenizer.vocab_files_names['''entity_vocab_file'''] ) ,'''w''' ) as f: json.dump(__a ,__a ) _a : Optional[int] = MLukeTokenizer.from_pretrained(__a ) # Initialize the embeddings of the special tokens _a : str = tokenizer.convert_tokens_to_ids(['''@'''] )[0] _a : Tuple = tokenizer.convert_tokens_to_ids(['''#'''] )[0] _a : Any = state_dict['''embeddings.word_embeddings.weight'''] _a : Optional[int] = word_emb[ent_init_index].unsqueeze(0 ) _a : Any = word_emb[enta_init_index].unsqueeze(0 ) _a : Union[str, Any] = torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: _a : Tuple = state_dict[bias_name] _a : Optional[Any] = decoder_bias[ent_init_index].unsqueeze(0 ) _a : Optional[int] = decoder_bias[enta_init_index].unsqueeze(0 ) _a : Dict = torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: _a : Tuple = F"""encoder.layer.{layer_index}.attention.self.""" _a : List[Any] = state_dict[prefix + matrix_name] _a : Dict = state_dict[prefix + matrix_name] _a : List[Any] = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks _a : Union[str, Any] = state_dict['''entity_embeddings.entity_embeddings.weight'''] _a : Optional[int] = entity_emb[entity_vocab['''[MASK]''']].unsqueeze(0 ) _a : Any = torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' _a : int = state_dict['''entity_predictions.bias'''] _a : int = entity_prediction_bias[entity_vocab['''[MASK]''']].unsqueeze(0 ) _a : Optional[Any] = torch.cat([entity_prediction_bias, entity_mask_bias] ) _a : Optional[int] = LukeForMaskedLM(config=__a ).eval() state_dict.pop('''entity_predictions.decoder.weight''' ) state_dict.pop('''lm_head.decoder.weight''' ) state_dict.pop('''lm_head.decoder.bias''' ) _a : int = OrderedDict() for key, value in state_dict.items(): if not (key.startswith('''lm_head''' ) or key.startswith('''entity_predictions''' )): _a : Optional[int] = state_dict[key] else: _a : Tuple = state_dict[key] _a , _a : int = model.load_state_dict(__a ,strict=__a ) if set(__a ) != {"luke.embeddings.position_ids"}: raise ValueError(F"""Unexpected unexpected_keys: {unexpected_keys}""" ) if set(__a ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(F"""Unexpected missing_keys: {missing_keys}""" ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs _a : Optional[int] = MLukeTokenizer.from_pretrained(__a ,task='''entity_classification''' ) _a : int = '''ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan).''' _a : List[Any] = (0, 9) _a : Tuple = tokenizer(__a ,entity_spans=[span] ,return_tensors='''pt''' ) _a : int = model(**__a ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base _a : List[str] = torch.Size((1, 33, 768) ) _a : Union[str, Any] = torch.tensor([[0.08_92, 0.05_96, -0.28_19], [0.01_34, 0.11_99, 0.05_73], [-0.01_69, 0.09_27, 0.06_44]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( F"""Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}""" ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3] ,__a ,atol=1E-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base _a : str = torch.Size((1, 1, 768) ) _a : List[Any] = torch.tensor([[-0.14_82, 0.06_09, 0.03_22]] ) if not (outputs.entity_last_hidden_state.shape == expected_shape): raise ValueError( F"""Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is""" F""" {expected_shape}""" ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3] ,__a ,atol=1E-4 ): raise ValueError # Verify masked word/entity prediction _a : Optional[int] = MLukeTokenizer.from_pretrained(__a ) _a : Dict = '''Tokyo is the capital of <mask>.''' _a : List[str] = (24, 30) _a : Optional[int] = tokenizer(__a ,entity_spans=[span] ,return_tensors='''pt''' ) _a : Optional[Any] = model(**__a ) _a : Any = encoding['''input_ids'''][0].tolist() _a : Optional[Any] = input_ids.index(tokenizer.convert_tokens_to_ids('''<mask>''' ) ) _a : Any = outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(__a ) _a : Any = outputs.entity_logits[0][0].argmax().item() _a : Optional[Any] = [ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith('''en:''' )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print('''Saving PyTorch model to {}'''.format(__a ) ) model.save_pretrained(__a ) def __UpperCAmelCase ( __a : List[Any] ) -> int: """simple docstring""" _a : Union[str, Any] = ['''[MASK]''', '''[PAD]''', '''[UNK]'''] _a : int = [json.loads(__a ) for line in open(__a )] _a : List[Any] = {} for entry in data: _a : int = entry['''id'''] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: _a : List[Any] = entity_id break _a : Dict = F"""{language}:{entity_name}""" _a : int = entity_id return new_mapping if __name__ == "__main__": a__ = argparse.ArgumentParser() # Required parameters parser.add_argument('''--checkpoint_path''', type=str, help='''Path to a pytorch_model.bin file.''') parser.add_argument( '''--metadata_path''', default=None, type=str, help='''Path to a metadata.json file, defining the configuration.''' ) parser.add_argument( '''--entity_vocab_path''', default=None, type=str, help='''Path to an entity_vocab.tsv file, containing the entity vocabulary.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to where to dump the output PyTorch model.''' ) parser.add_argument( '''--model_size''', default='''base''', type=str, choices=['''base''', '''large'''], help='''Size of the model to be converted.''' ) a__ = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
14
import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = VideoToVideoSDPipeline snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"video"} ) - {"image", "width", "height"} snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"video"} ) - {"image"} snake_case__ = PipelineTesterMixin.required_optional_params - {"latents"} snake_case__ = False # No `output_type`. snake_case__ = frozenset( [ "num_inference_steps", "generator", "latents", "return_dict", "callback", "callback_steps", ] ) def a ( self : int ) -> Optional[int]: torch.manual_seed(0 ) lowerCAmelCase__ = 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 , ) lowerCAmelCase__ = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=SCREAMING_SNAKE_CASE__ , set_alpha_to_one=SCREAMING_SNAKE_CASE__ , ) torch.manual_seed(0 ) lowerCAmelCase__ = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) lowerCAmelCase__ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="gelu" , projection_dim=512 , ) lowerCAmelCase__ = CLIPTextModel(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) lowerCAmelCase__ = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, } return components def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Dict=0 ) -> Tuple: # 3 frames lowerCAmelCase__ = floats_tensor((1, 3, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) if str(SCREAMING_SNAKE_CASE__ ).startswith("mps" ): lowerCAmelCase__ = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: lowerCAmelCase__ = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = { "prompt": "A painting of a squirrel eating a burger", "video": video, "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "pt", } return inputs def a ( self : Union[str, Any] ) -> str: lowerCAmelCase__ = "cpu" # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ = self.get_dummy_components() lowerCAmelCase__ = VideoToVideoSDPipeline(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = "np" lowerCAmelCase__ = sd_pipe(**SCREAMING_SNAKE_CASE__ ).frames lowerCAmelCase__ = frames[0][-3:, -3:, -1] assert frames[0].shape == (32, 32, 3) lowerCAmelCase__ = np.array([106, 117, 113, 174, 137, 112, 148, 151, 131] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def a ( self : List[Any] ) -> str: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE__ , expected_max_diff=5e-3 ) @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a ( self : List[Any] ) -> str: pass @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a ( self : int ) -> Optional[Any]: pass @unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline." ) def a ( self : List[str] ) -> Optional[int]: pass def a ( self : Optional[Any] ) -> Tuple: return super().test_progress_bar() @slow @skip_mps class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : str ) -> int: lowerCAmelCase__ = VideoToVideoSDPipeline.from_pretrained("cerspense/zeroscope_v2_XL" , torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames lowerCAmelCase__ = torch.Generator(device="cpu" ).manual_seed(0 ) lowerCAmelCase__ = torch.randn((1, 10, 3, 1_024, 576) , generator=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = video.to("cuda" ) lowerCAmelCase__ = "Spiderman is surfing" lowerCAmelCase__ = pipe(SCREAMING_SNAKE_CASE__ , video=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=3 , output_type="pt" ).frames lowerCAmelCase__ = np.array([-1.0_458_984, -1.1_279_297, -0.9_663_086, -0.91_503_906, -0.75_097_656] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1e-2
61
0
from ...configuration_utils import PretrainedConfig from ...utils import logging A : Union[str, Any] = logging.get_logger(__name__) A : str = { 'edbeeching/decision-transformer-gym-hopper-medium': ( 'https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json' ), # See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer } class A ( UpperCAmelCase__ ): '''simple docstring''' A__ = '''decision_transformer''' A__ = ['''past_key_values'''] A__ = { '''max_position_embeddings''': '''n_positions''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__(self : Any , _UpperCAmelCase : Optional[int]=17 , _UpperCAmelCase : int=4 , _UpperCAmelCase : str=128 , _UpperCAmelCase : Union[str, Any]=4096 , _UpperCAmelCase : int=True , _UpperCAmelCase : Optional[int]=1 , _UpperCAmelCase : Union[str, Any]=1024 , _UpperCAmelCase : Optional[int]=3 , _UpperCAmelCase : Optional[int]=1 , _UpperCAmelCase : List[Any]=None , _UpperCAmelCase : str="relu" , _UpperCAmelCase : str=0.1 , _UpperCAmelCase : str=0.1 , _UpperCAmelCase : Union[str, Any]=0.1 , _UpperCAmelCase : Union[str, Any]=1E-5 , _UpperCAmelCase : Optional[Any]=0.02 , _UpperCAmelCase : Dict=True , _UpperCAmelCase : Optional[Any]=True , _UpperCAmelCase : int=5_0256 , _UpperCAmelCase : str=5_0256 , _UpperCAmelCase : Optional[int]=False , _UpperCAmelCase : Any=False , **_UpperCAmelCase : Optional[int] , ) -> Any: """simple docstring""" lowercase__ = state_dim lowercase__ = act_dim lowercase__ = hidden_size lowercase__ = max_ep_len lowercase__ = action_tanh lowercase__ = vocab_size lowercase__ = n_positions lowercase__ = n_layer lowercase__ = n_head lowercase__ = n_inner lowercase__ = activation_function lowercase__ = resid_pdrop lowercase__ = embd_pdrop lowercase__ = attn_pdrop lowercase__ = layer_norm_epsilon lowercase__ = initializer_range lowercase__ = scale_attn_weights lowercase__ = use_cache lowercase__ = scale_attn_by_inverse_layer_idx lowercase__ = reorder_and_upcast_attn lowercase__ = bos_token_id lowercase__ = eos_token_id super().__init__(bos_token_id=_UpperCAmelCase , eos_token_id=_UpperCAmelCase , **_UpperCAmelCase )
15
from __future__ import annotations def _A ( lowerCAmelCase_ : list , lowerCAmelCase_ : int , lowerCAmelCase_ : int , lowerCAmelCase_ : int ): """simple docstring""" lowerCAmelCase__ = [] lowerCAmelCase__ , lowerCAmelCase__ = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0 ) ) lowerCAmelCase__ = result + left + right return input_list def _A ( lowerCAmelCase_ : list ): """simple docstring""" if len(lowerCAmelCase_ ) <= 1: return input_list lowerCAmelCase__ = list(lowerCAmelCase_ ) # iteration for two-way merging lowerCAmelCase__ = 2 while p <= len(lowerCAmelCase_ ): # getting low, high and middle value for merge-sort of single list for i in range(0 , len(lowerCAmelCase_ ) , lowerCAmelCase_ ): lowerCAmelCase__ = i lowerCAmelCase__ = i + p - 1 lowerCAmelCase__ = (low + high + 1) // 2 lowerCAmelCase__ = merge(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # final merge of last two parts if p * 2 >= len(lowerCAmelCase_ ): lowerCAmelCase__ = i lowerCAmelCase__ = merge(lowerCAmelCase_ , 0 , lowerCAmelCase_ , len(lowerCAmelCase_ ) - 1 ) break p *= 2 return input_list if __name__ == "__main__": UpperCamelCase = input('Enter numbers separated by a comma:\n').strip() if user_input == "": UpperCamelCase = [] else: UpperCamelCase = [int(item.strip()) for item in user_input.split(',')] print(iter_merge_sort(unsorted))
61
0
import copy import inspect import unittest from transformers import PretrainedConfig, SwiftFormerConfig from transformers.testing_utils import ( require_torch, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwiftFormerForImageClassification, SwiftFormerModel from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : List[str] , __lowerCamelCase : int , __lowerCamelCase : int=13 , __lowerCamelCase : Optional[int]=3 , __lowerCamelCase : str=True , __lowerCamelCase : Any=True , __lowerCamelCase : Optional[Any]=0.1 , __lowerCamelCase : Any=0.1 , __lowerCamelCase : Optional[int]=224 , __lowerCamelCase : Any=1000 , __lowerCamelCase : Optional[Any]=[3, 3, 6, 4] , __lowerCamelCase : List[Any]=[48, 56, 112, 220] , ): SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = use_labels SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = num_labels SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = layer_depths SCREAMING_SNAKE_CASE = embed_dims def _snake_case ( self : Optional[Any] ): SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE = None if self.use_labels: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE = self.get_config() return config, pixel_values, labels def _snake_case ( self : Dict ): return SwiftFormerConfig( depths=self.layer_depths , embed_dims=self.embed_dims , mlp_ratio=4 , downsamples=[True, True, True, True] , hidden_act="gelu" , num_labels=self.num_labels , down_patch_size=3 , down_stride=2 , down_pad=1 , drop_rate=0.0 , drop_path_rate=0.0 , use_layer_scale=__lowerCamelCase , layer_scale_init_value=1e-5 , ) def _snake_case ( self : List[str] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Tuple , __lowerCamelCase : List[Any] ): SCREAMING_SNAKE_CASE = SwiftFormerModel(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dims[-1], 7, 7) ) def _snake_case ( self : Dict , __lowerCamelCase : int , __lowerCamelCase : Any , __lowerCamelCase : Optional[int] ): SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = SwiftFormerForImageClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE = model(__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) SCREAMING_SNAKE_CASE = SwiftFormerForImageClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self : int ): ((SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE)) = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else () lowerCamelCase__ = ( {"feature-extraction": SwiftFormerModel, "image-classification": SwiftFormerForImageClassification} if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = SwiftFormerModelTester(self ) SCREAMING_SNAKE_CASE = ConfigTester( self , config_class=__lowerCamelCase , has_text_modality=__lowerCamelCase , hidden_size=37 , num_attention_heads=12 , num_hidden_layers=12 , ) def _snake_case ( self : List[Any] ): self.config_tester.run_common_tests() @unittest.skip(reason="SwiftFormer does not use inputs_embeds" ) def _snake_case ( self : Optional[int] ): pass def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__lowerCamelCase , nn.Linear ) ) def _snake_case ( self : List[Any] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE = ["pixel_values"] self.assertListEqual(arg_names[:1] , __lowerCamelCase ) def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase ) @slow def _snake_case ( self : Tuple ): for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = SwiftFormerModel.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) @unittest.skip(reason="SwiftFormer does not output attentions" ) def _snake_case ( self : Union[str, Any] ): pass def _snake_case ( self : Optional[Any] ): def check_hidden_states_output(__lowerCamelCase : Optional[int] , __lowerCamelCase : str , __lowerCamelCase : Tuple ): SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) SCREAMING_SNAKE_CASE = outputs.hidden_states SCREAMING_SNAKE_CASE = 8 self.assertEqual(len(__lowerCamelCase ) , __lowerCamelCase ) # TODO # SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width) # with the width and height being successively divided by 2, after every 2 blocks for i in range(len(__lowerCamelCase ) ): self.assertEqual( hidden_states[i].shape , torch.Size( [ self.model_tester.batch_size, self.model_tester.embed_dims[i // 2], (self.model_tester.image_size // 4) // 2 ** (i // 2), (self.model_tester.image_size // 4) // 2 ** (i // 2), ] ) , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) def _snake_case ( self : List[Any] ): def _config_zero_init(__lowerCamelCase : List[Any] ): SCREAMING_SNAKE_CASE = copy.deepcopy(__lowerCamelCase ) for key in configs_no_init.__dict__.keys(): if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key: setattr(__lowerCamelCase , __lowerCamelCase , 1e-10 ) if isinstance(getattr(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) , __lowerCamelCase ): SCREAMING_SNAKE_CASE = _config_zero_init(getattr(__lowerCamelCase , __lowerCamelCase ) ) setattr(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) return configs_no_init SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = _config_zero_init(__lowerCamelCase ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = model_class(config=__lowerCamelCase ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1e9) / 1e9).round().item() , [0.0, 1.0] , msg=f"Parameter {name} of model {model_class} seems not properly initialized" , ) @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def _snake_case ( self : str ): pass def __a ( ): SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @cached_property def _snake_case ( self : List[str] ): return ViTImageProcessor.from_pretrained("MBZUAI/swiftformer-xs" ) if is_vision_available() else None @slow def _snake_case ( self : List[Any] ): SCREAMING_SNAKE_CASE = SwiftFormerForImageClassification.from_pretrained("MBZUAI/swiftformer-xs" ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = self.default_image_processor SCREAMING_SNAKE_CASE = prepare_img() SCREAMING_SNAKE_CASE = image_processor(images=__lowerCamelCase , return_tensors="pt" ).to(__lowerCamelCase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ) # verify the logits SCREAMING_SNAKE_CASE = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __lowerCamelCase ) SCREAMING_SNAKE_CASE = torch.tensor([[-2.17_03e00, 2.11_07e00, -2.08_11e00]] ).to(__lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowerCamelCase , atol=1e-4 ) )
16
import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, ) class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=13 , SCREAMING_SNAKE_CASE__ : int=7 , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=99 , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : List[str]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : Optional[Any]=37 , SCREAMING_SNAKE_CASE__ : Optional[int]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE__ : Tuple=512 , SCREAMING_SNAKE_CASE__ : Tuple=16 , SCREAMING_SNAKE_CASE__ : Optional[Any]=2 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 , SCREAMING_SNAKE_CASE__ : Dict=4 , ) -> Optional[int]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = seq_length lowerCAmelCase__ = is_training lowerCAmelCase__ = use_attention_mask lowerCAmelCase__ = use_token_type_ids lowerCAmelCase__ = use_labels lowerCAmelCase__ = vocab_size lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = type_vocab_size lowerCAmelCase__ = type_sequence_label_size lowerCAmelCase__ = initializer_range lowerCAmelCase__ = num_choices def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase__ = None if self.use_attention_mask: lowerCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase__ = None if self.use_token_type_ids: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCAmelCase__ = RobertaPreLayerNormConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def a ( self : List[str] ) -> Union[str, Any]: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict def a ( self : Optional[Any] ) -> Dict: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = True lowerCAmelCase__ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax # Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40 class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = True snake_case__ = ( ( FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, ) if is_flax_available() else () ) def a ( self : int ) -> Dict: lowerCAmelCase__ = FlaxRobertaPreLayerNormModelTester(self ) @slow def a ( self : Tuple ) -> Union[str, Any]: for model_class_name in self.all_model_classes: lowerCAmelCase__ = model_class_name.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(np.ones((1, 1) ) ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_flax class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @slow def a ( self : int ) -> Dict: lowerCAmelCase__ = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ )[0] lowerCAmelCase__ = [1, 11, 50_265] self.assertEqual(list(output.shape ) , SCREAMING_SNAKE_CASE__ ) # compare the actual values for a slice. lowerCAmelCase__ = np.array( [[[40.4_880, 18.0_199, -5.2_367], [-1.8_877, -4.0_885, 10.7_085], [-2.2_613, -5.6_110, 7.2_665]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) @slow def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = FlaxRobertaPreLayerNormModel.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ )[0] # compare the actual values for a slice. lowerCAmelCase__ = np.array( [[[0.0_208, -0.0_356, 0.0_237], [-0.1_569, -0.0_411, -0.2_626], [0.1_879, 0.0_125, -0.0_089]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available UpperCAmelCase_ : Union[str, Any] = {'''configuration_yolos''': ['''YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''YolosConfig''', '''YolosOnnxConfig''']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : List[str] = ['''YolosFeatureExtractor'''] UpperCAmelCase_ : Tuple = ['''YolosImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : List[Any] = [ '''YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''YolosForObjectDetection''', '''YolosModel''', '''YolosPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_yolos import YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP, YolosConfig, YolosOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_yolos import YolosFeatureExtractor from .image_processing_yolos import YolosImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_yolos import ( YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST, YolosForObjectDetection, YolosModel, YolosPreTrainedModel, ) else: import sys UpperCAmelCase_ : Optional[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
17
class __lowerCamelCase : """simple docstring""" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = size lowerCAmelCase__ = [0] * size lowerCAmelCase__ = [0] * size @staticmethod def a ( SCREAMING_SNAKE_CASE__ : int ) -> int: return index | (index + 1) @staticmethod def a ( SCREAMING_SNAKE_CASE__ : int ) -> int: return (index & (index + 1)) - 1 def a ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = value while index < self.size: lowerCAmelCase__ = self.get_prev(SCREAMING_SNAKE_CASE__ ) + 1 if current_left_border == index: lowerCAmelCase__ = value else: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_next(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> int: right -= 1 # Because of right is exclusive lowerCAmelCase__ = 0 while left <= right: lowerCAmelCase__ = self.get_prev(SCREAMING_SNAKE_CASE__ ) if left <= current_left: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , self.tree[right] ) lowerCAmelCase__ = current_left else: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
61
0
'''simple docstring''' import numpy as np from nltk.translate import meteor_score import datasets from datasets.config import importlib_metadata, version _SCREAMING_SNAKE_CASE = version.parse(importlib_metadata.version("nltk")) if NLTK_VERSION >= version.Version("3.6.4"): from nltk import word_tokenize _SCREAMING_SNAKE_CASE = "\\n@inproceedings{banarjee2005,\n title = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments},\n author = {Banerjee, Satanjeev and Lavie, Alon},\n booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization},\n month = jun,\n year = {2005},\n address = {Ann Arbor, Michigan},\n publisher = {Association for Computational Linguistics},\n url = {https://www.aclweb.org/anthology/W05-0909},\n pages = {65--72},\n}\n" _SCREAMING_SNAKE_CASE = "\\nMETEOR, an automatic metric for machine translation evaluation\nthat is based on a generalized concept of unigram matching between the\nmachine-produced translation and human-produced reference translations.\nUnigrams can be matched based on their surface forms, stemmed forms,\nand meanings; furthermore, METEOR can be easily extended to include more\nadvanced matching strategies. Once all generalized unigram matches\nbetween the two strings have been found, METEOR computes a score for\nthis matching using a combination of unigram-precision, unigram-recall, and\na measure of fragmentation that is designed to directly capture how\nwell-ordered the matched words in the machine translation are in relation\nto the reference.\n\nMETEOR gets an R correlation value of 0.347 with human evaluation on the Arabic\ndata and 0.331 on the Chinese data. This is shown to be an improvement on\nusing simply unigram-precision, unigram-recall and their harmonic F1\ncombination.\n" _SCREAMING_SNAKE_CASE = "\nComputes METEOR score of translated segments against one or more references.\nArgs:\n predictions: list of predictions to score. Each prediction\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\n alpha: Parameter for controlling relative weights of precision and recall. default: 0.9\n beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3\n gamma: Relative weight assigned to fragmentation penalty. default: 0.5\nReturns:\n 'meteor': meteor score.\nExamples:\n\n >>> meteor = datasets.load_metric('meteor')\n >>> predictions = [\"It is a guide to action which ensures that the military always obeys the commands of the party\"]\n >>> references = [\"It is a guide to action that ensures that the military will forever heed Party commands\"]\n >>> results = meteor.compute(predictions=predictions, references=references)\n >>> print(round(results[\"meteor\"], 4))\n 0.6944\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class lowerCAmelCase_ ( datasets.Metric ): def _snake_case ( self ) -> Optional[int]: 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/nltk/nltk/blob/develop/nltk/translate/meteor_score.py"] , reference_urls=[ "https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score", "https://en.wikipedia.org/wiki/METEOR", ] , ) def _snake_case ( self , _lowerCAmelCase ) -> Optional[int]: import nltk nltk.download("wordnet" ) if NLTK_VERSION >= version.Version("3.6.5" ): nltk.download("punkt" ) if NLTK_VERSION >= version.Version("3.6.6" ): nltk.download("omw-1.4" ) def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase=0.9 , _lowerCAmelCase=3 , _lowerCAmelCase=0.5 ) -> int: if NLTK_VERSION >= version.Version("3.6.5" ): _lowerCAmelCase = [ meteor_score.single_meteor_score( word_tokenize(_lowerCAmelCase ) , word_tokenize(_lowerCAmelCase ) , alpha=_lowerCAmelCase , beta=_lowerCAmelCase , gamma=_lowerCAmelCase ) for ref, pred in zip(_lowerCAmelCase , _lowerCAmelCase ) ] else: _lowerCAmelCase = [ meteor_score.single_meteor_score(_lowerCAmelCase , _lowerCAmelCase , alpha=_lowerCAmelCase , beta=_lowerCAmelCase , gamma=_lowerCAmelCase ) for ref, pred in zip(_lowerCAmelCase , _lowerCAmelCase ) ] return {"meteor": np.mean(_lowerCAmelCase )}
18
import unittest from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin UpperCamelCase = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = XLNetTokenizer snake_case__ = XLNetTokenizerFast snake_case__ = True snake_case__ = True def a ( self : str ) -> str: super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) tokenizer.sanitize_special_tokens() tokenizer.save_pretrained(self.tmpdirname ) def a ( self : List[str] ) -> List[Any]: lowerCAmelCase__ = "<s>" lowerCAmelCase__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def a ( self : Union[str, Any] ) -> str: lowerCAmelCase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "<eod>" ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 1_006 ) def a ( self : int ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 1_000 ) def a ( self : List[str] ) -> Any: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("This is a test" ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [285, 46, 10, 170, 382] ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) lowerCAmelCase__ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] ) lowerCAmelCase__ = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) def a ( self : Optional[int] ) -> Optional[Any]: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "", "i", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "se", ".", ] , ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["▁he", "ll", "o"] ) def a ( self : List[Any] ) -> Optional[int]: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "se", ".", ] , ) @slow def a ( self : Any ) -> Any: lowerCAmelCase__ = XLNetTokenizer.from_pretrained("xlnet-base-cased" ) lowerCAmelCase__ = tokenizer.encode("sequence builders" , add_special_tokens=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.encode("multi-sequence build" , add_special_tokens=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert encoded_sentence == text + [4, 3] assert encoded_pair == text + [4] + text_a + [4, 3] @slow def a ( self : Union[str, Any] ) -> Any: # fmt: off lowerCAmelCase__ = {"input_ids": [[17, 21_442, 270, 17, 10, 14_645, 318, 34, 17, 4_546, 3_145, 787, 13, 7_752, 22_018, 23, 21, 17, 4_546, 3_145, 787, 13, 3_352, 14_431, 13, 5_500, 11, 1_176, 580, 13, 16_819, 4_797, 23, 17, 10, 17_135, 658, 19, 457, 7_932, 13, 184, 19, 3_154, 17_135, 6_468, 19, 1_404, 12_269, 19, 4_229, 5_356, 16_264, 46, 19, 17, 20_545, 10_395, 9, 9, 9, 11, 28, 6_421, 9_531, 20_729, 17, 10, 353, 17_022, 11, 21, 6_421, 9_531, 16_949, 17, 10, 11_509, 753, 11, 33, 95, 2_421, 7_385, 956, 14_431, 2_626, 25, 842, 7_385, 4_836, 21, 1_429, 2_272, 9_855, 3_120, 161, 24_738, 19, 13_203, 658, 218, 787, 21, 430, 18_482, 847, 2_637, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 322, 22_178, 27, 1_064, 22, 956, 13, 11_101, 1_429, 5_854, 24_313, 18_953, 40, 422, 24_366, 68, 1_758, 37, 10_483, 14_257, 31, 207, 263, 21, 203, 3_773, 25, 71, 9_735, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 32, 2_049, 3_442, 17, 13_894, 3_380, 23, 95, 18, 17_634, 2_288, 9, 4, 3]], "token_type_ids": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=SCREAMING_SNAKE_CASE__ , model_name="xlnet-base-cased" , revision="c841166438c31ec7ca9a106dee7bb312b73ae511" , )
61
0
"""simple docstring""" import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class _UpperCAmelCase( lowerCamelCase ): def UpperCAmelCase ( self) -> Optional[int]: '''simple docstring''' _UpperCamelCase = pa.array(TypedSequence([1, 2, 3])) self.assertEqual(arr.type , pa.intaa()) def UpperCAmelCase ( self) -> List[str]: '''simple docstring''' with self.assertRaises(__a): _UpperCamelCase = pa.array(TypedSequence([1, 2, 3]) , type=pa.intaa()) def UpperCAmelCase ( self) -> Any: '''simple docstring''' with self.assertRaises(__a): _UpperCamelCase = pa.array(TypedSequence([1, 2, 3] , try_type=Value('''bool''') , type=Value('''int64'''))) def UpperCAmelCase ( self) -> Tuple: '''simple docstring''' _UpperCamelCase = pa.array(TypedSequence([1, 2, 3] , type=Value('''int32'''))) self.assertEqual(arr.type , pa.intaa()) def UpperCAmelCase ( self) -> int: '''simple docstring''' with self.assertRaises((TypeError, pa.lib.ArrowInvalid)): _UpperCamelCase = pa.array(TypedSequence(['''foo''', '''bar'''] , type=Value('''int64'''))) def UpperCAmelCase ( self) -> int: '''simple docstring''' _UpperCamelCase = pa.array(TypedSequence([1, 2, 3] , try_type=Value('''int32'''))) self.assertEqual(arr.type , pa.intaa()) def UpperCAmelCase ( self) -> Tuple: '''simple docstring''' _UpperCamelCase = pa.array(TypedSequence(['''foo''', '''bar'''] , try_type=Value('''int64'''))) self.assertEqual(arr.type , pa.string()) def UpperCAmelCase ( self) -> Any: '''simple docstring''' _UpperCamelCase = pa.array(TypedSequence([[[1, 2, 3]]] , type=ArrayaD((1, 3) , '''int64'''))) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , '''int64''')) def UpperCAmelCase ( self) -> Optional[int]: '''simple docstring''' with self.assertRaises((TypeError, pa.lib.ArrowInvalid)): _UpperCamelCase = pa.array(TypedSequence(['''foo''', '''bar'''] , type=ArrayaD((1, 3) , '''int64'''))) def UpperCAmelCase ( self) -> Dict: '''simple docstring''' _UpperCamelCase = pa.array(TypedSequence([[[1, 2, 3]]] , try_type=ArrayaD((1, 3) , '''int64'''))) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , '''int64''')) def UpperCAmelCase ( self) -> Tuple: '''simple docstring''' _UpperCamelCase = pa.array(TypedSequence(['''foo''', '''bar'''] , try_type=ArrayaD((1, 3) , '''int64'''))) self.assertEqual(arr.type , pa.string()) @require_pil def UpperCAmelCase ( self) -> List[Any]: '''simple docstring''' import PIL.Image _UpperCamelCase = PIL.Image.fromarray(np.arange(10 , dtype=np.uinta).reshape(2 , 5)) with patch( '''datasets.arrow_writer.cast_to_python_objects''' , side_effect=__a) as mock_cast_to_python_objects: _UpperCamelCase = pa.array(TypedSequence([{'''path''': None, '''bytes''': B'''image_bytes'''}, pil_image] , type=Image())) _UpperCamelCase , _UpperCamelCase = mock_cast_to_python_objects.call_args_list[-1] self.assertIn('''optimize_list_casting''' , __a) self.assertFalse(kwargs['''optimize_list_casting''']) def lowerCamelCase__ ( __snake_case, __snake_case ) -> Dict: """simple docstring""" _UpperCamelCase = pa.BufferReader(__snake_case ) if isinstance(__snake_case, pa.Buffer ) else pa.memory_map(__snake_case ) _UpperCamelCase = pa.ipc.open_stream(__snake_case ) _UpperCamelCase = f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize('''writer_batch_size''', [None, 1, 10] ) @pytest.mark.parametrize( '''fields''', [None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}] ) def lowerCamelCase__ ( __snake_case, __snake_case ) -> Optional[int]: """simple docstring""" _UpperCamelCase = pa.BufferOutputStream() _UpperCamelCase = pa.schema(__snake_case ) if fields else None with ArrowWriter(stream=__snake_case, schema=__snake_case, writer_batch_size=__snake_case ) as writer: writer.write({'''col_1''': '''foo''', '''col_2''': 1} ) writer.write({'''col_1''': '''bar''', '''col_2''': 2} ) _UpperCamelCase , _UpperCamelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: _UpperCamelCase = {'''col_1''': pa.string(), '''col_2''': pa.intaa()} assert writer._schema == pa.schema(__snake_case, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def lowerCamelCase__ ( ) -> List[Any]: """simple docstring""" _UpperCamelCase = pa.BufferOutputStream() _UpperCamelCase = Features({'''labels''': ClassLabel(names=['''neg''', '''pos'''] )} ) with ArrowWriter(stream=__snake_case, features=__snake_case ) as writer: writer.write({'''labels''': 0} ) writer.write({'''labels''': 1} ) _UpperCamelCase , _UpperCamelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata _UpperCamelCase = pa.BufferReader(output.getvalue() ) _UpperCamelCase = pa.ipc.open_stream(__snake_case ) _UpperCamelCase = f.read_all() _UpperCamelCase = pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(__snake_case ) @pytest.mark.parametrize('''writer_batch_size''', [None, 1, 10] ) def lowerCamelCase__ ( __snake_case ) -> Dict: """simple docstring""" _UpperCamelCase = pa.BufferOutputStream() with ArrowWriter( stream=__snake_case, writer_batch_size=__snake_case, hash_salt='''split_name''', check_duplicates=__snake_case, ) as writer: with pytest.raises(__snake_case ): writer.write({'''col_1''': '''foo''', '''col_2''': 1}, key=[1, 2] ) _UpperCamelCase , _UpperCamelCase = writer.finalize() @pytest.mark.parametrize('''writer_batch_size''', [None, 2, 10] ) def lowerCamelCase__ ( __snake_case ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase = pa.BufferOutputStream() with ArrowWriter( stream=__snake_case, writer_batch_size=__snake_case, hash_salt='''split_name''', check_duplicates=__snake_case, ) as writer: with pytest.raises(__snake_case ): writer.write({'''col_1''': '''foo''', '''col_2''': 1}, key=10 ) writer.write({'''col_1''': '''bar''', '''col_2''': 2}, key=10 ) _UpperCamelCase , _UpperCamelCase = writer.finalize() @pytest.mark.parametrize('''writer_batch_size''', [None, 2, 10] ) def lowerCamelCase__ ( __snake_case ) -> Optional[int]: """simple docstring""" _UpperCamelCase = pa.BufferOutputStream() with ArrowWriter( stream=__snake_case, writer_batch_size=__snake_case, hash_salt='''split_name''', check_duplicates=__snake_case, ) as writer: writer.write({'''col_1''': '''foo''', '''col_2''': 1}, key=1 ) writer.write({'''col_1''': '''bar''', '''col_2''': 2}, key=2 ) _UpperCamelCase , _UpperCamelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('''writer_batch_size''', [None, 1, 10] ) @pytest.mark.parametrize( '''fields''', [None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}] ) def lowerCamelCase__ ( __snake_case, __snake_case ) -> Optional[Any]: """simple docstring""" _UpperCamelCase = pa.BufferOutputStream() _UpperCamelCase = pa.schema(__snake_case ) if fields else None with ArrowWriter(stream=__snake_case, schema=__snake_case, writer_batch_size=__snake_case ) as writer: writer.write_batch({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]} ) writer.write_batch({'''col_1''': [], '''col_2''': []} ) _UpperCamelCase , _UpperCamelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: _UpperCamelCase = {'''col_1''': pa.string(), '''col_2''': pa.intaa()} assert writer._schema == pa.schema(__snake_case, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('''writer_batch_size''', [None, 1, 10] ) @pytest.mark.parametrize( '''fields''', [None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}] ) def lowerCamelCase__ ( __snake_case, __snake_case ) -> Optional[int]: """simple docstring""" _UpperCamelCase = pa.BufferOutputStream() _UpperCamelCase = pa.schema(__snake_case ) if fields else None with ArrowWriter(stream=__snake_case, schema=__snake_case, writer_batch_size=__snake_case ) as writer: writer.write_table(pa.Table.from_pydict({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]} ) ) _UpperCamelCase , _UpperCamelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: _UpperCamelCase = {'''col_1''': pa.string(), '''col_2''': pa.intaa()} assert writer._schema == pa.schema(__snake_case, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('''writer_batch_size''', [None, 1, 10] ) @pytest.mark.parametrize( '''fields''', [None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}] ) def lowerCamelCase__ ( __snake_case, __snake_case ) -> Any: """simple docstring""" _UpperCamelCase = pa.BufferOutputStream() _UpperCamelCase = pa.schema(__snake_case ) if fields else None with ArrowWriter(stream=__snake_case, schema=__snake_case, writer_batch_size=__snake_case ) as writer: writer.write_row(pa.Table.from_pydict({'''col_1''': ['''foo'''], '''col_2''': [1]} ) ) writer.write_row(pa.Table.from_pydict({'''col_1''': ['''bar'''], '''col_2''': [2]} ) ) _UpperCamelCase , _UpperCamelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: _UpperCamelCase = {'''col_1''': pa.string(), '''col_2''': pa.intaa()} assert writer._schema == pa.schema(__snake_case, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def lowerCamelCase__ ( ) -> str: """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: _UpperCamelCase = {'''col_1''': pa.string(), '''col_2''': pa.intaa()} _UpperCamelCase = os.path.join(__snake_case, '''test.arrow''' ) with ArrowWriter(path=__snake_case, schema=pa.schema(__snake_case ) ) as writer: writer.write_batch({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]} ) _UpperCamelCase , _UpperCamelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(__snake_case, metadata=writer._schema.metadata ) _check_output(__snake_case, 1 ) def lowerCamelCase__ ( __snake_case ) -> Optional[int]: """simple docstring""" if pa.types.is_list(__snake_case ): return get_base_dtype(arr_type.value_type ) else: return arr_type def lowerCamelCase__ ( __snake_case, __snake_case ) -> List[Any]: """simple docstring""" if isinstance(lst[0], __snake_case ): change_first_primitive_element_in_list(lst[0], __snake_case ) else: _UpperCamelCase = value @pytest.mark.parametrize('''optimized_int_type, expected_dtype''', [(None, pa.intaa()), (Value('''int32''' ), pa.intaa())] ) @pytest.mark.parametrize('''sequence''', [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> Optional[Any]: """simple docstring""" _UpperCamelCase = pa.array(TypedSequence(__snake_case, optimized_int_type=__snake_case ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( '''col, expected_dtype''', [ ('''attention_mask''', pa.inta()), ('''special_tokens_mask''', pa.inta()), ('''token_type_ids''', pa.inta()), ('''input_ids''', pa.intaa()), ('''other''', pa.intaa()), ], ) @pytest.mark.parametrize('''sequence''', [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase = pa.array(OptimizedTypedSequence(__snake_case, col=__snake_case ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications _UpperCamelCase = copy.deepcopy(__snake_case ) _UpperCamelCase = np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(__snake_case, __snake_case ) _UpperCamelCase = pa.array(OptimizedTypedSequence(__snake_case, col=__snake_case ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize('''raise_exception''', [False, True] ) def lowerCamelCase__ ( __snake_case, __snake_case ) -> Any: """simple docstring""" _UpperCamelCase = str(tmp_path / '''dataset-train.arrow''' ) try: with ArrowWriter(path=__snake_case ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def lowerCamelCase__ ( __snake_case ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase = '''mock://dataset-train.arrow''' with ArrowWriter(path=__snake_case, storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs, type(__snake_case ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({'''col_1''': '''foo''', '''col_2''': 1} ) writer.write({'''col_1''': '''bar''', '''col_2''': 2} ) _UpperCamelCase , _UpperCamelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(__snake_case ) def lowerCamelCase__ ( ) -> Tuple: """simple docstring""" _UpperCamelCase = pa.BufferOutputStream() with ParquetWriter(stream=__snake_case ) as writer: writer.write({'''col_1''': '''foo''', '''col_2''': 1} ) writer.write({'''col_1''': '''bar''', '''col_2''': 2} ) _UpperCamelCase , _UpperCamelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _UpperCamelCase = pa.BufferReader(output.getvalue() ) _UpperCamelCase = pq.read_table(__snake_case ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize('''embed_local_files''', [False, True] ) def lowerCamelCase__ ( __snake_case, __snake_case ) -> List[str]: """simple docstring""" import PIL.Image _UpperCamelCase = str(tmp_path / '''test_image_rgb.jpg''' ) PIL.Image.fromarray(np.zeros((5, 5), dtype=np.uinta ) ).save(__snake_case, format='''png''' ) _UpperCamelCase = pa.BufferOutputStream() with ParquetWriter( stream=__snake_case, features=Features({'''image''': Image()} ), embed_local_files=__snake_case ) as writer: writer.write({'''image''': image_path} ) writer.finalize() _UpperCamelCase = pa.BufferReader(output.getvalue() ) _UpperCamelCase = pq.read_table(__snake_case ) _UpperCamelCase = pa_table.to_pydict() if embed_local_files: assert isinstance(out['''image'''][0]['''path'''], __snake_case ) with open(__snake_case, '''rb''' ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def lowerCamelCase__ ( ) -> int: """simple docstring""" _UpperCamelCase = pa.schema([pa.field('''col_1''', pa.string(), nullable=__snake_case )] ) _UpperCamelCase = pa.BufferOutputStream() with ArrowWriter(stream=__snake_case ) as writer: writer._build_writer(inferred_schema=__snake_case ) assert writer._schema == pa.schema([pa.field('''col_1''', pa.string() )] )
19
import operator as op UpperCamelCase = 'scaler.pt' UpperCamelCase = 'pytorch_model' UpperCamelCase = 'random_states' UpperCamelCase = 'optimizer' UpperCamelCase = 'scheduler' UpperCamelCase = 'pytorch_model.bin' UpperCamelCase = 'pytorch_model.bin.index.json' UpperCamelCase = 'model.safetensors' UpperCamelCase = 'model.safetensors.index.json' UpperCamelCase = '1.10.2' UpperCamelCase = 'py38' UpperCamelCase = '4.17.0' UpperCamelCase = ['ml.p3.16xlarge', 'ml.p3dn.24xlarge', 'ml.p4dn.24xlarge'] UpperCamelCase = ['FULL_SHARD', 'SHARD_GRAD_OP', 'NO_SHARD', 'HYBRID_SHARD', 'HYBRID_SHARD_ZERO2'] UpperCamelCase = ['TRANSFORMER_BASED_WRAP', 'SIZE_BASED_WRAP', 'NO_WRAP'] UpperCamelCase = ['BACKWARD_PRE', 'BACKWARD_POST', 'NO_PREFETCH'] UpperCamelCase = ['FULL_STATE_DICT', 'LOCAL_STATE_DICT', 'SHARDED_STATE_DICT'] UpperCamelCase = '2.0.1' UpperCamelCase = ['pdsh', 'standard', 'openmpi', 'mvapich'] UpperCamelCase = ['default', 'reduce-overhead', 'max-autotune'] UpperCamelCase = {'>': op.gt, '>=': op.ge, '==': op.eq, '!=': op.ne, '<=': op.le, '<': op.lt} # These are the args for `torch.distributed.launch` for pytorch < 1.9 UpperCamelCase = [ 'nnodes', 'nproc_per_node', 'rdzv_backend', 'rdzv_endpoint', 'rdzv_id', 'rdzv_conf', 'standalone', 'max_restarts', 'monitor_interval', 'start_method', 'role', 'module', 'm', 'no_python', 'run_path', 'log_dir', 'r', 'redirects', 't', 'tee', 'node_rank', 'master_addr', 'master_port', ] UpperCamelCase = ['DEEPSPEED', 'MULTI_GPU', 'FSDP', 'MEGATRON_LM'] UpperCamelCase = ['DEEPSPEED', 'MULTI_XPU', 'FSDP']
61
0
import os import unittest from transformers.models.bartpho.tokenization_bartpho import VOCAB_FILES_NAMES, BartphoTokenizer from transformers.testing_utils import get_tests_dir from ...test_tokenization_common import TokenizerTesterMixin _lowerCAmelCase: List[str] = get_tests_dir('fixtures/test_sentencepiece_bpe.model') class lowercase_ (lowercase__ , unittest.TestCase ): snake_case =BartphoTokenizer snake_case =False snake_case =True def __UpperCamelCase ( self) -> List[str]: super().setUp() a__ =['▁This', '▁is', '▁a', '▁t', 'est'] a__ =dict(zip(lowercase_ , range(len(lowercase_)))) a__ ={'unk_token': '<unk>'} a__ =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['monolingual_vocab_file']) with open(self.monolingual_vocab_file , 'w' , encoding='utf-8') as fp: for token in vocab_tokens: fp.write(F"""{token} {vocab_tokens[token]}\n""") a__ =BartphoTokenizer(lowercase_ , self.monolingual_vocab_file , **self.special_tokens_map) tokenizer.save_pretrained(self.tmpdirname) def __UpperCamelCase ( self , **lowercase_) -> Optional[Any]: kwargs.update(self.special_tokens_map) return BartphoTokenizer.from_pretrained(self.tmpdirname , **lowercase_) def __UpperCamelCase ( self , lowercase_) -> Dict: a__ ='This is a là test' a__ ='This is a<unk><unk> test' return input_text, output_text def __UpperCamelCase ( self) -> Any: a__ =BartphoTokenizer(lowercase_ , self.monolingual_vocab_file , **self.special_tokens_map) a__ ='This is a là test' a__ ='▁This ▁is ▁a ▁l à ▁t est'.split() a__ =tokenizer.tokenize(lowercase_) self.assertListEqual(lowercase_ , lowercase_) a__ =tokens + [tokenizer.unk_token] a__ =[4, 5, 6, 3, 3, 7, 8, 3] self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase_) , lowercase_)
20
import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'vocab_file': 'sentencepiece.model'} UpperCamelCase = { 'vocab_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model', }, } UpperCamelCase = { 'google/rembert': 256, } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int]=False , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : Any="[CLS]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" , SCREAMING_SNAKE_CASE__ : Dict="[UNK]" , SCREAMING_SNAKE_CASE__ : Optional[Any]="[SEP]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[PAD]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[CLS]" , SCREAMING_SNAKE_CASE__ : List[Any]="[MASK]" , **SCREAMING_SNAKE_CASE__ : str , ) -> Dict: super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ , remove_space=SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = do_lower_case lowerCAmelCase__ = remove_space lowerCAmelCase__ = keep_accents lowerCAmelCase__ = vocab_file lowerCAmelCase__ = spm.SentencePieceProcessor() self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def a ( self : int ) -> Union[str, Any]: return len(self.sp_model ) def a ( self : Any ) -> str: lowerCAmelCase__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Union[str, Any] ) -> List[str]: lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = d lowerCAmelCase__ = spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int=False ) -> Optional[int]: lowerCAmelCase__ = self.sp_model.EncodeAsPieces(SCREAMING_SNAKE_CASE__ ) return pieces def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> List[Any]: return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Dict: return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : int ) -> int: lowerCAmelCase__ = self.sp_model.decode_pieces(SCREAMING_SNAKE_CASE__ ) return out_string def a ( self : int , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: 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 not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error("Vocabulary path ({}) should be a directory".format(SCREAMING_SNAKE_CASE__ ) ) return lowerCAmelCase__ = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
61
0
import argparse import collections import os import re 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_table.py UpperCAmelCase_ : List[str] = "src/transformers" UpperCAmelCase_ : List[str] = "docs/source/en" UpperCAmelCase_ : str = "." def lowerCAmelCase_ ( lowerCamelCase , lowerCamelCase , lowerCamelCase ): with open(lowerCamelCase , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: __magic_name__ : Optional[int] =f.readlines() # Find the start prompt. __magic_name__ : Dict =0 while not lines[start_index].startswith(lowerCamelCase ): start_index += 1 start_index += 1 __magic_name__ : Union[str, Any] =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 # Add here suffixes that are used to identify models, separated by | UpperCAmelCase_ : Any = "Model|Encoder|Decoder|ForConditionalGeneration" # Regexes that match TF/Flax/PT model names. UpperCAmelCase_ : Any = re.compile(R"TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)") UpperCAmelCase_ : Tuple = re.compile(R"Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)") # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. UpperCAmelCase_ : Optional[int] = re.compile(R"(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)") # This is to make sure the transformers module imported is the one in the repo. UpperCAmelCase_ : Tuple = direct_transformers_import(TRANSFORMERS_PATH) def lowerCAmelCase_ ( lowerCamelCase ): __magic_name__ : int =re.finditer(""".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)""" , lowerCamelCase ) return [m.group(0 ) for m in matches] def lowerCAmelCase_ ( lowerCamelCase , lowerCamelCase ): __magic_name__ : Any =2 if text == """✅""" or text == """❌""" else len(lowerCamelCase ) __magic_name__ : Optional[Any] =(width - text_length) // 2 __magic_name__ : str =width - text_length - left_indent return " " * left_indent + text + " " * right_indent def lowerCAmelCase_ ( ): __magic_name__ : Union[str, Any] =transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES __magic_name__ : Optional[int] ={ name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } __magic_name__ : Union[str, Any] ={name: config.replace("""Config""" , """""" ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. __magic_name__ : Any =collections.defaultdict(lowerCamelCase ) __magic_name__ : Union[str, Any] =collections.defaultdict(lowerCamelCase ) __magic_name__ : List[Any] =collections.defaultdict(lowerCamelCase ) __magic_name__ : int =collections.defaultdict(lowerCamelCase ) __magic_name__ : Dict =collections.defaultdict(lowerCamelCase ) # Let's lookup through all transformers object (once). for attr_name in dir(lowerCamelCase ): __magic_name__ : Dict =None if attr_name.endswith("""Tokenizer""" ): __magic_name__ : Optional[Any] =slow_tokenizers __magic_name__ : str =attr_name[:-9] elif attr_name.endswith("""TokenizerFast""" ): __magic_name__ : Tuple =fast_tokenizers __magic_name__ : Dict =attr_name[:-13] elif _re_tf_models.match(lowerCamelCase ) is not None: __magic_name__ : List[str] =tf_models __magic_name__ : List[str] =_re_tf_models.match(lowerCamelCase ).groups()[0] elif _re_flax_models.match(lowerCamelCase ) is not None: __magic_name__ : Tuple =flax_models __magic_name__ : Tuple =_re_flax_models.match(lowerCamelCase ).groups()[0] elif _re_pt_models.match(lowerCamelCase ) is not None: __magic_name__ : List[Any] =pt_models __magic_name__ : Any =_re_pt_models.match(lowerCamelCase ).groups()[0] if lookup_dict is not None: while len(lowerCamelCase ) > 0: if attr_name in model_name_to_prefix.values(): __magic_name__ : Optional[int] =True break # Try again after removing the last word in the name __magic_name__ : Union[str, Any] ="""""".join(camel_case_split(lowerCamelCase )[:-1] ) # Let's build that table! __magic_name__ : List[str] =list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) __magic_name__ : Union[str, Any] =["""Model""", """Tokenizer slow""", """Tokenizer fast""", """PyTorch support""", """TensorFlow support""", """Flax Support"""] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). __magic_name__ : Optional[int] =[len(lowerCamelCase ) + 2 for c in columns] __magic_name__ : int =max([len(lowerCamelCase ) for name in model_names] ) + 2 # Build the table per se __magic_name__ : List[Any] ="""|""" + """|""".join([_center_text(lowerCamelCase , lowerCamelCase ) for c, w in zip(lowerCamelCase , lowerCamelCase )] ) + """|\n""" # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([""":""" + """-""" * (w - 2) + """:""" for w in widths] ) + "|\n" __magic_name__ : Optional[int] ={True: """✅""", False: """❌"""} for name in model_names: __magic_name__ : Optional[Any] =model_name_to_prefix[name] __magic_name__ : Optional[Any] =[ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(lowerCamelCase , lowerCamelCase ) for l, w in zip(lowerCamelCase , lowerCamelCase )] ) + "|\n" return table def lowerCAmelCase_ ( lowerCamelCase=False ): __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ : List[Any] =_find_text_in_file( filename=os.path.join(lowerCamelCase , """index.md""" ) , start_prompt="""<!--This table is updated automatically from the auto modules""" , end_prompt="""<!-- End table-->""" , ) __magic_name__ : Any =get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(lowerCamelCase , """index.md""" ) , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( """The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.""" ) if __name__ == "__main__": UpperCAmelCase_ : List[str] = argparse.ArgumentParser() parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") UpperCAmelCase_ : Dict = parser.parse_args() check_model_table(args.fix_and_overwrite)
21
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
61
0
'''simple docstring''' from datasets.utils.patching import _PatchedModuleObj, patch_submodule from . import _test_patching def snake_case_ (): '''simple docstring''' import os as original_os from os import path as original_path from os import rename as original_rename from os.path import dirname as original_dirname from os.path import join as original_join assert _test_patching.os is original_os assert _test_patching.path is original_path assert _test_patching.join is original_join assert _test_patching.renamed_os is original_os assert _test_patching.renamed_path is original_path assert _test_patching.renamed_join is original_join _a = '''__test_patch_submodule_mock__''' with patch_submodule(_test_patching , '''os.path.join''' , UpperCamelCase ): # Every way to access os.path.join must be patched, and the rest must stay untouched # check os.path.join assert isinstance(_test_patching.os , _PatchedModuleObj ) assert isinstance(_test_patching.os.path , _PatchedModuleObj ) assert _test_patching.os.path.join is mock # check path.join assert isinstance(_test_patching.path , _PatchedModuleObj ) assert _test_patching.path.join is mock # check join assert _test_patching.join is mock # check that the other attributes are untouched assert _test_patching.os.rename is original_rename assert _test_patching.path.dirname is original_dirname assert _test_patching.os.path.dirname is original_dirname # Even renamed modules or objects must be patched # check renamed_os.path.join assert isinstance(_test_patching.renamed_os , _PatchedModuleObj ) assert isinstance(_test_patching.renamed_os.path , _PatchedModuleObj ) assert _test_patching.renamed_os.path.join is mock # check renamed_path.join assert isinstance(_test_patching.renamed_path , _PatchedModuleObj ) assert _test_patching.renamed_path.join is mock # check renamed_join assert _test_patching.renamed_join is mock # check that the other attributes are untouched assert _test_patching.renamed_os.rename is original_rename assert _test_patching.renamed_path.dirname is original_dirname assert _test_patching.renamed_os.path.dirname is original_dirname # check that everthing is back to normal when the patch is over assert _test_patching.os is original_os assert _test_patching.path is original_path assert _test_patching.join is original_join assert _test_patching.renamed_os is original_os assert _test_patching.renamed_path is original_path assert _test_patching.renamed_join is original_join def snake_case_ (): '''simple docstring''' assert _test_patching.open is open _a = '''__test_patch_submodule_builtin_mock__''' # _test_patching has "open" in its globals assert _test_patching.open is open with patch_submodule(_test_patching , '''open''' , UpperCamelCase ): assert _test_patching.open is mock # check that everthing is back to normal when the patch is over assert _test_patching.open is open def snake_case_ (): '''simple docstring''' _a = '''__test_patch_submodule_missing_mock__''' with patch_submodule(_test_patching , '''pandas.read_csv''' , UpperCamelCase ): pass def snake_case_ (): '''simple docstring''' _a = '''__test_patch_submodule_missing_builtin_mock__''' # _test_patching doesn't have "len" in its globals assert getattr(_test_patching , '''len''' , UpperCamelCase ) is None with patch_submodule(_test_patching , '''len''' , UpperCamelCase ): assert _test_patching.len is mock assert _test_patching.len is len def snake_case_ (): '''simple docstring''' _a = '''__test_patch_submodule_start_and_stop_mock__''' _a = patch_submodule(_test_patching , '''open''' , UpperCamelCase ) assert _test_patching.open is open patch.start() assert _test_patching.open is mock patch.stop() assert _test_patching.open is open def snake_case_ (): '''simple docstring''' from os import rename as original_rename from os.path import dirname as original_dirname from os.path import join as original_join _a = '''__test_patch_submodule_successive_join__''' _a = '''__test_patch_submodule_successive_dirname__''' _a = '''__test_patch_submodule_successive_rename__''' assert _test_patching.os.path.join is original_join assert _test_patching.os.path.dirname is original_dirname assert _test_patching.os.rename is original_rename with patch_submodule(_test_patching , '''os.path.join''' , UpperCamelCase ): with patch_submodule(_test_patching , '''os.rename''' , UpperCamelCase ): with patch_submodule(_test_patching , '''os.path.dirname''' , UpperCamelCase ): assert _test_patching.os.path.join is mock_join assert _test_patching.os.path.dirname is mock_dirname assert _test_patching.os.rename is mock_rename # try another order with patch_submodule(_test_patching , '''os.rename''' , UpperCamelCase ): with patch_submodule(_test_patching , '''os.path.join''' , UpperCamelCase ): with patch_submodule(_test_patching , '''os.path.dirname''' , UpperCamelCase ): assert _test_patching.os.path.join is mock_join assert _test_patching.os.path.dirname is mock_dirname assert _test_patching.os.rename is mock_rename assert _test_patching.os.path.join is original_join assert _test_patching.os.path.dirname is original_dirname assert _test_patching.os.rename is original_rename def snake_case_ (): '''simple docstring''' _a = '''__test_patch_submodule_doesnt_exist_mock__''' with patch_submodule(_test_patching , '''__module_that_doesn_exist__.__attribute_that_doesn_exist__''' , UpperCamelCase ): pass with patch_submodule(_test_patching , '''os.__attribute_that_doesn_exist__''' , UpperCamelCase ): pass
22
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = ["pixel_values"] def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Union[int, float] = 1 / 255 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> None: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = size if size is not None else {"shortest_edge": 384} lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = do_resize lowerCAmelCase__ = size # Default value set here for backwards compatibility where the value in config is None lowerCAmelCase__ = crop_pct if crop_pct is not None else 224 / 256 lowerCAmelCase__ = resample lowerCAmelCase__ = do_rescale lowerCAmelCase__ = rescale_factor lowerCAmelCase__ = do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN lowerCAmelCase__ = image_std if image_std is not None else IMAGENET_STANDARD_STD def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : int , ) -> np.ndarray: lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) if "shortest_edge" not in size: raise ValueError(f'Size dictionary must contain \'shortest_edge\' key. Got {size.keys()}' ) lowerCAmelCase__ = size["shortest_edge"] if shortest_edge < 384: # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct lowerCAmelCase__ = int(shortest_edge / crop_pct ) lowerCAmelCase__ = get_resize_output_image_size(SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # then crop to (shortest_edge, shortest_edge) return center_crop(image=SCREAMING_SNAKE_CASE__ , size=(shortest_edge, shortest_edge) , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) else: # warping (no cropping) when evaluated at 384 or larger return resize( SCREAMING_SNAKE_CASE__ , size=(shortest_edge, shortest_edge) , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : int , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[int, float] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> List[Any]: return rescale(SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Optional[int] , ) -> np.ndarray: return normalize(SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : ImageInput , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE__ : ChannelDimension = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE__ : Dict , ) -> PIL.Image.Image: lowerCAmelCase__ = do_resize if do_resize is not None else self.do_resize lowerCAmelCase__ = crop_pct if crop_pct is not None else self.crop_pct lowerCAmelCase__ = resample if resample is not None else self.resample lowerCAmelCase__ = do_rescale if do_rescale is not None else self.do_rescale lowerCAmelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCAmelCase__ = do_normalize if do_normalize is not None else self.do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else self.image_mean lowerCAmelCase__ = image_std if image_std is not None else self.image_std lowerCAmelCase__ = size if size is not None else self.size lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = make_list_of_images(SCREAMING_SNAKE_CASE__ ) if not valid_images(SCREAMING_SNAKE_CASE__ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_resize and size["shortest_edge"] < 384 and crop_pct is None: raise ValueError("crop_pct must be specified if size < 384." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. lowerCAmelCase__ = [to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if do_resize: lowerCAmelCase__ = [self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , crop_pct=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images] if do_rescale: lowerCAmelCase__ = [self.rescale(image=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ ) for image in images] if do_normalize: lowerCAmelCase__ = [self.normalize(image=SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = {"pixel_values": images} return BatchFeature(data=SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ )
61
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 snake_case__ : Union[str, Any] = logging.get_logger(__name__) @add_end_docstrings(UpperCAmelCase__ ) class _a ( UpperCAmelCase__ ): """simple docstring""" def __init__( self , *_UpperCAmelCase , **_UpperCAmelCase ) -> Any: super().__init__(*_UpperCAmelCase , **_UpperCAmelCase ) 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 _UpperCAmelCase ( self , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=None ) -> List[str]: UpperCamelCase_ = {} UpperCamelCase_ = {} if prompt is not None: UpperCamelCase_ = prompt if generate_kwargs is not None: UpperCamelCase_ = generate_kwargs if max_new_tokens is not None: if "generate_kwargs" not in forward_kwargs: UpperCamelCase_ = {} 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' ) UpperCamelCase_ = max_new_tokens return preprocess_params, forward_kwargs, {} def __call__( self , _UpperCAmelCase , **_UpperCAmelCase ) -> int: return super().__call__(_UpperCAmelCase , **_UpperCAmelCase ) def _UpperCAmelCase ( self , _UpperCAmelCase , _UpperCAmelCase=None ) -> str: UpperCamelCase_ = load_image(_UpperCAmelCase ) if prompt is not None: if not isinstance(_UpperCAmelCase , _UpperCAmelCase ): raise ValueError( f"""Received an invalid text input, got - {type(_UpperCAmelCase )} - but expected a single string. """ 'Note also that one single text can be provided for conditional image to text generation.' ) UpperCamelCase_ = self.model.config.model_type if model_type == "git": UpperCamelCase_ = self.image_processor(images=_UpperCAmelCase , return_tensors=self.framework ) UpperCamelCase_ = self.tokenizer(text=_UpperCAmelCase , add_special_tokens=_UpperCAmelCase ).input_ids UpperCamelCase_ = [self.tokenizer.cls_token_id] + input_ids UpperCamelCase_ = torch.tensor(_UpperCAmelCase ).unsqueeze(0 ) model_inputs.update({'input_ids': input_ids} ) elif model_type == "pix2struct": UpperCamelCase_ = self.image_processor(images=_UpperCAmelCase , header_text=_UpperCAmelCase , return_tensors=self.framework ) elif model_type != "vision-encoder-decoder": # vision-encoder-decoder does not support conditional generation UpperCamelCase_ = self.image_processor(images=_UpperCAmelCase , return_tensors=self.framework ) UpperCamelCase_ = self.tokenizer(_UpperCAmelCase , return_tensors=self.framework ) model_inputs.update(_UpperCAmelCase ) else: raise ValueError(f"""Model type {model_type} does not support conditional text generation""" ) else: UpperCamelCase_ = self.image_processor(images=_UpperCAmelCase , return_tensors=self.framework ) if self.model.config.model_type == "git" and prompt is None: UpperCamelCase_ = None return model_inputs def _UpperCAmelCase ( self , _UpperCAmelCase , _UpperCAmelCase=None ) -> Any: # Git model sets `model_inputs["input_ids"] = None` in `preprocess` (when `prompt=None`). In batch model, the # pipeline will group them into a list of `None`, which fail `_forward`. Avoid this by checking it first. if ( "input_ids" in model_inputs and isinstance(model_inputs['input_ids'] , _UpperCAmelCase ) and all(x is None for x in model_inputs['input_ids'] ) ): UpperCamelCase_ = None if generate_kwargs is None: UpperCamelCase_ = {} # 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. UpperCamelCase_ = model_inputs.pop(self.model.main_input_name ) UpperCamelCase_ = self.model.generate(_UpperCAmelCase , **_UpperCAmelCase , **_UpperCAmelCase ) return model_outputs def _UpperCAmelCase ( self , _UpperCAmelCase ) -> Any: UpperCamelCase_ = [] for output_ids in model_outputs: UpperCamelCase_ = { 'generated_text': self.tokenizer.decode( _UpperCAmelCase , skip_special_tokens=_UpperCAmelCase , ) } records.append(_UpperCAmelCase ) return records
23
import shutil import tempfile import unittest import numpy as np import pytest from transformers import is_speech_available, is_vision_available from transformers.testing_utils import require_torch if is_vision_available(): from transformers import TvltImageProcessor if is_speech_available(): from transformers import TvltFeatureExtractor from transformers import TvltProcessor @require_torch class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : Any ) -> int: lowerCAmelCase__ = "ZinengTang/tvlt-base" lowerCAmelCase__ = tempfile.mkdtemp() def a ( self : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: return TvltImageProcessor.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE__ ) def a ( self : int , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> str: return TvltFeatureExtractor.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] ) -> Any: shutil.rmtree(self.tmpdirname ) def a ( self : Any ) -> Union[str, Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) lowerCAmelCase__ = TvltProcessor.from_pretrained(self.tmpdirname ) self.assertIsInstance(processor.feature_extractor , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> List[Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([12_000] ) lowerCAmelCase__ = feature_extractor(SCREAMING_SNAKE_CASE__ , return_tensors="np" ) lowerCAmelCase__ = processor(audio=SCREAMING_SNAKE_CASE__ , return_tensors="np" ) for key in audio_dict.keys(): self.assertAlmostEqual(audio_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a ( self : Dict ) -> str: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([3, 224, 224] ) lowerCAmelCase__ = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors="np" ) lowerCAmelCase__ = processor(images=SCREAMING_SNAKE_CASE__ , return_tensors="np" ) for key in image_dict.keys(): self.assertAlmostEqual(image_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a ( self : int ) -> Any: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([12_000] ) lowerCAmelCase__ = np.ones([3, 224, 224] ) lowerCAmelCase__ = processor(audio=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , ["audio_values", "audio_mask", "pixel_values", "pixel_mask"] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE__ ): processor() def a ( self : Tuple ) -> Optional[Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( processor.model_input_names , image_processor.model_input_names + feature_extractor.model_input_names , msg="`processor` and `image_processor`+`feature_extractor` model input names do not match" , )
61
0
'''simple docstring''' import gc import random import unittest import torch from diffusers import ( IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ) from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference from . import IFPipelineTesterMixin @skip_mps class lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase , unittest.TestCase): __lowercase : Dict = IFPipeline __lowercase : Optional[int] = TEXT_TO_IMAGE_PARAMS - {'''width''', '''height''', '''latents'''} __lowercase : int = TEXT_TO_IMAGE_BATCH_PARAMS __lowercase : Tuple = PipelineTesterMixin.required_optional_params - {'''latents'''} def lowerCAmelCase ( self ) -> Optional[Any]: '''simple docstring''' return self._get_dummy_components() def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=0 ) -> Union[str, Any]: '''simple docstring''' if str(__SCREAMING_SNAKE_CASE ).startswith('''mps''' ): __snake_case = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: __snake_case = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) __snake_case = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def lowerCAmelCase ( self ) -> int: '''simple docstring''' self._test_save_load_optional_components() @unittest.skipIf(torch_device != '''cuda''' , reason='''float16 requires CUDA''' ) def lowerCAmelCase ( self ) -> List[str]: '''simple docstring''' super().test_save_load_floataa(expected_max_diff=1E-1 ) def lowerCAmelCase ( self ) -> Union[str, Any]: '''simple docstring''' self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def lowerCAmelCase ( self ) -> int: '''simple docstring''' self._test_save_load_local() def lowerCAmelCase ( self ) -> List[str]: '''simple docstring''' self._test_inference_batch_single_identical( expected_max_diff=1E-2 , ) @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def lowerCAmelCase ( self ) -> str: '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @slow @require_torch_gpu class lowerCAmelCase ( unittest.TestCase): def lowerCAmelCase ( self ) -> Tuple: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase ( self ) -> Dict: '''simple docstring''' __snake_case = IFPipeline.from_pretrained('''DeepFloyd/IF-I-XL-v1.0''' , variant='''fp16''' , torch_dtype=torch.floataa ) __snake_case = IFSuperResolutionPipeline.from_pretrained( '''DeepFloyd/IF-II-L-v1.0''' , variant='''fp16''' , torch_dtype=torch.floataa , text_encoder=__SCREAMING_SNAKE_CASE , tokenizer=__SCREAMING_SNAKE_CASE ) # pre compute text embeddings and remove T5 to save memory pipe_a.text_encoder.to('''cuda''' ) __snake_case , __snake_case = pipe_a.encode_prompt('''anime turtle''' , device='''cuda''' ) del pipe_a.tokenizer del pipe_a.text_encoder gc.collect() __snake_case = None __snake_case = None pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # img2img __snake_case = IFImgaImgPipeline(**pipe_a.components ) __snake_case = IFImgaImgSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_imgaimg(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # inpainting __snake_case = IFInpaintingPipeline(**pipe_a.components ) __snake_case = IFInpaintingSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_inpainting(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> int: '''simple docstring''' _start_torch_memory_measurement() __snake_case = torch.Generator(device='''cpu''' ).manual_seed(0 ) __snake_case = pipe_a( prompt_embeds=__SCREAMING_SNAKE_CASE , negative_prompt_embeds=__SCREAMING_SNAKE_CASE , num_inference_steps=2 , generator=__SCREAMING_SNAKE_CASE , output_type='''np''' , ) __snake_case = output.images[0] assert image.shape == (64, 64, 3) __snake_case = torch.cuda.max_memory_allocated() assert mem_bytes < 13 * 10**9 __snake_case = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy''' ) assert_mean_pixel_difference(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # pipeline 2 _start_torch_memory_measurement() __snake_case = torch.Generator(device='''cpu''' ).manual_seed(0 ) __snake_case = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(__SCREAMING_SNAKE_CASE ) __snake_case = pipe_a( prompt_embeds=__SCREAMING_SNAKE_CASE , negative_prompt_embeds=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type='''np''' , ) __snake_case = output.images[0] assert image.shape == (256, 256, 3) __snake_case = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 __snake_case = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> Union[str, Any]: '''simple docstring''' _start_torch_memory_measurement() __snake_case = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(__SCREAMING_SNAKE_CASE ) __snake_case = torch.Generator(device='''cpu''' ).manual_seed(0 ) __snake_case = pipe_a( prompt_embeds=__SCREAMING_SNAKE_CASE , negative_prompt_embeds=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , num_inference_steps=2 , generator=__SCREAMING_SNAKE_CASE , output_type='''np''' , ) __snake_case = output.images[0] assert image.shape == (64, 64, 3) __snake_case = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 __snake_case = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy''' ) assert_mean_pixel_difference(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # pipeline 2 _start_torch_memory_measurement() __snake_case = torch.Generator(device='''cpu''' ).manual_seed(0 ) __snake_case = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(__SCREAMING_SNAKE_CASE ) __snake_case = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(__SCREAMING_SNAKE_CASE ) __snake_case = pipe_a( prompt_embeds=__SCREAMING_SNAKE_CASE , negative_prompt_embeds=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , original_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type='''np''' , ) __snake_case = output.images[0] assert image.shape == (256, 256, 3) __snake_case = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 __snake_case = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> Optional[Any]: '''simple docstring''' _start_torch_memory_measurement() __snake_case = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(__SCREAMING_SNAKE_CASE ) __snake_case = floats_tensor((1, 3, 64, 64) , rng=random.Random(1 ) ).to(__SCREAMING_SNAKE_CASE ) __snake_case = torch.Generator(device='''cpu''' ).manual_seed(0 ) __snake_case = pipe_a( prompt_embeds=__SCREAMING_SNAKE_CASE , negative_prompt_embeds=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , num_inference_steps=2 , generator=__SCREAMING_SNAKE_CASE , output_type='''np''' , ) __snake_case = output.images[0] assert image.shape == (64, 64, 3) __snake_case = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 __snake_case = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy''' ) assert_mean_pixel_difference(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # pipeline 2 _start_torch_memory_measurement() __snake_case = torch.Generator(device='''cpu''' ).manual_seed(0 ) __snake_case = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(__SCREAMING_SNAKE_CASE ) __snake_case = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(__SCREAMING_SNAKE_CASE ) __snake_case = floats_tensor((1, 3, 256, 256) , rng=random.Random(1 ) ).to(__SCREAMING_SNAKE_CASE ) __snake_case = pipe_a( prompt_embeds=__SCREAMING_SNAKE_CASE , negative_prompt_embeds=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , original_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type='''np''' , ) __snake_case = output.images[0] assert image.shape == (256, 256, 3) __snake_case = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 __snake_case = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _UpperCamelCase ()-> List[str]: '''simple docstring''' torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats()
24
import os # Precomputes a list of the 100 first triangular numbers UpperCamelCase = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def _A ( ): """simple docstring""" lowerCAmelCase__ = os.path.dirname(os.path.realpath(lowerCAmelCase_ ) ) lowerCAmelCase__ = os.path.join(lowerCAmelCase_ , "words.txt" ) lowerCAmelCase__ = "" with open(lowerCAmelCase_ ) as f: lowerCAmelCase__ = f.readline() lowerCAmelCase__ = [word.strip("\"" ) for word in words.strip("\r\n" ).split("," )] lowerCAmelCase__ = [ word for word in [sum(ord(lowerCAmelCase_ ) - 64 for x in word ) for word in words] if word in TRIANGULAR_NUMBERS ] return len(lowerCAmelCase_ ) if __name__ == "__main__": print(solution())
61
0
from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar a_ = TypeVar('KEY') a_ = TypeVar('VAL') @dataclass(frozen=__A , slots=__A ) class _UpperCamelCase ( Generic[KEY, VAL] ): '''simple docstring''' lowerCamelCase__ =42 lowerCamelCase__ =42 class _UpperCamelCase ( _Item ): '''simple docstring''' def __init__( self : Dict ) -> None: """simple docstring""" super().__init__(a , a ) def __bool__( self : str ) -> bool: """simple docstring""" return False a_ = _DeletedItem() class _UpperCamelCase ( MutableMapping[KEY, VAL] ): '''simple docstring''' def __init__( self : Union[str, Any] , a : int = 8 , a : float = 0.75 ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE : int = initial_block_size SCREAMING_SNAKE_CASE : list[_Item | None] = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 SCREAMING_SNAKE_CASE : List[str] = capacity_factor SCREAMING_SNAKE_CASE : List[Any] = 0 def __UpperCamelCase ( self : str , a : KEY ) -> int: """simple docstring""" return hash(a ) % len(self._buckets ) def __UpperCamelCase ( self : Optional[Any] , a : int ) -> int: """simple docstring""" return (ind + 1) % len(self._buckets ) def __UpperCamelCase ( self : List[Any] , a : int , a : KEY , a : VAL ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = self._buckets[ind] if not stored: SCREAMING_SNAKE_CASE : int = _Item(a , a ) self._len += 1 return True elif stored.key == key: SCREAMING_SNAKE_CASE : Dict = _Item(a , a ) return True else: return False def __UpperCamelCase ( self : Union[str, Any] ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE : int = len(self._buckets ) * self._capacity_factor return len(self ) >= int(a ) def __UpperCamelCase ( self : Tuple ) -> bool: """simple docstring""" if len(self._buckets ) <= self._initial_block_size: return False SCREAMING_SNAKE_CASE : Optional[int] = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def __UpperCamelCase ( self : Any , a : int ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = self._buckets SCREAMING_SNAKE_CASE : Optional[int] = [None] * new_size SCREAMING_SNAKE_CASE : Dict = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def __UpperCamelCase ( self : Tuple ) -> None: """simple docstring""" self._resize(len(self._buckets ) * 2 ) def __UpperCamelCase ( self : List[str] ) -> None: """simple docstring""" self._resize(len(self._buckets ) // 2 ) def __UpperCamelCase ( self : List[str] , a : KEY ) -> Iterator[int]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self._get_bucket_index(a ) for _ in range(len(self._buckets ) ): yield ind SCREAMING_SNAKE_CASE : int = self._get_next_ind(a ) def __UpperCamelCase ( self : List[Any] , a : KEY , a : VAL ) -> None: """simple docstring""" for ind in self._iterate_buckets(a ): if self._try_set(a , a , a ): break def __setitem__( self : List[str] , a : KEY , a : VAL ) -> None: """simple docstring""" if self._is_full(): self._size_up() self._add_item(a , a ) def __delitem__( self : int , a : KEY ) -> None: """simple docstring""" for ind in self._iterate_buckets(a ): SCREAMING_SNAKE_CASE : List[str] = self._buckets[ind] if item is None: raise KeyError(a ) if item is _deleted: continue if item.key == key: SCREAMING_SNAKE_CASE : int = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self : List[str] , a : KEY ) -> VAL: """simple docstring""" for ind in self._iterate_buckets(a ): SCREAMING_SNAKE_CASE : List[Any] = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(a ) def __len__( self : Optional[Any] ) -> int: """simple docstring""" return self._len def __iter__( self : Any ) -> Iterator[KEY]: """simple docstring""" yield from (item.key for item in self._buckets if item) def __repr__( self : Optional[int] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : int = " ,".join( F"{item.key}: {item.val}" for item in self._buckets if item ) return F"HashMap({val_string})"
25
import random def _A ( lowerCAmelCase_ : Dict , lowerCAmelCase_ : int , lowerCAmelCase_ : Any ): """simple docstring""" lowerCAmelCase__ = a[left_index] lowerCAmelCase__ = left_index + 1 for j in range(left_index + 1 , lowerCAmelCase_ ): if a[j] < pivot: lowerCAmelCase__ , lowerCAmelCase__ = a[i], a[j] i += 1 lowerCAmelCase__ , lowerCAmelCase__ = a[i - 1], a[left_index] return i - 1 def _A ( lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : str ): """simple docstring""" if left < right: lowerCAmelCase__ = random.randint(lowerCAmelCase_ , right - 1 ) lowerCAmelCase__ , lowerCAmelCase__ = ( a[left], a[pivot], ) # switches the pivot with the left most bound lowerCAmelCase__ = partition(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) quick_sort_random( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # recursive quicksort to the left of the pivot point quick_sort_random( lowerCAmelCase_ , pivot_index + 1 , lowerCAmelCase_ ) # recursive quicksort to the right of the pivot point def _A ( ): """simple docstring""" lowerCAmelCase__ = input("Enter numbers separated by a comma:\n" ).strip() lowerCAmelCase__ = [int(lowerCAmelCase_ ) for item in user_input.split("," )] quick_sort_random(lowerCAmelCase_ , 0 , len(lowerCAmelCase_ ) ) print(lowerCAmelCase_ ) if __name__ == "__main__": main()
61
0
'''simple docstring''' import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class _A ( enum.Enum ): lowercase__: Any = 0 lowercase__: Optional[Any] = 1 lowercase__: List[Any] = 2 @add_end_docstrings(__lowercase ) class _A ( __lowercase ): lowercase__: List[Any] = ''' In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision and denounces one of the men as a horse thief. Although his father initially slaps him for making such an accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop, begging for his blessing. <eod> </s> <eos> ''' def __init__( self : int , *__magic_name__ : Tuple , **__magic_name__ : Optional[Any] ) -> Optional[int]: """simple docstring""" super().__init__(*__magic_name__ , **__magic_name__ ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == """tf""" else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. __snake_case : Union[str, Any] = None if self.model.config.prefix is not None: __snake_case : Optional[Any] = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. __snake_case : Union[str, Any] = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. __snake_case , __snake_case , __snake_case : int = self._sanitize_parameters(prefix=__magic_name__ , **self._forward_params ) __snake_case : Optional[Any] = {**self._preprocess_params, **preprocess_params} __snake_case : Dict = {**self._forward_params, **forward_params} def lowercase__ ( self : Optional[Any] , __magic_name__ : Optional[Any]=None , __magic_name__ : Union[str, Any]=None , __magic_name__ : Any=None , __magic_name__ : str=None , __magic_name__ : Dict=None , __magic_name__ : Dict=None , __magic_name__ : Tuple=None , __magic_name__ : Any=None , **__magic_name__ : List[str] , ) -> Any: """simple docstring""" __snake_case : Union[str, Any] = {} if prefix is not None: __snake_case : Tuple = prefix if prefix: __snake_case : List[str] = self.tokenizer( __magic_name__ , padding=__magic_name__ , add_special_tokens=__magic_name__ , return_tensors=self.framework ) __snake_case : Optional[int] = prefix_inputs["""input_ids"""].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( f'''{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected''' """ [None, 'hole']""" ) __snake_case : Optional[Any] = handle_long_generation preprocess_params.update(__magic_name__ ) __snake_case : Dict = generate_kwargs __snake_case : List[Any] = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_full_text`""" ) if return_tensors is not None: raise ValueError("""`return_full_text` is mutually exclusive with `return_tensors`""" ) __snake_case : Union[str, Any] = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_tensors`""" ) __snake_case : Union[str, Any] = ReturnType.TENSORS if return_type is not None: __snake_case : Dict = return_type if clean_up_tokenization_spaces is not None: __snake_case : Any = clean_up_tokenization_spaces if stop_sequence is not None: __snake_case : List[str] = self.tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) if len(__magic_name__ ) > 1: warnings.warn( """Stopping on a multiple token sequence is not yet supported on transformers. The first token of""" """ the stop sequence will be used as the stop sequence string in the interim.""" ) __snake_case : Union[str, Any] = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def lowercase__ ( self : str , *__magic_name__ : Optional[int] , **__magic_name__ : int ) -> int: """simple docstring""" if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({"""add_space_before_punct_symbol""": True} ) return super()._parse_and_tokenize(*__magic_name__ , **__magic_name__ ) def __call__( self : int , __magic_name__ : List[str] , **__magic_name__ : Optional[int] ) -> Dict: """simple docstring""" return super().__call__(__magic_name__ , **__magic_name__ ) def lowercase__ ( self : Tuple , __magic_name__ : int , __magic_name__ : List[str]="" , __magic_name__ : List[str]=None , **__magic_name__ : str ) -> str: """simple docstring""" __snake_case : Optional[int] = self.tokenizer( prefix + prompt_text , padding=__magic_name__ , add_special_tokens=__magic_name__ , return_tensors=self.framework ) __snake_case : Optional[int] = prompt_text if handle_long_generation == "hole": __snake_case : List[str] = inputs["""input_ids"""].shape[-1] if "max_new_tokens" in generate_kwargs: __snake_case : List[Any] = generate_kwargs["""max_new_tokens"""] else: __snake_case : Tuple = generate_kwargs.get("""max_length""" , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError("""We cannot infer how many new tokens are expected""" ) if cur_len + new_tokens > self.tokenizer.model_max_length: __snake_case : str = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( """We cannot use `hole` to handle this generation the number of desired tokens exceeds the""" """ models max length""" ) __snake_case : Dict = inputs["""input_ids"""][:, -keep_length:] if "attention_mask" in inputs: __snake_case : int = inputs["""attention_mask"""][:, -keep_length:] return inputs def lowercase__ ( self : List[Any] , __magic_name__ : List[Any] , **__magic_name__ : Optional[int] ) -> Any: """simple docstring""" __snake_case : Any = model_inputs["""input_ids"""] __snake_case : List[Any] = model_inputs.get("""attention_mask""" , __magic_name__ ) # Allow empty prompts if input_ids.shape[1] == 0: __snake_case : List[str] = None __snake_case : Optional[int] = None __snake_case : List[str] = 1 else: __snake_case : Optional[int] = input_ids.shape[0] __snake_case : Union[str, Any] = model_inputs.pop("""prompt_text""" ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. __snake_case : Tuple = generate_kwargs.pop("""prefix_length""" , 0 ) if prefix_length > 0: __snake_case : str = """max_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].max_new_tokens is not None ) if not has_max_new_tokens: __snake_case : List[str] = generate_kwargs.get("""max_length""" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length __snake_case : Dict = """min_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL __snake_case : Any = self.model.generate(input_ids=__magic_name__ , attention_mask=__magic_name__ , **__magic_name__ ) __snake_case : Any = generated_sequence.shape[0] if self.framework == "pt": __snake_case : List[str] = generated_sequence.reshape(__magic_name__ , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": __snake_case : List[Any] = tf.reshape(__magic_name__ , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def lowercase__ ( self : Dict , __magic_name__ : List[str] , __magic_name__ : Any=ReturnType.FULL_TEXT , __magic_name__ : str=True ) -> Tuple: """simple docstring""" __snake_case : List[Any] = model_outputs["""generated_sequence"""][0] __snake_case : Union[str, Any] = model_outputs["""input_ids"""] __snake_case : str = model_outputs["""prompt_text"""] __snake_case : List[Any] = generated_sequence.numpy().tolist() __snake_case : str = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: __snake_case : Tuple = {"""generated_token_ids""": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text __snake_case : Tuple = self.tokenizer.decode( __magic_name__ , skip_special_tokens=__magic_name__ , clean_up_tokenization_spaces=__magic_name__ , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: __snake_case : List[str] = 0 else: __snake_case : Tuple = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=__magic_name__ , clean_up_tokenization_spaces=__magic_name__ , ) ) if return_type == ReturnType.FULL_TEXT: __snake_case : List[str] = prompt_text + text[prompt_length:] else: __snake_case : Dict = text[prompt_length:] __snake_case : Union[str, Any] = {"""generated_text""": all_text} records.append(__magic_name__ ) return records
26
import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process UpperCamelCase = logging.getLogger(__name__) @dataclass class __lowerCamelCase : """simple docstring""" snake_case__ = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) snake_case__ = field( default="NER" , metadata={"help": "Task type to fine tune in training (e.g. NER, POS, etc)"} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) snake_case__ = field(default=UpperCamelCase__ , metadata={"help": "Set this flag to use fast tokenization."} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) @dataclass class __lowerCamelCase : """simple docstring""" snake_case__ = field( metadata={"help": "The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."} , ) snake_case__ = field( default=1_2_8 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Overwrite the cached training and evaluation sets"} ) def _A ( ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. Use' " --overwrite_output_dir to overcome." ) lowerCAmelCase__ = import_module("tasks" ) try: lowerCAmelCase__ = getattr(lowerCAmelCase_ , model_args.task_type ) lowerCAmelCase__ = token_classification_task_clazz() except AttributeError: raise ValueError( F'Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. ' F'Available tasks classes are: {TokenClassificationTask.__subclasses__()}' ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("Training/evaluation parameters %s" , lowerCAmelCase_ ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task lowerCAmelCase__ = token_classification_task.get_labels(data_args.labels ) lowerCAmelCase__ = dict(enumerate(lowerCAmelCase_ ) ) lowerCAmelCase__ = len(lowerCAmelCase_ ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowerCAmelCase__ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=lowerCAmelCase_ , idalabel=lowerCAmelCase_ , labelaid={label: i for i, label in enumerate(lowerCAmelCase_ )} , cache_dir=model_args.cache_dir , ) lowerCAmelCase__ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast , ) lowerCAmelCase__ = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , ) # Get datasets lowerCAmelCase__ = ( TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) lowerCAmelCase__ = ( TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def align_predictions(lowerCAmelCase_ : np.ndarray , lowerCAmelCase_ : np.ndarray ) -> Tuple[List[int], List[int]]: lowerCAmelCase__ = np.argmax(lowerCAmelCase_ , axis=2 ) lowerCAmelCase__ , lowerCAmelCase__ = preds.shape lowerCAmelCase__ = [[] for _ in range(lowerCAmelCase_ )] lowerCAmelCase__ = [[] for _ in range(lowerCAmelCase_ )] for i in range(lowerCAmelCase_ ): for j in range(lowerCAmelCase_ ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(lowerCAmelCase_ : EvalPrediction ) -> Dict: lowerCAmelCase__ , lowerCAmelCase__ = align_predictions(p.predictions , p.label_ids ) return { "accuracy_score": accuracy_score(lowerCAmelCase_ , lowerCAmelCase_ ), "precision": precision_score(lowerCAmelCase_ , lowerCAmelCase_ ), "recall": recall_score(lowerCAmelCase_ , lowerCAmelCase_ ), "f1": fa_score(lowerCAmelCase_ , lowerCAmelCase_ ), } # Data collator lowerCAmelCase__ = DataCollatorWithPadding(lowerCAmelCase_ , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer lowerCAmelCase__ = Trainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , train_dataset=lowerCAmelCase_ , eval_dataset=lowerCAmelCase_ , compute_metrics=lowerCAmelCase_ , data_collator=lowerCAmelCase_ , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation lowerCAmelCase__ = {} if training_args.do_eval: logger.info("*** Evaluate ***" ) lowerCAmelCase__ = trainer.evaluate() lowerCAmelCase__ = os.path.join(training_args.output_dir , "eval_results.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: logger.info("***** Eval results *****" ) for key, value in result.items(): logger.info(" %s = %s" , lowerCAmelCase_ , lowerCAmelCase_ ) writer.write("%s = %s\n" % (key, value) ) results.update(lowerCAmelCase_ ) # Predict if training_args.do_predict: lowerCAmelCase__ = TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = trainer.predict(lowerCAmelCase_ ) lowerCAmelCase__ , lowerCAmelCase__ = align_predictions(lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ = os.path.join(training_args.output_dir , "test_results.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: for key, value in metrics.items(): logger.info(" %s = %s" , lowerCAmelCase_ , lowerCAmelCase_ ) writer.write("%s = %s\n" % (key, value) ) # Save predictions lowerCAmelCase__ = os.path.join(training_args.output_dir , "test_predictions.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: with open(os.path.join(data_args.data_dir , "test.txt" ) , "r" ) as f: token_classification_task.write_predictions_to_file(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return results def _A ( lowerCAmelCase_ : Tuple ): """simple docstring""" main() if __name__ == "__main__": main()
61
0
from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin from .unet_ad_blocks import get_down_block, get_mid_block, get_out_block, get_up_block @dataclass class lowerCamelCase( __snake_case ): '''simple docstring''' __magic_name__ = 42 class lowerCamelCase( __snake_case , __snake_case ): '''simple docstring''' @register_to_config def __init__( self , snake_case_ = 6_5536 , snake_case_ = None , snake_case_ = 2 , snake_case_ = 2 , snake_case_ = 0 , snake_case_ = "fourier" , snake_case_ = True , snake_case_ = False , snake_case_ = 0.0 , snake_case_ = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D") , snake_case_ = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip") , snake_case_ = "UNetMidBlock1D" , snake_case_ = None , snake_case_ = (32, 32, 64) , snake_case_ = None , snake_case_ = 8 , snake_case_ = 1 , snake_case_ = False , ): super().__init__() _A = sample_size # time if time_embedding_type == "fourier": _A = GaussianFourierProjection( embedding_size=8 , set_W_to_weight=snake_case_ , log=snake_case_ , flip_sin_to_cos=snake_case_ ) _A = 2 * block_out_channels[0] elif time_embedding_type == "positional": _A = Timesteps( block_out_channels[0] , flip_sin_to_cos=snake_case_ , downscale_freq_shift=snake_case_ ) _A = block_out_channels[0] if use_timestep_embedding: _A = block_out_channels[0] * 4 _A = TimestepEmbedding( in_channels=snake_case_ , time_embed_dim=snake_case_ , act_fn=snake_case_ , out_dim=block_out_channels[0] , ) _A = nn.ModuleList([] ) _A = None _A = nn.ModuleList([] ) _A = None # down _A = in_channels for i, down_block_type in enumerate(snake_case_ ): _A = output_channel _A = block_out_channels[i] if i == 0: input_channel += extra_in_channels _A = i == len(snake_case_ ) - 1 _A = get_down_block( snake_case_ , num_layers=snake_case_ , in_channels=snake_case_ , out_channels=snake_case_ , temb_channels=block_out_channels[0] , add_downsample=not is_final_block or downsample_each_block , ) self.down_blocks.append(snake_case_ ) # mid _A = get_mid_block( snake_case_ , in_channels=block_out_channels[-1] , mid_channels=block_out_channels[-1] , out_channels=block_out_channels[-1] , embed_dim=block_out_channels[0] , num_layers=snake_case_ , add_downsample=snake_case_ , ) # up _A = list(reversed(snake_case_ ) ) _A = reversed_block_out_channels[0] if out_block_type is None: _A = out_channels else: _A = block_out_channels[0] for i, up_block_type in enumerate(snake_case_ ): _A = output_channel _A = ( reversed_block_out_channels[i + 1] if i < len(snake_case_ ) - 1 else final_upsample_channels ) _A = i == len(snake_case_ ) - 1 _A = get_up_block( snake_case_ , num_layers=snake_case_ , in_channels=snake_case_ , out_channels=snake_case_ , temb_channels=block_out_channels[0] , add_upsample=not is_final_block , ) self.up_blocks.append(snake_case_ ) _A = output_channel # out _A = norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4 , 32 ) _A = get_out_block( out_block_type=snake_case_ , num_groups_out=snake_case_ , embed_dim=block_out_channels[0] , out_channels=snake_case_ , act_fn=snake_case_ , fc_dim=block_out_channels[-1] // 4 , ) def lowerCAmelCase__ ( self , snake_case_ , snake_case_ , snake_case_ = True , ): _A = timestep if not torch.is_tensor(snake_case_ ): _A = torch.tensor([timesteps] , dtype=torch.long , device=sample.device ) elif torch.is_tensor(snake_case_ ) and len(timesteps.shape ) == 0: _A = timesteps[None].to(sample.device ) _A = self.time_proj(snake_case_ ) if self.config.use_timestep_embedding: _A = self.time_mlp(snake_case_ ) else: _A = timestep_embed[..., None] _A = timestep_embed.repeat([1, 1, sample.shape[2]] ).to(sample.dtype ) _A = timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:]) ) # 2. down _A = () for downsample_block in self.down_blocks: _A, _A = downsample_block(hidden_states=snake_case_ , temb=snake_case_ ) down_block_res_samples += res_samples # 3. mid if self.mid_block: _A = self.mid_block(snake_case_ , snake_case_ ) # 4. up for i, upsample_block in enumerate(self.up_blocks ): _A = down_block_res_samples[-1:] _A = down_block_res_samples[:-1] _A = upsample_block(snake_case_ , res_hidden_states_tuple=snake_case_ , temb=snake_case_ ) # 5. post-process if self.out_block: _A = self.out_block(snake_case_ , snake_case_ ) if not return_dict: return (sample,) return UNetaDOutput(sample=snake_case_ )
27
import os import re from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'vocab_file': 'spiece.model'} UpperCamelCase = { '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' ), } } UpperCamelCase = { 'google/bigbird-roberta-base': 4096, 'google/bigbird-roberta-large': 4096, 'google/bigbird-base-trivia-itc': 4096, } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ = ["input_ids", "attention_mask"] snake_case__ = [] def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str]="<unk>" , SCREAMING_SNAKE_CASE__ : List[str]="<s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="</s>" , SCREAMING_SNAKE_CASE__ : Tuple="<pad>" , SCREAMING_SNAKE_CASE__ : Any="[SEP]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[MASK]" , SCREAMING_SNAKE_CASE__ : List[Any]="[CLS]" , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None , **SCREAMING_SNAKE_CASE__ : List[Any] , ) -> None: lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else bos_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else eos_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else unk_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else pad_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cls_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else sep_token # Mask token behave like a normal word, i.e. include the space before it lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else mask_token lowerCAmelCase__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = vocab_file lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def a ( self : List[str] ) -> List[str]: return self.sp_model.get_piece_size() def a ( self : List[str] ) -> Dict: lowerCAmelCase__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Optional[int] ) -> Any: lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Any: lowerCAmelCase__ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowerCAmelCase__ = {} lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: return self.sp_model.piece_to_id(SCREAMING_SNAKE_CASE__ ) def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[str]: lowerCAmelCase__ = self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) return token def a ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: lowerCAmelCase__ = [] lowerCAmelCase__ = "" lowerCAmelCase__ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) + token lowerCAmelCase__ = True lowerCAmelCase__ = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) return out_string.strip() def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : bool = True , **SCREAMING_SNAKE_CASE__ : int , ) -> str: lowerCAmelCase__ = kwargs.pop("use_source_tokenizer" , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 lowerCAmelCase__ = [] lowerCAmelCase__ = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = [] sub_texts.append(SCREAMING_SNAKE_CASE__ ) else: current_sub_text.append(SCREAMING_SNAKE_CASE__ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) ) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: lowerCAmelCase__ = re.sub(r" (\[(MASK|SEP)\])" , r"\1" , " ".join(SCREAMING_SNAKE_CASE__ ) ) else: lowerCAmelCase__ = "".join(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: lowerCAmelCase__ = self.clean_up_tokenization(SCREAMING_SNAKE_CASE__ ) return clean_text else: return text def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return lowerCAmelCase__ = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE__ , "wb" ) as fi: lowerCAmelCase__ = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,) def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] lowerCAmelCase__ = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
61
0
'''simple docstring''' import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def lowercase__( __UpperCamelCase: Dict ): """simple docstring""" SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = image.size SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 SCREAMING_SNAKE_CASE : Optional[int] = image.resize((w, h) ,resample=PIL_INTERPOLATION['lanczos'] ) SCREAMING_SNAKE_CASE : Optional[Any] = np.array(__UpperCamelCase ).astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE : int = image[None].transpose(0 ,3 ,1 ,2 ) SCREAMING_SNAKE_CASE : int = torch.from_numpy(__UpperCamelCase ) return 2.0 * image - 1.0 class _a ( SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self, A, A, A, ): '''simple docstring''' super().__init__() self.register_modules(vqvae=A, unet=A, scheduler=A ) @torch.no_grad() def __call__( self, A = None, A = 1, A = 100, A = 0.0, A = None, A = "pil", A = True, ): '''simple docstring''' if isinstance(A, PIL.Image.Image ): SCREAMING_SNAKE_CASE : int = 1 elif isinstance(A, torch.Tensor ): SCREAMING_SNAKE_CASE : Optional[Any] = image.shape[0] else: raise ValueError(F"`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(A )}" ) if isinstance(A, PIL.Image.Image ): SCREAMING_SNAKE_CASE : List[str] = preprocess(A ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image SCREAMING_SNAKE_CASE : Tuple = (batch_size, self.unet.config.in_channels // 2, height, width) SCREAMING_SNAKE_CASE : Any = next(self.unet.parameters() ).dtype SCREAMING_SNAKE_CASE : int = randn_tensor(A, generator=A, device=self.device, dtype=A ) SCREAMING_SNAKE_CASE : Optional[Any] = image.to(device=self.device, dtype=A ) # set timesteps and move to the correct device self.scheduler.set_timesteps(A, device=self.device ) SCREAMING_SNAKE_CASE : str = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler SCREAMING_SNAKE_CASE : List[Any] = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] SCREAMING_SNAKE_CASE : str = 'eta' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) SCREAMING_SNAKE_CASE : Tuple = {} if accepts_eta: SCREAMING_SNAKE_CASE : Any = eta for t in self.progress_bar(A ): # concat latents and low resolution image in the channel dimension. SCREAMING_SNAKE_CASE : List[str] = torch.cat([latents, image], dim=1 ) SCREAMING_SNAKE_CASE : int = self.scheduler.scale_model_input(A, A ) # predict the noise residual SCREAMING_SNAKE_CASE : List[str] = self.unet(A, A ).sample # compute the previous noisy sample x_t -> x_t-1 SCREAMING_SNAKE_CASE : str = self.scheduler.step(A, A, A, **A ).prev_sample # decode the image latents with the VQVAE SCREAMING_SNAKE_CASE : Dict = self.vqvae.decode(A ).sample SCREAMING_SNAKE_CASE : Dict = torch.clamp(A, -1.0, 1.0 ) SCREAMING_SNAKE_CASE : str = image / 2 + 0.5 SCREAMING_SNAKE_CASE : List[str] = image.cpu().permute(0, 2, 3, 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE : Union[str, Any] = self.numpy_to_pil(A ) if not return_dict: return (image,) return ImagePipelineOutput(images=A )
28
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { 'sayakpaul/vit-msn-base': 'https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json', # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "vit_msn" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple=768 , SCREAMING_SNAKE_CASE__ : Optional[Any]=12 , SCREAMING_SNAKE_CASE__ : List[str]=12 , SCREAMING_SNAKE_CASE__ : Dict=3_072 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.0 , SCREAMING_SNAKE_CASE__ : int=0.0 , SCREAMING_SNAKE_CASE__ : List[str]=0.02 , SCREAMING_SNAKE_CASE__ : List[str]=1e-0_6 , SCREAMING_SNAKE_CASE__ : Dict=224 , SCREAMING_SNAKE_CASE__ : Optional[int]=16 , SCREAMING_SNAKE_CASE__ : Dict=3 , SCREAMING_SNAKE_CASE__ : Dict=True , **SCREAMING_SNAKE_CASE__ : Tuple , ) -> int: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = initializer_range lowerCAmelCase__ = layer_norm_eps lowerCAmelCase__ = image_size lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = qkv_bias
61
0
"""simple docstring""" import shutil import tempfile import unittest import numpy as np import pytest from transformers import is_speech_available, is_vision_available from transformers.testing_utils import require_torch if is_vision_available(): from transformers import TvltImageProcessor if is_speech_available(): from transformers import TvltFeatureExtractor from transformers import TvltProcessor @require_torch class __lowerCamelCase ( unittest.TestCase ): def UpperCAmelCase__ ( self ): lowerCamelCase_ = '''ZinengTang/tvlt-base''' lowerCamelCase_ = tempfile.mkdtemp() def UpperCAmelCase__ ( self , **UpperCAmelCase ): return TvltImageProcessor.from_pretrained(self.checkpoint , **UpperCAmelCase ) def UpperCAmelCase__ ( self , **UpperCAmelCase ): return TvltFeatureExtractor.from_pretrained(self.checkpoint , **UpperCAmelCase ) def UpperCAmelCase__ ( self ): shutil.rmtree(self.tmpdirname ) def UpperCAmelCase__ ( self ): lowerCamelCase_ = self.get_image_processor() lowerCamelCase_ = self.get_feature_extractor() lowerCamelCase_ = TvltProcessor(image_processor=UpperCAmelCase , feature_extractor=UpperCAmelCase ) processor.save_pretrained(self.tmpdirname ) lowerCamelCase_ = TvltProcessor.from_pretrained(self.tmpdirname ) self.assertIsInstance(processor.feature_extractor , UpperCAmelCase ) self.assertIsInstance(processor.image_processor , UpperCAmelCase ) def UpperCAmelCase__ ( self ): lowerCamelCase_ = self.get_image_processor() lowerCamelCase_ = self.get_feature_extractor() lowerCamelCase_ = TvltProcessor(image_processor=UpperCAmelCase , feature_extractor=UpperCAmelCase ) lowerCamelCase_ = np.ones([1_2000] ) lowerCamelCase_ = feature_extractor(UpperCAmelCase , return_tensors='''np''' ) lowerCamelCase_ = processor(audio=UpperCAmelCase , return_tensors='''np''' ) for key in audio_dict.keys(): self.assertAlmostEqual(audio_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCAmelCase__ ( self ): lowerCamelCase_ = self.get_image_processor() lowerCamelCase_ = self.get_feature_extractor() lowerCamelCase_ = TvltProcessor(image_processor=UpperCAmelCase , feature_extractor=UpperCAmelCase ) lowerCamelCase_ = np.ones([3, 224, 224] ) lowerCamelCase_ = image_processor(UpperCAmelCase , return_tensors='''np''' ) lowerCamelCase_ = processor(images=UpperCAmelCase , return_tensors='''np''' ) for key in image_dict.keys(): self.assertAlmostEqual(image_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCAmelCase__ ( self ): lowerCamelCase_ = self.get_image_processor() lowerCamelCase_ = self.get_feature_extractor() lowerCamelCase_ = TvltProcessor(image_processor=UpperCAmelCase , feature_extractor=UpperCAmelCase ) lowerCamelCase_ = np.ones([1_2000] ) lowerCamelCase_ = np.ones([3, 224, 224] ) lowerCamelCase_ = processor(audio=UpperCAmelCase , images=UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , ['''audio_values''', '''audio_mask''', '''pixel_values''', '''pixel_mask'''] ) # test if it raises when no input is passed with pytest.raises(UpperCAmelCase ): processor() def UpperCAmelCase__ ( self ): lowerCamelCase_ = self.get_image_processor() lowerCamelCase_ = self.get_feature_extractor() lowerCamelCase_ = TvltProcessor(image_processor=UpperCAmelCase , feature_extractor=UpperCAmelCase ) self.assertListEqual( processor.model_input_names , image_processor.model_input_names + feature_extractor.model_input_names , msg='''`processor` and `image_processor`+`feature_extractor` model input names do not match''' , )
29
import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def __init__( self : List[Any] , *SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> None: warnings.warn( "The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use FlavaImageProcessor instead." , SCREAMING_SNAKE_CASE__ , ) super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
61
0
import importlib import os from dataclasses import dataclass from enum import Enum from typing import Any, Dict, Optional, Union import torch from ..utils import BaseOutput __a = 'scheduler_config.json' class __a( _a ): """simple docstring""" lowerCAmelCase = 1 lowerCAmelCase = 2 lowerCAmelCase = 3 lowerCAmelCase = 4 lowerCAmelCase = 5 lowerCAmelCase = 6 lowerCAmelCase = 7 lowerCAmelCase = 8 lowerCAmelCase = 9 lowerCAmelCase = 10 lowerCAmelCase = 11 lowerCAmelCase = 12 lowerCAmelCase = 13 lowerCAmelCase = 14 @dataclass class __a( _a ): """simple docstring""" lowerCAmelCase = 42 class __a: """simple docstring""" lowerCAmelCase = SCHEDULER_CONFIG_NAME lowerCAmelCase = [] lowerCAmelCase = True @classmethod def a__ ( cls ,_SCREAMING_SNAKE_CASE = None ,_SCREAMING_SNAKE_CASE = None ,_SCREAMING_SNAKE_CASE=False ,**_SCREAMING_SNAKE_CASE ,) -> List[str]: UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_ : str = cls.load_config( pretrained_model_name_or_path=_SCREAMING_SNAKE_CASE ,subfolder=_SCREAMING_SNAKE_CASE ,return_unused_kwargs=_SCREAMING_SNAKE_CASE ,return_commit_hash=_SCREAMING_SNAKE_CASE ,**_SCREAMING_SNAKE_CASE ,) return cls.from_config(_SCREAMING_SNAKE_CASE ,return_unused_kwargs=_SCREAMING_SNAKE_CASE ,**_SCREAMING_SNAKE_CASE ) def a__ ( self ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE = False ,**_SCREAMING_SNAKE_CASE ) -> Dict: self.save_config(save_directory=_SCREAMING_SNAKE_CASE ,push_to_hub=_SCREAMING_SNAKE_CASE ,**_SCREAMING_SNAKE_CASE ) @property def a__ ( self ) -> Tuple: return self._get_compatibles() @classmethod def a__ ( cls ) -> Optional[Any]: UpperCAmelCase_ : int = list(set([cls.__name__] + cls._compatibles ) ) UpperCAmelCase_ : int = importlib.import_module(__name__.split('''.''' )[0] ) UpperCAmelCase_ : Any = [ getattr(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) for c in compatible_classes_str if hasattr(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) ] return compatible_classes
30
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import ( BaseOutput, OptionalDependencyNotAvailable, is_flax_available, is_k_diffusion_available, is_k_diffusion_version, is_onnx_available, is_torch_available, is_transformers_available, is_transformers_version, ) @dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_cycle_diffusion import CycleDiffusionPipeline from .pipeline_stable_diffusion import StableDiffusionPipeline from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from .pipeline_stable_unclip import StableUnCLIPPipeline from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline from .safety_checker import StableDiffusionSafetyChecker from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.25.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline else: from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.26.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionPixaPixZeroPipeline, ) else: from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline try: if not ( is_torch_available() and is_transformers_available() and is_k_diffusion_available() and is_k_diffusion_version('>=', '0.0.12') ): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline try: if not (is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_onnx_objects import * # noqa F403 else: from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline if is_transformers_available() and is_flax_available(): import flax @flax.struct.dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline from .safety_checker_flax import FlaxStableDiffusionSafetyChecker
61
0
import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class lowerCamelCase_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : str , _lowerCAmelCase : str , _lowerCAmelCase : Optional[int]=7 , _lowerCAmelCase : Optional[Any]=3 , _lowerCAmelCase : List[Any]=18 , _lowerCAmelCase : List[str]=30 , _lowerCAmelCase : Tuple=400 , _lowerCAmelCase : int=True , _lowerCAmelCase : Optional[int]=None , _lowerCAmelCase : str=True , ): SCREAMING_SNAKE_CASE_ = size if size is not None else {'height': 18, 'width': 18} SCREAMING_SNAKE_CASE_ = parent SCREAMING_SNAKE_CASE_ = batch_size SCREAMING_SNAKE_CASE_ = num_channels SCREAMING_SNAKE_CASE_ = image_size SCREAMING_SNAKE_CASE_ = min_resolution SCREAMING_SNAKE_CASE_ = max_resolution SCREAMING_SNAKE_CASE_ = do_resize SCREAMING_SNAKE_CASE_ = size SCREAMING_SNAKE_CASE_ = apply_ocr def lowerCAmelCase_ ( self : Optional[Any] ): return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class lowerCamelCase_ ( _SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowercase_ = LayoutLMvaImageProcessor if is_pytesseract_available() else None def lowerCAmelCase_ ( self : Tuple ): SCREAMING_SNAKE_CASE_ = LayoutLMvaImageProcessingTester(self ) @property def lowerCAmelCase_ ( self : List[Any] ): return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase_ ( self : List[str] ): SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCAmelCase , 'do_resize' ) ) self.assertTrue(hasattr(_lowerCAmelCase , 'size' ) ) self.assertTrue(hasattr(_lowerCAmelCase , 'apply_ocr' ) ) def lowerCAmelCase_ ( self : str ): SCREAMING_SNAKE_CASE_ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 18, 'width': 18} ) SCREAMING_SNAKE_CASE_ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {'height': 42, 'width': 42} ) def lowerCAmelCase_ ( self : Optional[Any] ): pass def lowerCAmelCase_ ( self : Any ): # Initialize image_processing SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(_lowerCAmelCase , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE_ = image_processing(image_inputs[0] , return_tensors='pt' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) self.assertIsInstance(encoding.words , _lowerCAmelCase ) self.assertIsInstance(encoding.boxes , _lowerCAmelCase ) # Test batched SCREAMING_SNAKE_CASE_ = image_processing(_lowerCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def lowerCAmelCase_ ( self : int ): # Initialize image_processing SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCAmelCase , numpify=_lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(_lowerCAmelCase , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE_ = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched SCREAMING_SNAKE_CASE_ = image_processing(_lowerCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def lowerCAmelCase_ ( self : Optional[Any] ): # Initialize image_processing SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCAmelCase , torchify=_lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(_lowerCAmelCase , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE_ = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched SCREAMING_SNAKE_CASE_ = image_processing(_lowerCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def lowerCAmelCase_ ( self : List[str] ): # with apply_OCR = True SCREAMING_SNAKE_CASE_ = LayoutLMvaImageProcessor() from datasets import load_dataset SCREAMING_SNAKE_CASE_ = load_dataset('hf-internal-testing/fixtures_docvqa' , split='test' ) SCREAMING_SNAKE_CASE_ = Image.open(ds[0]['file'] ).convert('RGB' ) SCREAMING_SNAKE_CASE_ = image_processing(_lowerCAmelCase , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 SCREAMING_SNAKE_CASE_ = [['11:14', 'to', '11:39', 'a.m', '11:39', 'to', '11:44', 'a.m.', '11:44', 'a.m.', 'to', '12:25', 'p.m.', '12:25', 'to', '12:58', 'p.m.', '12:58', 'to', '4:00', 'p.m.', '2:00', 'to', '5:00', 'p.m.', 'Coffee', 'Break', 'Coffee', 'will', 'be', 'served', 'for', 'men', 'and', 'women', 'in', 'the', 'lobby', 'adjacent', 'to', 'exhibit', 'area.', 'Please', 'move', 'into', 'exhibit', 'area.', '(Exhibits', 'Open)', 'TRRF', 'GENERAL', 'SESSION', '(PART', '|)', 'Presiding:', 'Lee', 'A.', 'Waller', 'TRRF', 'Vice', 'President', '“Introductory', 'Remarks”', 'Lee', 'A.', 'Waller,', 'TRRF', 'Vice', 'Presi-', 'dent', 'Individual', 'Interviews', 'with', 'TRRF', 'Public', 'Board', 'Members', 'and', 'Sci-', 'entific', 'Advisory', 'Council', 'Mem-', 'bers', 'Conducted', 'by', 'TRRF', 'Treasurer', 'Philip', 'G.', 'Kuehn', 'to', 'get', 'answers', 'which', 'the', 'public', 'refrigerated', 'warehousing', 'industry', 'is', 'looking', 'for.', 'Plus', 'questions', 'from', 'the', 'floor.', 'Dr.', 'Emil', 'M.', 'Mrak,', 'University', 'of', 'Cal-', 'ifornia,', 'Chairman,', 'TRRF', 'Board;', 'Sam', 'R.', 'Cecil,', 'University', 'of', 'Georgia', 'College', 'of', 'Agriculture;', 'Dr.', 'Stanley', 'Charm,', 'Tufts', 'University', 'School', 'of', 'Medicine;', 'Dr.', 'Robert', 'H.', 'Cotton,', 'ITT', 'Continental', 'Baking', 'Company;', 'Dr.', 'Owen', 'Fennema,', 'University', 'of', 'Wis-', 'consin;', 'Dr.', 'Robert', 'E.', 'Hardenburg,', 'USDA.', 'Questions', 'and', 'Answers', 'Exhibits', 'Open', 'Capt.', 'Jack', 'Stoney', 'Room', 'TRRF', 'Scientific', 'Advisory', 'Council', 'Meeting', 'Ballroom', 'Foyer']] # noqa: E231 SCREAMING_SNAKE_CASE_ = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , _lowerCAmelCase ) self.assertListEqual(encoding.boxes , _lowerCAmelCase ) # with apply_OCR = False SCREAMING_SNAKE_CASE_ = LayoutLMvaImageProcessor(apply_ocr=_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = image_processing(_lowerCAmelCase , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
31
def _A ( lowerCAmelCase_ : int ): """simple docstring""" if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("'float' object cannot be interpreted as an integer" ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("'str' object cannot be interpreted as an integer" ) if num == 0: return "0b0" lowerCAmelCase__ = False if num < 0: lowerCAmelCase__ = True lowerCAmelCase__ = -num lowerCAmelCase__ = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(lowerCAmelCase_ ) for e in binary ) return "0b" + "".join(str(lowerCAmelCase_ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
61
0
from __future__ import annotations def A__ ( SCREAMING_SNAKE_CASE_ : list[int] ) -> int: """simple docstring""" if not nums: return 0 _UpperCAmelCase = nums[0] _UpperCAmelCase = 0 for num in nums[1:]: _UpperCAmelCase , _UpperCAmelCase = ( max_excluding + num, max(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ), ) return max(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": import doctest doctest.testmod()
32
from __future__ import annotations UpperCamelCase = '#' class __lowerCamelCase : """simple docstring""" def __init__( self : Dict ) -> None: lowerCAmelCase__ = {} def a ( self : Any , SCREAMING_SNAKE_CASE__ : str ) -> None: lowerCAmelCase__ = self._trie for char in text: if char not in trie: lowerCAmelCase__ = {} lowerCAmelCase__ = trie[char] lowerCAmelCase__ = True def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : str ) -> tuple | list: lowerCAmelCase__ = self._trie for char in prefix: if char in trie: lowerCAmelCase__ = trie[char] else: return [] return self._elements(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : dict ) -> tuple: lowerCAmelCase__ = [] for c, v in d.items(): lowerCAmelCase__ = [" "] if c == END else [(c + s) for s in self._elements(SCREAMING_SNAKE_CASE__ )] result.extend(SCREAMING_SNAKE_CASE__ ) return tuple(SCREAMING_SNAKE_CASE__ ) UpperCamelCase = Trie() UpperCamelCase = ('depart', 'detergent', 'daring', 'dog', 'deer', 'deal') for word in words: trie.insert_word(word) def _A ( lowerCAmelCase_ : str ): """simple docstring""" lowerCAmelCase__ = trie.find_word(lowerCAmelCase_ ) return tuple(string + word for word in suffixes ) def _A ( ): """simple docstring""" print(autocomplete_using_trie("de" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
61
0
lowerCamelCase__ : List[str] = """Alexander Joslin""" import operator as op from .stack import Stack def SCREAMING_SNAKE_CASE ( __lowerCAmelCase ) -> int: snake_case__ = {'''*''': op.mul, '''/''': op.truediv, '''+''': op.add, '''-''': op.sub} snake_case__ = Stack() snake_case__ = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(__lowerCAmelCase ) ) elif i in operators: # RULE 2 operator_stack.push(__lowerCAmelCase ) elif i == ")": # RULE 4 snake_case__ = operator_stack.peek() operator_stack.pop() snake_case__ = operand_stack.peek() operand_stack.pop() snake_case__ = operand_stack.peek() operand_stack.pop() snake_case__ = operators[opr](__lowerCAmelCase , __lowerCAmelCase ) operand_stack.push(__lowerCAmelCase ) # RULE 5 return operand_stack.peek() if __name__ == "__main__": lowerCamelCase__ : Optional[Any] = """(5 + ((4 * 2) * (2 + 3)))""" # answer = 45 print(F"""{equation} = {dijkstras_two_stack_algorithm(equation)}""")
33
import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, TimesformerForVideoClassification, TimesformerModel, ) from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class __lowerCamelCase : """simple docstring""" def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple=13 , SCREAMING_SNAKE_CASE__ : Optional[Any]=10 , SCREAMING_SNAKE_CASE__ : Optional[int]=3 , SCREAMING_SNAKE_CASE__ : List[str]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=2 , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : Optional[int]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : List[Any]=37 , SCREAMING_SNAKE_CASE__ : int="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Any=10 , SCREAMING_SNAKE_CASE__ : int=0.02 , SCREAMING_SNAKE_CASE__ : Tuple="divided_space_time" , SCREAMING_SNAKE_CASE__ : Optional[int]=None , ) -> List[str]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = image_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_frames lowerCAmelCase__ = is_training lowerCAmelCase__ = use_labels lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = attention_type lowerCAmelCase__ = initializer_range lowerCAmelCase__ = scope lowerCAmelCase__ = num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token lowerCAmelCase__ = (image_size // patch_size) ** 2 lowerCAmelCase__ = (num_frames) * self.num_patches_per_frame + 1 def a ( self : int ) -> Tuple: lowerCAmelCase__ = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase__ = None if self.use_labels: lowerCAmelCase__ = ids_tensor([self.batch_size] , self.num_labels ) lowerCAmelCase__ = self.get_config() return config, pixel_values, labels def a ( self : List[Any] ) -> Any: lowerCAmelCase__ = TimesformerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , initializer_range=self.initializer_range , attention_type=self.attention_type , ) lowerCAmelCase__ = self.num_labels return config def a ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: lowerCAmelCase__ = TimesformerModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple ) -> Tuple: lowerCAmelCase__ = TimesformerForVideoClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) # verify the logits shape lowerCAmelCase__ = torch.Size((self.batch_size, self.num_labels) ) self.parent.assertEqual(result.logits.shape , SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> Dict: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else () snake_case__ = ( {"feature-extraction": TimesformerModel, "video-classification": TimesformerForVideoClassification} if is_torch_available() else {} ) snake_case__ = False snake_case__ = False snake_case__ = False snake_case__ = False def a ( self : List[str] ) -> List[Any]: lowerCAmelCase__ = TimesformerModelTester(self ) lowerCAmelCase__ = ConfigTester( self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ , hidden_size=37 ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple=False ) -> str: lowerCAmelCase__ = copy.deepcopy(SCREAMING_SNAKE_CASE__ ) if return_labels: if model_class in get_values(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) return inputs_dict def a ( self : Optional[Any] ) -> List[str]: self.config_tester.run_common_tests() @unittest.skip(reason="TimeSformer does not use inputs_embeds" ) def a ( self : Union[str, Any] ) -> Tuple: pass def a ( self : Dict ) -> List[str]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowerCAmelCase__ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__ , nn.Linear ) ) def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase__ = [*signature.parameters.keys()] lowerCAmelCase__ = ["pixel_values"] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] ) -> Tuple: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*SCREAMING_SNAKE_CASE__ ) @slow def a ( self : str ) -> Tuple: for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase__ = TimesformerModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Dict: if not self.has_attentions: pass else: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ = True for model_class in self.all_model_classes: lowerCAmelCase__ = self.model_tester.seq_length lowerCAmelCase__ = self.model_tester.num_frames lowerCAmelCase__ = True lowerCAmelCase__ = False lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) lowerCAmelCase__ = len(SCREAMING_SNAKE_CASE__ ) # Check attention is always last and order is fine lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(out_len + 1 , len(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) def a ( self : List[str] ) -> Any: def check_hidden_states_output(SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] ): lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.hidden_states lowerCAmelCase__ = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _A ( ): """simple docstring""" lowerCAmelCase__ = hf_hub_download( repo_id="hf-internal-testing/spaghetti-video" , filename="eating_spaghetti.npy" , repo_type="dataset" ) lowerCAmelCase__ = np.load(lowerCAmelCase_ ) return list(lowerCAmelCase_ ) @require_torch @require_vision class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @cached_property def a ( self : Optional[Any] ) -> Union[str, Any]: # logits were tested with a different mean and std, so we use the same here return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) if is_vision_available() else None ) @slow def a ( self : Optional[Any] ) -> str: lowerCAmelCase__ = TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400" ).to( SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.default_image_processor lowerCAmelCase__ = prepare_video() lowerCAmelCase__ = image_processor(video[:8] , return_tensors="pt" ).to(SCREAMING_SNAKE_CASE__ ) # forward pass with torch.no_grad(): lowerCAmelCase__ = model(**SCREAMING_SNAKE_CASE__ ) # verify the logits lowerCAmelCase__ = torch.Size((1, 400) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = torch.tensor([-0.3_016, -0.7_713, -0.4_205] ).to(SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
0
"""simple docstring""" from random import randint from tempfile import TemporaryFile import numpy as np def __snake_case ( _lowercase ,_lowercase ,_lowercase ): """simple docstring""" UpperCamelCase = 0 if start < end: UpperCamelCase = randint(_lowercase ,_lowercase ) UpperCamelCase = a[end] UpperCamelCase = a[pivot] UpperCamelCase = temp UpperCamelCase , UpperCamelCase = _in_place_partition(_lowercase ,_lowercase ,_lowercase ) count += _in_place_quick_sort(_lowercase ,_lowercase ,p - 1 ) count += _in_place_quick_sort(_lowercase ,p + 1 ,_lowercase ) return count def __snake_case ( _lowercase ,_lowercase ,_lowercase ): """simple docstring""" UpperCamelCase = 0 UpperCamelCase = randint(_lowercase ,_lowercase ) UpperCamelCase = a[end] UpperCamelCase = a[pivot] UpperCamelCase = temp UpperCamelCase = start - 1 for index in range(_lowercase ,_lowercase ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value UpperCamelCase = new_pivot_index + 1 UpperCamelCase = a[new_pivot_index] UpperCamelCase = a[index] UpperCamelCase = temp UpperCamelCase = a[new_pivot_index + 1] UpperCamelCase = a[end] UpperCamelCase = temp return new_pivot_index + 1, count SCREAMING_SNAKE_CASE_ = TemporaryFile() SCREAMING_SNAKE_CASE_ = 100 # 1000 elements are to be sorted SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 0, 1 # mean and standard deviation SCREAMING_SNAKE_CASE_ = np.random.normal(mu, sigma, p) np.save(outfile, X) print('The array is') print(X) outfile.seek(0) # using the same array SCREAMING_SNAKE_CASE_ = np.load(outfile) SCREAMING_SNAKE_CASE_ = len(M) - 1 SCREAMING_SNAKE_CASE_ = _in_place_quick_sort(M, 0, r) print( 'No of Comparisons for 100 elements selected from a standard normal distribution' 'is :' ) print(z)
34
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _A ( ): """simple docstring""" lowerCAmelCase__ = ArgumentParser( description=( "PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes" ) ) # Optional arguments for the launch helper parser.add_argument("--num_cores" , type=lowerCAmelCase_ , default=1 , help="Number of TPU cores to use (1 or 8)." ) # positional parser.add_argument( "training_script" , type=lowerCAmelCase_ , help=( "The full path to the single TPU training " "program/script to be launched in parallel, " "followed by all the arguments for the " "training script" ) , ) # rest from the training program parser.add_argument("training_script_args" , nargs=lowerCAmelCase_ ) return parser.parse_args() def _A ( ): """simple docstring""" lowerCAmelCase__ = parse_args() # Import training_script as a module. lowerCAmelCase__ = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) lowerCAmelCase__ = script_fpath.stem lowerCAmelCase__ = importlib.import_module(lowerCAmelCase_ ) # Patch sys.argv lowerCAmelCase__ = [args.training_script] + args.training_script_args + ["--tpu_num_cores", str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
61
0
def a ( A__ ) -> int: '''simple docstring''' if a < 0: raise ValueError('''Input value must be a positive integer''' ) elif isinstance(A__ , A__ ): raise TypeError('''Input value must be a \'int\' type''' ) return bin(A__ ).count('''1''' ) if __name__ == "__main__": import doctest doctest.testmod()
35
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool UpperCamelCase = { 'Acehnese Arabic': 'ace_Arab', 'Acehnese Latin': 'ace_Latn', 'Mesopotamian Arabic': 'acm_Arab', 'Ta\'izzi-Adeni Arabic': 'acq_Arab', 'Tunisian Arabic': 'aeb_Arab', 'Afrikaans': 'afr_Latn', 'South Levantine Arabic': 'ajp_Arab', 'Akan': 'aka_Latn', 'Amharic': 'amh_Ethi', 'North Levantine Arabic': 'apc_Arab', 'Modern Standard Arabic': 'arb_Arab', 'Modern Standard Arabic Romanized': 'arb_Latn', 'Najdi Arabic': 'ars_Arab', 'Moroccan Arabic': 'ary_Arab', 'Egyptian Arabic': 'arz_Arab', 'Assamese': 'asm_Beng', 'Asturian': 'ast_Latn', 'Awadhi': 'awa_Deva', 'Central Aymara': 'ayr_Latn', 'South Azerbaijani': 'azb_Arab', 'North Azerbaijani': 'azj_Latn', 'Bashkir': 'bak_Cyrl', 'Bambara': 'bam_Latn', 'Balinese': 'ban_Latn', 'Belarusian': 'bel_Cyrl', 'Bemba': 'bem_Latn', 'Bengali': 'ben_Beng', 'Bhojpuri': 'bho_Deva', 'Banjar Arabic': 'bjn_Arab', 'Banjar Latin': 'bjn_Latn', 'Standard Tibetan': 'bod_Tibt', 'Bosnian': 'bos_Latn', 'Buginese': 'bug_Latn', 'Bulgarian': 'bul_Cyrl', 'Catalan': 'cat_Latn', 'Cebuano': 'ceb_Latn', 'Czech': 'ces_Latn', 'Chokwe': 'cjk_Latn', 'Central Kurdish': 'ckb_Arab', 'Crimean Tatar': 'crh_Latn', 'Welsh': 'cym_Latn', 'Danish': 'dan_Latn', 'German': 'deu_Latn', 'Southwestern Dinka': 'dik_Latn', 'Dyula': 'dyu_Latn', 'Dzongkha': 'dzo_Tibt', 'Greek': 'ell_Grek', 'English': 'eng_Latn', 'Esperanto': 'epo_Latn', 'Estonian': 'est_Latn', 'Basque': 'eus_Latn', 'Ewe': 'ewe_Latn', 'Faroese': 'fao_Latn', 'Fijian': 'fij_Latn', 'Finnish': 'fin_Latn', 'Fon': 'fon_Latn', 'French': 'fra_Latn', 'Friulian': 'fur_Latn', 'Nigerian Fulfulde': 'fuv_Latn', 'Scottish Gaelic': 'gla_Latn', 'Irish': 'gle_Latn', 'Galician': 'glg_Latn', 'Guarani': 'grn_Latn', 'Gujarati': 'guj_Gujr', 'Haitian Creole': 'hat_Latn', 'Hausa': 'hau_Latn', 'Hebrew': 'heb_Hebr', 'Hindi': 'hin_Deva', 'Chhattisgarhi': 'hne_Deva', 'Croatian': 'hrv_Latn', 'Hungarian': 'hun_Latn', 'Armenian': 'hye_Armn', 'Igbo': 'ibo_Latn', 'Ilocano': 'ilo_Latn', 'Indonesian': 'ind_Latn', 'Icelandic': 'isl_Latn', 'Italian': 'ita_Latn', 'Javanese': 'jav_Latn', 'Japanese': 'jpn_Jpan', 'Kabyle': 'kab_Latn', 'Jingpho': 'kac_Latn', 'Kamba': 'kam_Latn', 'Kannada': 'kan_Knda', 'Kashmiri Arabic': 'kas_Arab', 'Kashmiri Devanagari': 'kas_Deva', 'Georgian': 'kat_Geor', 'Central Kanuri Arabic': 'knc_Arab', 'Central Kanuri Latin': 'knc_Latn', 'Kazakh': 'kaz_Cyrl', 'Kabiyè': 'kbp_Latn', 'Kabuverdianu': 'kea_Latn', 'Khmer': 'khm_Khmr', 'Kikuyu': 'kik_Latn', 'Kinyarwanda': 'kin_Latn', 'Kyrgyz': 'kir_Cyrl', 'Kimbundu': 'kmb_Latn', 'Northern Kurdish': 'kmr_Latn', 'Kikongo': 'kon_Latn', 'Korean': 'kor_Hang', 'Lao': 'lao_Laoo', 'Ligurian': 'lij_Latn', 'Limburgish': 'lim_Latn', 'Lingala': 'lin_Latn', 'Lithuanian': 'lit_Latn', 'Lombard': 'lmo_Latn', 'Latgalian': 'ltg_Latn', 'Luxembourgish': 'ltz_Latn', 'Luba-Kasai': 'lua_Latn', 'Ganda': 'lug_Latn', 'Luo': 'luo_Latn', 'Mizo': 'lus_Latn', 'Standard Latvian': 'lvs_Latn', 'Magahi': 'mag_Deva', 'Maithili': 'mai_Deva', 'Malayalam': 'mal_Mlym', 'Marathi': 'mar_Deva', 'Minangkabau Arabic ': 'min_Arab', 'Minangkabau Latin': 'min_Latn', 'Macedonian': 'mkd_Cyrl', 'Plateau Malagasy': 'plt_Latn', 'Maltese': 'mlt_Latn', 'Meitei Bengali': 'mni_Beng', 'Halh Mongolian': 'khk_Cyrl', 'Mossi': 'mos_Latn', 'Maori': 'mri_Latn', 'Burmese': 'mya_Mymr', 'Dutch': 'nld_Latn', 'Norwegian Nynorsk': 'nno_Latn', 'Norwegian Bokmål': 'nob_Latn', 'Nepali': 'npi_Deva', 'Northern Sotho': 'nso_Latn', 'Nuer': 'nus_Latn', 'Nyanja': 'nya_Latn', 'Occitan': 'oci_Latn', 'West Central Oromo': 'gaz_Latn', 'Odia': 'ory_Orya', 'Pangasinan': 'pag_Latn', 'Eastern Panjabi': 'pan_Guru', 'Papiamento': 'pap_Latn', 'Western Persian': 'pes_Arab', 'Polish': 'pol_Latn', 'Portuguese': 'por_Latn', 'Dari': 'prs_Arab', 'Southern Pashto': 'pbt_Arab', 'Ayacucho Quechua': 'quy_Latn', 'Romanian': 'ron_Latn', 'Rundi': 'run_Latn', 'Russian': 'rus_Cyrl', 'Sango': 'sag_Latn', 'Sanskrit': 'san_Deva', 'Santali': 'sat_Olck', 'Sicilian': 'scn_Latn', 'Shan': 'shn_Mymr', 'Sinhala': 'sin_Sinh', 'Slovak': 'slk_Latn', 'Slovenian': 'slv_Latn', 'Samoan': 'smo_Latn', 'Shona': 'sna_Latn', 'Sindhi': 'snd_Arab', 'Somali': 'som_Latn', 'Southern Sotho': 'sot_Latn', 'Spanish': 'spa_Latn', 'Tosk Albanian': 'als_Latn', 'Sardinian': 'srd_Latn', 'Serbian': 'srp_Cyrl', 'Swati': 'ssw_Latn', 'Sundanese': 'sun_Latn', 'Swedish': 'swe_Latn', 'Swahili': 'swh_Latn', 'Silesian': 'szl_Latn', 'Tamil': 'tam_Taml', 'Tatar': 'tat_Cyrl', 'Telugu': 'tel_Telu', 'Tajik': 'tgk_Cyrl', 'Tagalog': 'tgl_Latn', 'Thai': 'tha_Thai', 'Tigrinya': 'tir_Ethi', 'Tamasheq Latin': 'taq_Latn', 'Tamasheq Tifinagh': 'taq_Tfng', 'Tok Pisin': 'tpi_Latn', 'Tswana': 'tsn_Latn', 'Tsonga': 'tso_Latn', 'Turkmen': 'tuk_Latn', 'Tumbuka': 'tum_Latn', 'Turkish': 'tur_Latn', 'Twi': 'twi_Latn', 'Central Atlas Tamazight': 'tzm_Tfng', 'Uyghur': 'uig_Arab', 'Ukrainian': 'ukr_Cyrl', 'Umbundu': 'umb_Latn', 'Urdu': 'urd_Arab', 'Northern Uzbek': 'uzn_Latn', 'Venetian': 'vec_Latn', 'Vietnamese': 'vie_Latn', 'Waray': 'war_Latn', 'Wolof': 'wol_Latn', 'Xhosa': 'xho_Latn', 'Eastern Yiddish': 'ydd_Hebr', 'Yoruba': 'yor_Latn', 'Yue Chinese': 'yue_Hant', 'Chinese Simplified': 'zho_Hans', 'Chinese Traditional': 'zho_Hant', 'Standard Malay': 'zsm_Latn', 'Zulu': 'zul_Latn', } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "facebook/nllb-200-distilled-600M" snake_case__ = ( "This is a tool that translates text from a language to another. It takes three inputs: `text`, which should " "be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, " "which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in " "plain English, such as 'Romanian', or 'Albanian'. It returns the text translated in `tgt_lang`." ) snake_case__ = "translator" snake_case__ = AutoTokenizer snake_case__ = AutoModelForSeqaSeqLM snake_case__ = LANGUAGE_CODES snake_case__ = ["text", "text", "text"] snake_case__ = ["text"] def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: if src_lang not in self.lang_to_code: raise ValueError(f'{src_lang} is not a supported language.' ) if tgt_lang not in self.lang_to_code: raise ValueError(f'{tgt_lang} is not a supported language.' ) lowerCAmelCase__ = self.lang_to_code[src_lang] lowerCAmelCase__ = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( SCREAMING_SNAKE_CASE__ , return_tensors="pt" , src_lang=SCREAMING_SNAKE_CASE__ , tgt_lang=SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: return self.model.generate(**SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[str]: return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=SCREAMING_SNAKE_CASE__ )
61
0
import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": __lowercase : Dict = argparse.ArgumentParser() parser.add_argument( '''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the checkpoint to convert.''' ) parser.add_argument( '''--original_config_file''', type=str, required=True, help='''The YAML config file corresponding to the original architecture.''', ) parser.add_argument( '''--num_in_channels''', default=None, type=int, help='''The number of input channels. If `None` number of input channels will be automatically inferred.''', ) parser.add_argument( '''--image_size''', default=512, type=int, help=( '''The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2''' ''' Base. Use 768 for Stable Diffusion v2.''' ), ) parser.add_argument( '''--extract_ema''', action='''store_true''', help=( '''Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights''' ''' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield''' ''' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.''' ), ) parser.add_argument( '''--upcast_attention''', action='''store_true''', help=( '''Whether the attention computation should always be upcasted. This is necessary when running stable''' ''' diffusion 2.1.''' ), ) parser.add_argument( '''--from_safetensors''', action='''store_true''', help='''If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.''', ) parser.add_argument( '''--to_safetensors''', action='''store_true''', help='''Whether to store pipeline in safetensors format or not.''', ) parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''') parser.add_argument('''--device''', type=str, help='''Device to use (e.g. cpu, cuda:0, cuda:1, etc.)''') def lowercase ( __A : Tuple ) -> Union[str, Any]: '''simple docstring''' if string == "True": return True elif string == "False": return False else: raise ValueError(f"""could not parse string as bool {string}""" ) parser.add_argument( '''--use_linear_projection''', help='''Override for use linear projection''', required=False, type=parse_bool ) parser.add_argument('''--cross_attention_dim''', help='''Override for cross attention_dim''', required=False, type=int) __lowercase : Union[str, Any] = parser.parse_args() __lowercase : Optional[int] = download_controlnet_from_original_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, extract_ema=args.extract_ema, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, use_linear_projection=args.use_linear_projection, cross_attention_dim=args.cross_attention_dim, ) controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
36
import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = VideoToVideoSDPipeline snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"video"} ) - {"image", "width", "height"} snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"video"} ) - {"image"} snake_case__ = PipelineTesterMixin.required_optional_params - {"latents"} snake_case__ = False # No `output_type`. snake_case__ = frozenset( [ "num_inference_steps", "generator", "latents", "return_dict", "callback", "callback_steps", ] ) def a ( self : int ) -> Optional[int]: torch.manual_seed(0 ) lowerCAmelCase__ = 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 , ) lowerCAmelCase__ = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=SCREAMING_SNAKE_CASE__ , set_alpha_to_one=SCREAMING_SNAKE_CASE__ , ) torch.manual_seed(0 ) lowerCAmelCase__ = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) lowerCAmelCase__ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="gelu" , projection_dim=512 , ) lowerCAmelCase__ = CLIPTextModel(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) lowerCAmelCase__ = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, } return components def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Dict=0 ) -> Tuple: # 3 frames lowerCAmelCase__ = floats_tensor((1, 3, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) if str(SCREAMING_SNAKE_CASE__ ).startswith("mps" ): lowerCAmelCase__ = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: lowerCAmelCase__ = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = { "prompt": "A painting of a squirrel eating a burger", "video": video, "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "pt", } return inputs def a ( self : Union[str, Any] ) -> str: lowerCAmelCase__ = "cpu" # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ = self.get_dummy_components() lowerCAmelCase__ = VideoToVideoSDPipeline(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = "np" lowerCAmelCase__ = sd_pipe(**SCREAMING_SNAKE_CASE__ ).frames lowerCAmelCase__ = frames[0][-3:, -3:, -1] assert frames[0].shape == (32, 32, 3) lowerCAmelCase__ = np.array([106, 117, 113, 174, 137, 112, 148, 151, 131] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def a ( self : List[Any] ) -> str: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE__ , expected_max_diff=5e-3 ) @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a ( self : List[Any] ) -> str: pass @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a ( self : int ) -> Optional[Any]: pass @unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline." ) def a ( self : List[str] ) -> Optional[int]: pass def a ( self : Optional[Any] ) -> Tuple: return super().test_progress_bar() @slow @skip_mps class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : str ) -> int: lowerCAmelCase__ = VideoToVideoSDPipeline.from_pretrained("cerspense/zeroscope_v2_XL" , torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames lowerCAmelCase__ = torch.Generator(device="cpu" ).manual_seed(0 ) lowerCAmelCase__ = torch.randn((1, 10, 3, 1_024, 576) , generator=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = video.to("cuda" ) lowerCAmelCase__ = "Spiderman is surfing" lowerCAmelCase__ = pipe(SCREAMING_SNAKE_CASE__ , video=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=3 , output_type="pt" ).frames lowerCAmelCase__ = np.array([-1.0_458_984, -1.1_279_297, -0.9_663_086, -0.91_503_906, -0.75_097_656] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1e-2
61
0
import math def UpperCamelCase_ ( __a , __a ) -> Dict: if 0 not in (x, y): # We use the relation x^y = y*log10(x), where 10 is the base. return y * math.logaa(__a ) else: if x == 0: # 0 raised to any number is 0 return 0 elif y == 0: return 1 # any number raised to 0 is 1 raise AssertionError("This should never happen" ) if __name__ == "__main__": # Main function # Read two numbers from input and typecast them to int using map function. # Here x is the base and y is the power. UpperCamelCase : Tuple = """Enter the base and the power separated by a comma: """ UpperCamelCase , UpperCamelCase : str = map(int, input(prompt).split(""",""")) UpperCamelCase , UpperCamelCase : Tuple = map(int, input(prompt).split(""",""")) # We find the log of each number, using the function res(), which takes two # arguments. UpperCamelCase : Any = res(xa, ya) UpperCamelCase : List[str] = res(xa, ya) # We check for the largest number if resa > resa: print("""Largest number is""", xa, """^""", ya) elif resa > resa: print("""Largest number is""", xa, """^""", ya) else: print("""Both are equal""")
37
from __future__ import annotations def _A ( lowerCAmelCase_ : list , lowerCAmelCase_ : int , lowerCAmelCase_ : int , lowerCAmelCase_ : int ): """simple docstring""" lowerCAmelCase__ = [] lowerCAmelCase__ , lowerCAmelCase__ = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0 ) ) lowerCAmelCase__ = result + left + right return input_list def _A ( lowerCAmelCase_ : list ): """simple docstring""" if len(lowerCAmelCase_ ) <= 1: return input_list lowerCAmelCase__ = list(lowerCAmelCase_ ) # iteration for two-way merging lowerCAmelCase__ = 2 while p <= len(lowerCAmelCase_ ): # getting low, high and middle value for merge-sort of single list for i in range(0 , len(lowerCAmelCase_ ) , lowerCAmelCase_ ): lowerCAmelCase__ = i lowerCAmelCase__ = i + p - 1 lowerCAmelCase__ = (low + high + 1) // 2 lowerCAmelCase__ = merge(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # final merge of last two parts if p * 2 >= len(lowerCAmelCase_ ): lowerCAmelCase__ = i lowerCAmelCase__ = merge(lowerCAmelCase_ , 0 , lowerCAmelCase_ , len(lowerCAmelCase_ ) - 1 ) break p *= 2 return input_list if __name__ == "__main__": UpperCamelCase = input('Enter numbers separated by a comma:\n').strip() if user_input == "": UpperCamelCase = [] else: UpperCamelCase = [int(item.strip()) for item in user_input.split(',')] print(iter_merge_sort(unsorted))
61
0
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_mbart import MBartTokenizer else: A_ : Optional[int] = None A_ : List[Any] = logging.get_logger(__name__) A_ : Optional[Any] = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"} A_ : Any = { "vocab_file": { "facebook/mbart-large-en-ro": ( "https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model" ), "facebook/mbart-large-cc25": ( "https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model" ), }, "tokenizer_file": { "facebook/mbart-large-en-ro": "https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/tokenizer.json", "facebook/mbart-large-cc25": "https://huggingface.co/facebook/mbart-large-cc25/resolve/main/tokenizer.json", }, } A_ : Tuple = { "facebook/mbart-large-en-ro": 1024, "facebook/mbart-large-cc25": 1024, } # fmt: off A_ : Tuple = ["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN"] class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = ['''input_ids''', '''attention_mask'''] lowerCamelCase__ = MBartTokenizer lowerCamelCase__ = [] lowerCamelCase__ = [] def __init__( self , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="<unk>" , __SCREAMING_SNAKE_CASE="<pad>" , __SCREAMING_SNAKE_CASE="<mask>" , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): # Mask token behave like a normal word, i.e. include the space before it snake_case__ : List[Any] = AddedToken(__SCREAMING_SNAKE_CASE , lstrip=__SCREAMING_SNAKE_CASE , rstrip=__SCREAMING_SNAKE_CASE ) if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else mask_token super().__init__( vocab_file=__SCREAMING_SNAKE_CASE , tokenizer_file=__SCREAMING_SNAKE_CASE , bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , cls_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , mask_token=__SCREAMING_SNAKE_CASE , src_lang=__SCREAMING_SNAKE_CASE , tgt_lang=__SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) snake_case__ : Tuple = vocab_file snake_case__ : List[str] = False if not self.vocab_file else True snake_case__ : Union[str, Any] = FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({"""additional_special_tokens""": _additional_special_tokens} ) snake_case__ : List[Any] = { lang_code: self.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) for lang_code in FAIRSEQ_LANGUAGE_CODES } snake_case__ : Any = src_lang if src_lang is not None else """en_XX""" snake_case__ : Optional[Any] = self.convert_tokens_to_ids(self._src_lang ) snake_case__ : Dict = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def __UpperCamelCase ( self ): return self._src_lang @src_lang.setter def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): snake_case__ : Dict = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): snake_case__ : Tuple = [self.sep_token_id] snake_case__ : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): if src_lang is None or tgt_lang is None: raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model""" ) snake_case__ : List[Any] = src_lang snake_case__ : str = self(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = self.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = tgt_lang_id return inputs def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = "en_XX" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "ro_RO" , **__SCREAMING_SNAKE_CASE , ): snake_case__ : Union[str, Any] = src_lang snake_case__ : int = tgt_lang return super().prepare_seqaseq_batch(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): return self.set_src_lang_special_tokens(self.src_lang ) def __UpperCamelCase ( self ): return self.set_tgt_lang_special_tokens(self.tgt_lang ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): snake_case__ : Union[str, Any] = self.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) snake_case__ : int = [] snake_case__ : Dict = [self.eos_token_id, self.cur_lang_code] snake_case__ : int = self.convert_ids_to_tokens(self.prefix_tokens ) snake_case__ : List[str] = self.convert_ids_to_tokens(self.suffix_tokens ) snake_case__ : Optional[Any] = processors.TemplateProcessing( single=prefix_tokens_str + ["""$A"""] + suffix_tokens_str , pair=prefix_tokens_str + ["""$A""", """$B"""] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): snake_case__ : List[Any] = self.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = [] snake_case__ : List[Any] = [self.eos_token_id, self.cur_lang_code] snake_case__ : Any = self.convert_ids_to_tokens(self.prefix_tokens ) snake_case__ : Dict = self.convert_ids_to_tokens(self.suffix_tokens ) snake_case__ : Optional[int] = processors.TemplateProcessing( single=prefix_tokens_str + ["""$A"""] + suffix_tokens_str , pair=prefix_tokens_str + ["""$A""", """$B"""] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 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(__SCREAMING_SNAKE_CASE ): logger.error(f"Vocabulary path ({save_directory}) should be a directory." ) return snake_case__ : List[str] = os.path.join( __SCREAMING_SNAKE_CASE , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ): copyfile(self.vocab_file , __SCREAMING_SNAKE_CASE ) return (out_vocab_file,)
38
import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, ) class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=13 , SCREAMING_SNAKE_CASE__ : int=7 , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=99 , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : List[str]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : Optional[Any]=37 , SCREAMING_SNAKE_CASE__ : Optional[int]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE__ : Tuple=512 , SCREAMING_SNAKE_CASE__ : Tuple=16 , SCREAMING_SNAKE_CASE__ : Optional[Any]=2 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 , SCREAMING_SNAKE_CASE__ : Dict=4 , ) -> Optional[int]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = seq_length lowerCAmelCase__ = is_training lowerCAmelCase__ = use_attention_mask lowerCAmelCase__ = use_token_type_ids lowerCAmelCase__ = use_labels lowerCAmelCase__ = vocab_size lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = type_vocab_size lowerCAmelCase__ = type_sequence_label_size lowerCAmelCase__ = initializer_range lowerCAmelCase__ = num_choices def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase__ = None if self.use_attention_mask: lowerCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase__ = None if self.use_token_type_ids: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCAmelCase__ = RobertaPreLayerNormConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def a ( self : List[str] ) -> Union[str, Any]: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict def a ( self : Optional[Any] ) -> Dict: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = True lowerCAmelCase__ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax # Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40 class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = True snake_case__ = ( ( FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, ) if is_flax_available() else () ) def a ( self : int ) -> Dict: lowerCAmelCase__ = FlaxRobertaPreLayerNormModelTester(self ) @slow def a ( self : Tuple ) -> Union[str, Any]: for model_class_name in self.all_model_classes: lowerCAmelCase__ = model_class_name.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(np.ones((1, 1) ) ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_flax class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @slow def a ( self : int ) -> Dict: lowerCAmelCase__ = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ )[0] lowerCAmelCase__ = [1, 11, 50_265] self.assertEqual(list(output.shape ) , SCREAMING_SNAKE_CASE__ ) # compare the actual values for a slice. lowerCAmelCase__ = np.array( [[[40.4_880, 18.0_199, -5.2_367], [-1.8_877, -4.0_885, 10.7_085], [-2.2_613, -5.6_110, 7.2_665]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) @slow def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = FlaxRobertaPreLayerNormModel.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ )[0] # compare the actual values for a slice. lowerCAmelCase__ = np.array( [[[0.0_208, -0.0_356, 0.0_237], [-0.1_569, -0.0_411, -0.2_626], [0.1_879, 0.0_125, -0.0_089]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
0
from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''huggingface/informer-tourism-monthly''': ( '''https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json''' ), # See all Informer models at https://huggingface.co/models?filter=informer } class snake_case_ ( __A ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = "informer" SCREAMING_SNAKE_CASE : int = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", "num_hidden_layers": "encoder_layers", } def __init__( self : Dict , _UpperCamelCase : Optional[int] = None , _UpperCamelCase : Optional[int] = None , _UpperCamelCase : str = "student_t" , _UpperCamelCase : str = "nll" , _UpperCamelCase : int = 1 , _UpperCamelCase : List[int] = None , _UpperCamelCase : Optional[Union[str, bool]] = "mean" , _UpperCamelCase : int = 0 , _UpperCamelCase : int = 0 , _UpperCamelCase : int = 0 , _UpperCamelCase : int = 0 , _UpperCamelCase : Optional[List[int]] = None , _UpperCamelCase : Optional[List[int]] = None , _UpperCamelCase : int = 6_4 , _UpperCamelCase : int = 3_2 , _UpperCamelCase : int = 3_2 , _UpperCamelCase : int = 2 , _UpperCamelCase : int = 2 , _UpperCamelCase : int = 2 , _UpperCamelCase : int = 2 , _UpperCamelCase : bool = True , _UpperCamelCase : str = "gelu" , _UpperCamelCase : float = 0.05 , _UpperCamelCase : float = 0.1 , _UpperCamelCase : float = 0.1 , _UpperCamelCase : float = 0.1 , _UpperCamelCase : float = 0.1 , _UpperCamelCase : int = 1_0_0 , _UpperCamelCase : float = 0.02 , _UpperCamelCase : Dict=True , _UpperCamelCase : str = "prob" , _UpperCamelCase : int = 5 , _UpperCamelCase : bool = True , **_UpperCamelCase : Optional[Any] , ) ->Optional[int]: # time series specific configuration snake_case_ = prediction_length snake_case_ = context_length or prediction_length snake_case_ = distribution_output snake_case_ = loss snake_case_ = input_size snake_case_ = num_time_features snake_case_ = lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7] snake_case_ = scaling snake_case_ = num_dynamic_real_features snake_case_ = num_static_real_features snake_case_ = num_static_categorical_features # set cardinality if cardinality and num_static_categorical_features > 0: if len(_UpperCamelCase ) != num_static_categorical_features: raise ValueError( '''The cardinality should be a list of the same length as `num_static_categorical_features`''' ) snake_case_ = cardinality else: snake_case_ = [0] # set embedding_dimension if embedding_dimension and num_static_categorical_features > 0: if len(_UpperCamelCase ) != num_static_categorical_features: raise ValueError( '''The embedding dimension should be a list of the same length as `num_static_categorical_features`''' ) snake_case_ = embedding_dimension else: snake_case_ = [min(5_0 , (cat + 1) // 2 ) for cat in self.cardinality] snake_case_ = num_parallel_samples # Transformer architecture configuration snake_case_ = input_size * len(self.lags_sequence ) + self._number_of_features snake_case_ = d_model snake_case_ = encoder_attention_heads snake_case_ = decoder_attention_heads snake_case_ = encoder_ffn_dim snake_case_ = decoder_ffn_dim snake_case_ = encoder_layers snake_case_ = decoder_layers snake_case_ = dropout snake_case_ = attention_dropout snake_case_ = activation_dropout snake_case_ = encoder_layerdrop snake_case_ = decoder_layerdrop snake_case_ = activation_function snake_case_ = init_std snake_case_ = use_cache # Informer snake_case_ = attention_type snake_case_ = sampling_factor snake_case_ = distil super().__init__(is_encoder_decoder=_UpperCamelCase , **_UpperCamelCase ) @property def snake_case__( self : Optional[Any] ) ->int: return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
39
class __lowerCamelCase : """simple docstring""" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = size lowerCAmelCase__ = [0] * size lowerCAmelCase__ = [0] * size @staticmethod def a ( SCREAMING_SNAKE_CASE__ : int ) -> int: return index | (index + 1) @staticmethod def a ( SCREAMING_SNAKE_CASE__ : int ) -> int: return (index & (index + 1)) - 1 def a ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = value while index < self.size: lowerCAmelCase__ = self.get_prev(SCREAMING_SNAKE_CASE__ ) + 1 if current_left_border == index: lowerCAmelCase__ = value else: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_next(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> int: right -= 1 # Because of right is exclusive lowerCAmelCase__ = 0 while left <= right: lowerCAmelCase__ = self.get_prev(SCREAMING_SNAKE_CASE__ ) if left <= current_left: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , self.tree[right] ) lowerCAmelCase__ = current_left else: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
61
0