code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' import inspect import os import re from transformers.configuration_utils import PretrainedConfig 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_config_docstrings.py __lowerCAmelCase = """src/transformers""" # This is to make sure the transformers module imported is the one in the repo. __lowerCAmelCase = direct_transformers_import(PATH_TO_TRANSFORMERS) __lowerCAmelCase = transformers.models.auto.configuration_auto.CONFIG_MAPPING __lowerCAmelCase = { # used to compute the property `self.chunk_length` """EncodecConfig""": ["""overlap"""], # used as `self.bert_model = BertModel(config, ...)` """DPRConfig""": True, # not used in modeling files, but it's an important information """FSMTConfig""": ["""langs"""], # used internally in the configuration class file """GPTNeoConfig""": ["""attention_types"""], # used internally in the configuration class file """EsmConfig""": ["""is_folding_model"""], # used during training (despite we don't have training script for these models yet) """Mask2FormerConfig""": ["""ignore_value"""], # `ignore_value` used during training (despite we don't have training script for these models yet) # `norm` used in conversion script (despite not using in the modeling file) """OneFormerConfig""": ["""ignore_value""", """norm"""], # used during preprocessing and collation, see `collating_graphormer.py` """GraphormerConfig""": ["""spatial_pos_max"""], # used internally in the configuration class file """T5Config""": ["""feed_forward_proj"""], # used internally in the configuration class file # `tokenizer_class` get default value `T5Tokenizer` intentionally """MT5Config""": ["""feed_forward_proj""", """tokenizer_class"""], """UMT5Config""": ["""feed_forward_proj""", """tokenizer_class"""], # used internally in the configuration class file """LongT5Config""": ["""feed_forward_proj"""], # used internally in the configuration class file """SwitchTransformersConfig""": ["""feed_forward_proj"""], # having default values other than `1e-5` - we can't fix them without breaking """BioGptConfig""": ["""layer_norm_eps"""], # having default values other than `1e-5` - we can't fix them without breaking """GLPNConfig""": ["""layer_norm_eps"""], # having default values other than `1e-5` - we can't fix them without breaking """SegformerConfig""": ["""layer_norm_eps"""], # having default values other than `1e-5` - we can't fix them without breaking """CvtConfig""": ["""layer_norm_eps"""], # having default values other than `1e-5` - we can't fix them without breaking """PerceiverConfig""": ["""layer_norm_eps"""], # used internally to calculate the feature size """InformerConfig""": ["""num_static_real_features""", """num_time_features"""], # used internally to calculate the feature size """TimeSeriesTransformerConfig""": ["""num_static_real_features""", """num_time_features"""], # used internally to calculate the feature size """AutoformerConfig""": ["""num_static_real_features""", """num_time_features"""], # used internally to calculate `mlp_dim` """SamVisionConfig""": ["""mlp_ratio"""], # For (head) training, but so far not implemented """ClapAudioConfig""": ["""num_classes"""], # Not used, but providing useful information to users """SpeechT5HifiGanConfig""": ["""sampling_rate"""], } # TODO (ydshieh): Check the failing cases, try to fix them or move some cases to the above block once we are sure SPECIAL_CASES_TO_ALLOW.update( { """CLIPSegConfig""": True, """DeformableDetrConfig""": True, """DetaConfig""": True, """DinatConfig""": True, """DonutSwinConfig""": True, """EfficientFormerConfig""": True, """FSMTConfig""": True, """JukeboxConfig""": True, """LayoutLMv2Config""": True, """MaskFormerSwinConfig""": True, """MT5Config""": True, """NatConfig""": True, """OneFormerConfig""": True, """PerceiverConfig""": True, """RagConfig""": True, """SpeechT5Config""": True, """SwinConfig""": True, """Swin2SRConfig""": True, """Swinv2Config""": True, """SwitchTransformersConfig""": True, """TableTransformerConfig""": True, """TapasConfig""": True, """TransfoXLConfig""": True, """UniSpeechConfig""": True, """UniSpeechSatConfig""": True, """WavLMConfig""": True, """WhisperConfig""": True, # TODO: @Arthur (for `alignment_head` and `alignment_layer`) """JukeboxPriorConfig""": True, # TODO: @Younes (for `is_decoder`) """Pix2StructTextConfig""": True, } ) def UpperCAmelCase_ (__a : int , __a : Any , __a : int , __a : Optional[int] ): """simple docstring""" _a : Tuple = False for attribute in attributes: for modeling_source in source_strings: # check if we can find `config.xxx`, `getattr(config, "xxx", ...)` or `getattr(self.config, "xxx", ...)` if ( f"""config.{attribute}""" in modeling_source or f"""getattr(config, \"{attribute}\"""" in modeling_source or f"""getattr(self.config, \"{attribute}\"""" in modeling_source ): _a : str = True # Deal with multi-line cases elif ( re.search( Rf"""getattr[ \t\v\n\r\f]*\([ \t\v\n\r\f]*(self\.)?config,[ \t\v\n\r\f]*\"{attribute}\"""" , __a , ) is not None ): _a : List[str] = True # `SequenceSummary` is called with `SequenceSummary(config)` elif attribute in [ "summary_type", "summary_use_proj", "summary_activation", "summary_last_dropout", "summary_proj_to_labels", "summary_first_dropout", ]: if "SequenceSummary" in modeling_source: _a : Union[str, Any] = True if attribute_used: break if attribute_used: break # common and important attributes, even if they do not always appear in the modeling files _a : Optional[Any] = [ 'bos_index', 'eos_index', 'pad_index', 'unk_index', 'mask_index', 'image_size', 'use_cache', 'out_features', 'out_indices', ] _a : Dict = ['encoder_no_repeat_ngram_size'] # Special cases to be allowed _a : int = True if not attribute_used: _a : Dict = False for attribute in attributes: # Allow if the default value in the configuration class is different from the one in `PretrainedConfig` if attribute in ["is_encoder_decoder"] and default_value is True: _a : Any = True elif attribute in ["tie_word_embeddings"] and default_value is False: _a : Dict = True # Allow cases without checking the default value in the configuration class elif attribute in attributes_to_allow + attributes_used_in_generation: _a : List[Any] = True elif attribute.endswith('_token_id' ): _a : Optional[Any] = True # configuration class specific cases if not case_allowed: _a : Union[str, Any] = SPECIAL_CASES_TO_ALLOW.get(config_class.__name__ , [] ) _a : Any = allowed_cases is True or attribute in allowed_cases return attribute_used or case_allowed def UpperCAmelCase_ (__a : str ): """simple docstring""" _a : List[Any] = dict(inspect.signature(config_class.__init__ ).parameters ) _a : Any = [x for x in list(signature.keys() ) if x not in ['self', 'kwargs']] _a : Dict = [signature[param].default for param in parameter_names] # If `attribute_map` exists, an attribute can have different names to be used in the modeling files, and as long # as one variant is used, the test should pass _a : Dict = {} if len(config_class.attribute_map ) > 0: _a : str = {v: k for k, v in config_class.attribute_map.items()} # Get the path to modeling source files _a : Dict = inspect.getsourcefile(__a ) _a : Dict = os.path.dirname(__a ) # Let's check against all frameworks: as long as one framework uses an attribute, we are good. _a : Optional[Any] = [os.path.join(__a , __a ) for fn in os.listdir(__a ) if fn.startswith('modeling_' )] # Get the source code strings _a : Optional[int] = [] for path in modeling_paths: if os.path.isfile(__a ): with open(__a ) as fp: modeling_sources.append(fp.read() ) _a : Tuple = [] for config_param, default_value in zip(__a , __a ): # `attributes` here is all the variant names for `config_param` _a : Tuple = [config_param] # some configuration classes have non-empty `attribute_map`, and both names could be used in the # corresponding modeling files. As long as one of them appears, it is fine. if config_param in reversed_attribute_map: attributes.append(reversed_attribute_map[config_param] ) if not check_attribute_being_used(__a , __a , __a , __a ): unused_attributes.append(attributes[0] ) return sorted(__a ) def UpperCAmelCase_ (): """simple docstring""" _a : int = {} for _config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in _config_class.__module__: continue # Some config classes are not in `CONFIG_MAPPING` (e.g. `CLIPVisionConfig`, `Blip2VisionConfig`, etc.) _a : Tuple = [ cls for name, cls in inspect.getmembers( inspect.getmodule(_config_class ) , lambda __a : inspect.isclass(__a ) and issubclass(__a , __a ) and inspect.getmodule(__a ) == inspect.getmodule(_config_class ) , ) ] for config_class in config_classes_in_module: _a : Dict = check_config_attributes_being_used(__a ) if len(__a ) > 0: _a : List[Any] = unused_attributes if len(__a ) > 0: _a : Union[str, Any] = 'The following configuration classes contain unused attributes in the corresponding modeling files:\n' for name, attributes in configs_with_unused_attributes.items(): error += f"""{name}: {attributes}\n""" raise ValueError(__a ) if __name__ == "__main__": check_config_attributes()
271
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import KarrasVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : UNetaDModel __UpperCAmelCase : KarrasVeScheduler def __init__( self : Union[str, Any] ,_a : UNetaDModel ,_a : KarrasVeScheduler ): '''simple docstring''' super().__init__() self.register_modules(unet=_a ,scheduler=_a ) @torch.no_grad() def __call__( self : List[Any] ,_a : int = 1 ,_a : int = 50 ,_a : Optional[Union[torch.Generator, List[torch.Generator]]] = None ,_a : Optional[str] = "pil" ,_a : bool = True ,**_a : List[Any] ,): '''simple docstring''' _a : Any = self.unet.config.sample_size _a : Optional[int] = (batch_size, 3, img_size, img_size) _a : Dict = self.unet # sample x_0 ~ N(0, sigma_0^2 * I) _a : Dict = randn_tensor(_a ,generator=_a ,device=self.device ) * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(_a ) for t in self.progress_bar(self.scheduler.timesteps ): # here sigma_t == t_i from the paper _a : Optional[int] = self.scheduler.schedule[t] _a : List[str] = self.scheduler.schedule[t - 1] if t > 0 else 0 # 1. Select temporarily increased noise level sigma_hat # 2. Add new noise to move from sample_i to sample_hat _a, _a : List[Any] = self.scheduler.add_noise_to_input(_a ,_a ,generator=_a ) # 3. Predict the noise residual given the noise magnitude `sigma_hat` # The model inputs and output are adjusted by following eq. (213) in [1]. _a : Optional[int] = (sigma_hat / 2) * model((sample_hat + 1) / 2 ,sigma_hat / 2 ).sample # 4. Evaluate dx/dt at sigma_hat # 5. Take Euler step from sigma to sigma_prev _a : Tuple = self.scheduler.step(_a ,_a ,_a ,_a ) if sigma_prev != 0: # 6. Apply 2nd order correction # The model inputs and output are adjusted by following eq. (213) in [1]. _a : Optional[int] = (sigma_prev / 2) * model((step_output.prev_sample + 1) / 2 ,sigma_prev / 2 ).sample _a : Optional[Any] = self.scheduler.step_correct( _a ,_a ,_a ,_a ,step_output.prev_sample ,step_output['derivative'] ,) _a : Dict = step_output.prev_sample _a : Tuple = (sample / 2 + 0.5).clamp(0 ,1 ) _a : Optional[Any] = sample.cpu().permute(0 ,2 ,3 ,1 ).numpy() if output_type == "pil": _a : List[str] = self.numpy_to_pil(_a ) if not return_dict: return (image,) return ImagePipelineOutput(images=_a )
271
1
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging __lowerCAmelCase = logging.get_logger(__name__) if is_vision_available(): import PIL class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : Optional[int] = ['''pixel_values'''] def __init__( self : List[str] ,_a : bool = True ,_a : Dict[str, int] = None ,_a : PILImageResampling = PILImageResampling.BICUBIC ,_a : bool = True ,_a : Dict[str, int] = None ,_a : bool = True ,_a : Union[int, float] = 1 / 255 ,_a : bool = True ,_a : Optional[Union[float, List[float]]] = None ,_a : Optional[Union[float, List[float]]] = None ,_a : bool = True ,**_a : Tuple ,): '''simple docstring''' super().__init__(**_a ) _a : str = size if size is not None else {'shortest_edge': 224} _a : List[str] = get_size_dict(_a ,default_to_square=_a ) _a : Dict = crop_size if crop_size is not None else {'height': 224, 'width': 224} _a : Dict = get_size_dict(_a ,default_to_square=_a ,param_name='crop_size' ) _a : int = do_resize _a : Tuple = size _a : List[Any] = resample _a : Optional[Any] = do_center_crop _a : str = crop_size _a : str = do_rescale _a : Any = rescale_factor _a : Union[str, Any] = do_normalize _a : Any = image_mean if image_mean is not None else OPENAI_CLIP_MEAN _a : Tuple = image_std if image_std is not None else OPENAI_CLIP_STD _a : Dict = do_convert_rgb def __lowercase ( self : List[str] ,_a : np.ndarray ,_a : Dict[str, int] ,_a : PILImageResampling = PILImageResampling.BICUBIC ,_a : Optional[Union[str, ChannelDimension]] = None ,**_a : List[str] ,): '''simple docstring''' _a : str = get_size_dict(_a ,default_to_square=_a ) if "shortest_edge" not in size: raise ValueError(F"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}""" ) _a : Optional[int] = get_resize_output_image_size(_a ,size=size['shortest_edge'] ,default_to_square=_a ) return resize(_a ,size=_a ,resample=_a ,data_format=_a ,**_a ) def __lowercase ( self : Optional[int] ,_a : np.ndarray ,_a : Dict[str, int] ,_a : Optional[Union[str, ChannelDimension]] = None ,**_a : List[str] ,): '''simple docstring''' _a : List[Any] = get_size_dict(_a ) if "height" not in size or "width" not in size: raise ValueError(F"""The `size` parameter must contain the keys (height, width). Got {size.keys()}""" ) return center_crop(_a ,size=(size['height'], size['width']) ,data_format=_a ,**_a ) def __lowercase ( self : Optional[Any] ,_a : np.ndarray ,_a : Union[int, float] ,_a : Optional[Union[str, ChannelDimension]] = None ,**_a : Dict ,): '''simple docstring''' return rescale(_a ,scale=_a ,data_format=_a ,**_a ) def __lowercase ( self : List[str] ,_a : np.ndarray ,_a : Union[float, List[float]] ,_a : Union[float, List[float]] ,_a : Optional[Union[str, ChannelDimension]] = None ,**_a : Tuple ,): '''simple docstring''' return normalize(_a ,mean=_a ,std=_a ,data_format=_a ,**_a ) def __lowercase ( self : Optional[int] ,_a : ImageInput ,_a : bool = None ,_a : Dict[str, int] = None ,_a : PILImageResampling = None ,_a : bool = None ,_a : int = None ,_a : bool = None ,_a : float = None ,_a : bool = None ,_a : Optional[Union[float, List[float]]] = None ,_a : Optional[Union[float, List[float]]] = None ,_a : bool = None ,_a : Optional[Union[str, TensorType]] = None ,_a : Optional[ChannelDimension] = ChannelDimension.FIRST ,**_a : str ,): '''simple docstring''' _a : Optional[int] = do_resize if do_resize is not None else self.do_resize _a : Any = size if size is not None else self.size _a : Optional[int] = get_size_dict(_a ,param_name='size' ,default_to_square=_a ) _a : Tuple = resample if resample is not None else self.resample _a : Tuple = do_center_crop if do_center_crop is not None else self.do_center_crop _a : Dict = crop_size if crop_size is not None else self.crop_size _a : int = get_size_dict(_a ,param_name='crop_size' ,default_to_square=_a ) _a : Optional[int] = do_rescale if do_rescale is not None else self.do_rescale _a : int = rescale_factor if rescale_factor is not None else self.rescale_factor _a : Union[str, Any] = do_normalize if do_normalize is not None else self.do_normalize _a : Any = image_mean if image_mean is not None else self.image_mean _a : str = image_std if image_std is not None else self.image_std _a : List[Any] = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb _a : int = make_list_of_images(_a ) if not valid_images(_a ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_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: _a : Optional[Any] = [convert_to_rgb(_a ) for image in images] # All transformations expect numpy arrays. _a : Optional[Any] = [to_numpy_array(_a ) for image in images] if do_resize: _a : List[Any] = [self.resize(image=_a ,size=_a ,resample=_a ) for image in images] if do_center_crop: _a : Tuple = [self.center_crop(image=_a ,size=_a ) for image in images] if do_rescale: _a : List[Any] = [self.rescale(image=_a ,scale=_a ) for image in images] if do_normalize: _a : int = [self.normalize(image=_a ,mean=_a ,std=_a ) for image in images] _a : Dict = [to_channel_dimension_format(_a ,_a ) for image in images] _a : Any = {'pixel_values': images} return BatchFeature(data=_a ,tensor_type=_a )
271
'''simple docstring''' import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version from .. import __version__ from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging __lowerCAmelCase = ( """https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py""" ) __lowerCAmelCase = logging.get_logger(__name__) # pylint: disable=invalid-name def UpperCAmelCase_ (): """simple docstring""" _a : Optional[int] = 'https://pypi.org/pypi/diffusers/json' _a : int = json.loads(request.urlopen(__a ).read() )['releases'].keys() return sorted(__a , key=lambda __a : version.Version(__a ) ) def UpperCAmelCase_ (): """simple docstring""" if HF_MODULES_CACHE in sys.path: return sys.path.append(__a ) os.makedirs(__a , exist_ok=__a ) _a : str = Path(__a ) / '__init__.py' if not init_path.exists(): init_path.touch() def UpperCAmelCase_ (__a : Union[str, os.PathLike] ): """simple docstring""" init_hf_modules() _a : Dict = Path(__a ) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent ) os.makedirs(__a , exist_ok=__a ) _a : Optional[int] = dynamic_module_path / '__init__.py' if not init_path.exists(): init_path.touch() def UpperCAmelCase_ (__a : str ): """simple docstring""" with open(__a , 'r' , encoding='utf-8' ) as f: _a : int = f.read() # Imports of the form `import .xxx` _a : Tuple = re.findall('^\s*import\s+\.(\S+)\s*$' , __a , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall('^\s*from\s+\.(\S+)\s+import' , __a , flags=re.MULTILINE ) # Unique-ify return list(set(__a ) ) def UpperCAmelCase_ (__a : Any ): """simple docstring""" _a : Optional[int] = False _a : Optional[int] = [module_file] _a : List[str] = [] # Let's recurse through all relative imports while not no_change: _a : str = [] for f in files_to_check: new_imports.extend(get_relative_imports(__a ) ) _a : Union[str, Any] = Path(__a ).parent _a : str = [str(module_path / m ) for m in new_imports] _a : Tuple = [f for f in new_import_files if f not in all_relative_imports] _a : Dict = [f"""{f}.py""" for f in new_import_files] _a : List[str] = len(__a ) == 0 all_relative_imports.extend(__a ) return all_relative_imports def UpperCAmelCase_ (__a : Tuple ): """simple docstring""" with open(__a , 'r' , encoding='utf-8' ) as f: _a : Dict = f.read() # Imports of the form `import xxx` _a : Optional[int] = re.findall('^\s*import\s+(\S+)\s*$' , __a , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall('^\s*from\s+(\S+)\s+import' , __a , flags=re.MULTILINE ) # Only keep the top-level module _a : List[str] = [imp.split('.' )[0] for imp in imports if not imp.startswith('.' )] # Unique-ify and test we got them all _a : Optional[int] = list(set(__a ) ) _a : List[str] = [] for imp in imports: try: importlib.import_module(__a ) except ImportError: missing_packages.append(__a ) if len(__a ) > 0: raise ImportError( 'This modeling file requires the following packages that were not found in your environment: ' f"""{', '.join(__a )}. Run `pip install {' '.join(__a )}`""" ) return get_relative_imports(__a ) def UpperCAmelCase_ (__a : Any , __a : str ): """simple docstring""" _a : Any = module_path.replace(os.path.sep , '.' ) _a : Union[str, Any] = importlib.import_module(__a ) if class_name is None: return find_pipeline_class(__a ) return getattr(__a , __a ) def UpperCAmelCase_ (__a : Optional[int] ): """simple docstring""" from ..pipelines import DiffusionPipeline _a : List[str] = dict(inspect.getmembers(__a , inspect.isclass ) ) _a : str = None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , __a ) and cls.__module__.split('.' )[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( f"""Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:""" f""" {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in""" f""" {loaded_module}.""" ) _a : Any = cls return pipeline_class def UpperCAmelCase_ (__a : Union[str, os.PathLike] , __a : str , __a : Optional[Union[str, os.PathLike]] = None , __a : bool = False , __a : bool = False , __a : Optional[Dict[str, str]] = None , __a : Optional[Union[bool, str]] = None , __a : Optional[str] = None , __a : bool = False , ): """simple docstring""" _a : str = str(__a ) _a : Optional[Any] = os.path.join(__a , __a ) if os.path.isfile(__a ): _a : Tuple = module_file_or_url _a : Optional[Any] = 'local' elif pretrained_model_name_or_path.count('/' ) == 0: _a : int = get_diffusers_versions() # cut ".dev0" _a : Any = 'v' + '.'.join(__version__.split('.' )[:3] ) # retrieve github version that matches if revision is None: _a : Any = latest_version if latest_version[1:] in available_versions else 'main' logger.info(f"""Defaulting to latest_version: {revision}.""" ) elif revision in available_versions: _a : Any = f"""v{revision}""" elif revision == "main": _a : Optional[int] = revision else: raise ValueError( f"""`custom_revision`: {revision} does not exist. Please make sure to choose one of""" f""" {', '.join(available_versions + ['main'] )}.""" ) # community pipeline on GitHub _a : Tuple = COMMUNITY_PIPELINES_URL.format(revision=__a , pipeline=__a ) try: _a : Any = cached_download( __a , cache_dir=__a , force_download=__a , proxies=__a , resume_download=__a , local_files_only=__a , use_auth_token=__a , ) _a : List[Any] = 'git' _a : Any = pretrained_model_name_or_path + '.py' except EnvironmentError: logger.error(f"""Could not locate the {module_file} inside {pretrained_model_name_or_path}.""" ) raise else: try: # Load from URL or cache if already cached _a : Optional[Any] = hf_hub_download( __a , __a , cache_dir=__a , force_download=__a , proxies=__a , resume_download=__a , local_files_only=__a , use_auth_token=__a , ) _a : List[Any] = os.path.join('local' , '--'.join(pretrained_model_name_or_path.split('/' ) ) ) except EnvironmentError: logger.error(f"""Could not locate the {module_file} inside {pretrained_model_name_or_path}.""" ) raise # Check we have all the requirements in our environment _a : Optional[int] = check_imports(__a ) # Now we move the module inside our cached dynamic modules. _a : Optional[Any] = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(__a ) _a : Any = Path(__a ) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copy(__a , submodule_path / module_file ) for module_needed in modules_needed: _a : Dict = f"""{module_needed}.py""" shutil.copy(os.path.join(__a , __a ) , submodule_path / module_needed ) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. if isinstance(__a , __a ): _a : Optional[Any] = use_auth_token elif use_auth_token is True: _a : List[Any] = HfFolder.get_token() else: _a : Dict = None _a : int = model_info(__a , revision=__a , token=__a ).sha # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. _a : Optional[int] = submodule_path / commit_hash _a : str = full_submodule + os.path.sep + commit_hash create_dynamic_module(__a ) if not (submodule_path / module_file).exists(): shutil.copy(__a , submodule_path / module_file ) # Make sure we also have every file with relative for module_needed in modules_needed: if not (submodule_path / module_needed).exists(): get_cached_module_file( __a , f"""{module_needed}.py""" , cache_dir=__a , force_download=__a , resume_download=__a , proxies=__a , use_auth_token=__a , revision=__a , local_files_only=__a , ) return os.path.join(__a , __a ) def UpperCAmelCase_ (__a : Union[str, os.PathLike] , __a : str , __a : Optional[str] = None , __a : Optional[Union[str, os.PathLike]] = None , __a : bool = False , __a : bool = False , __a : Optional[Dict[str, str]] = None , __a : Optional[Union[bool, str]] = None , __a : Optional[str] = None , __a : bool = False , **__a : str , ): """simple docstring""" _a : Dict = get_cached_module_file( __a , __a , cache_dir=__a , force_download=__a , resume_download=__a , proxies=__a , use_auth_token=__a , revision=__a , local_files_only=__a , ) return get_class_in_module(__a , final_module.replace('.py' , '' ) )
271
1
'''simple docstring''' import argparse import torch from transformers import RemBertConfig, RemBertModel, load_tf_weights_in_rembert from transformers.utils import logging logging.set_verbosity_info() def UpperCAmelCase_ (__a : Tuple , __a : List[str] , __a : Union[str, Any] ): """simple docstring""" _a : Tuple = RemBertConfig.from_json_file(__a ) print('Building PyTorch model from configuration: {}'.format(str(__a ) ) ) _a : Tuple = RemBertModel(__a ) # Load weights from tf checkpoint load_tf_weights_in_rembert(__a , __a , __a ) # Save pytorch-model print('Save PyTorch model to {}'.format(__a ) ) torch.save(model.state_dict() , __a ) if __name__ == "__main__": __lowerCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--rembert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained RemBERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) __lowerCAmelCase = parser.parse_args() convert_rembert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.rembert_config_file, args.pytorch_dump_path)
271
'''simple docstring''' def UpperCAmelCase_ (__a : list , __a : list , __a : int ): """simple docstring""" _a : Optional[Any] = len(__a ) _a : int = [[0] * n for i in range(__a )] for i in range(__a ): _a : Tuple = y_points[i] for i in range(2 , __a ): for j in range(__a , __a ): _a : Tuple = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
271
1
'''simple docstring''' import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = ["""model.decoder.embed_positions.weights"""] def UpperCAmelCase_ (__a : List[Any] ): """simple docstring""" if "emb" in name: _a : Union[str, Any] = name.replace('emb' , 'model.decoder.embed_tokens' ) if "transformer" in name: _a : Tuple = name.replace('transformer' , 'model.decoder' ) if "cross_attention" in name: _a : int = name.replace('cross_attention' , 'encoder_attn' ) if "linear1" in name: _a : List[Any] = name.replace('linear1' , 'fc1' ) if "linear2" in name: _a : Any = name.replace('linear2' , 'fc2' ) if "norm1" in name: _a : Optional[int] = name.replace('norm1' , 'self_attn_layer_norm' ) if "norm_cross" in name: _a : List[Any] = name.replace('norm_cross' , 'encoder_attn_layer_norm' ) if "norm2" in name: _a : List[str] = name.replace('norm2' , 'final_layer_norm' ) if "out_norm" in name: _a : Tuple = name.replace('out_norm' , 'model.decoder.layer_norm' ) if "linears" in name: _a : Union[str, Any] = name.replace('linears' , 'lm_heads' ) if "condition_provider.conditioners.description.output_proj" in name: _a : List[str] = name.replace('condition_provider.conditioners.description.output_proj' , 'enc_to_dec_proj' ) return name def UpperCAmelCase_ (__a : OrderedDict , __a : int ): """simple docstring""" _a : List[Any] = list(state_dict.keys() ) _a : Optional[Any] = {} for key in keys: _a : Tuple = state_dict.pop(__a ) _a : List[Any] = rename_keys(__a ) if "in_proj_weight" in key: # split fused qkv proj _a : Dict = val[:hidden_size, :] _a : List[Any] = val[hidden_size : 2 * hidden_size, :] _a : List[Any] = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: _a : Any = val else: _a : Dict = val return state_dict, enc_dec_proj_state_dict def UpperCAmelCase_ (__a : str ): """simple docstring""" if checkpoint == "small": # default config values _a : Union[str, Any] = 1_0_2_4 _a : Any = 2_4 _a : str = 1_6 elif checkpoint == "medium": _a : Tuple = 1_5_3_6 _a : Optional[Any] = 4_8 _a : Union[str, Any] = 2_4 elif checkpoint == "large": _a : Optional[int] = 2_0_4_8 _a : Optional[int] = 4_8 _a : str = 3_2 else: raise ValueError(f"""Checkpoint should be one of `['small', 'medium', 'large']`, got {checkpoint}.""" ) _a : Optional[int] = MusicgenDecoderConfig( hidden_size=__a , ffn_dim=hidden_size * 4 , num_hidden_layers=__a , num_attention_heads=__a , ) return config @torch.no_grad() def UpperCAmelCase_ (__a : List[str] , __a : Dict=None , __a : Optional[Any]=None , __a : Dict="cpu" ): """simple docstring""" _a : Optional[int] = MusicGen.get_pretrained(__a , device=__a ) _a : int = decoder_config_from_checkpoint(__a ) _a : Tuple = fairseq_model.lm.state_dict() _a, _a : int = rename_state_dict( __a , hidden_size=decoder_config.hidden_size ) _a : List[str] = TaEncoderModel.from_pretrained('t5-base' ) _a : List[str] = EncodecModel.from_pretrained('facebook/encodec_32khz' ) _a : int = MusicgenForCausalLM(__a ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection _a, _a : Any = decoder.load_state_dict(__a , strict=__a ) for key in missing_keys.copy(): if key.startswith(('text_encoder', 'audio_encoder') ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(__a ) if len(__a ) > 0: raise ValueError(f"""Missing key(s) in state_dict: {missing_keys}""" ) if len(__a ) > 0: raise ValueError(f"""Unexpected key(s) in state_dict: {unexpected_keys}""" ) # init the composite model _a : List[Any] = MusicgenForConditionalGeneration(text_encoder=__a , audio_encoder=__a , decoder=__a ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(__a ) # check we can do a forward pass _a : Optional[int] = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) _a : Dict = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): _a : Tuple = model(input_ids=__a , decoder_input_ids=__a ).logits if logits.shape != (8, 1, 2_0_4_8): raise ValueError('Incorrect shape for logits' ) # now construct the processor _a : str = AutoTokenizer.from_pretrained('t5-base' ) _a : Dict = AutoFeatureExtractor.from_pretrained('facebook/encodec_32khz' , padding_side='left' ) _a : Optional[Any] = MusicgenProcessor(feature_extractor=__a , tokenizer=__a ) # set the appropriate bos/pad token ids _a : str = 2_0_4_8 _a : Union[str, Any] = 2_0_4_8 # set other default generation config params _a : List[Any] = int(3_0 * audio_encoder.config.frame_rate ) _a : Tuple = True _a : Tuple = 3.0 if pytorch_dump_folder is not None: Path(__a ).mkdir(exist_ok=__a ) logger.info(f"""Saving model {checkpoint} to {pytorch_dump_folder}""" ) model.save_pretrained(__a ) processor.save_pretrained(__a ) if repo_id: logger.info(f"""Pushing model {checkpoint} to {repo_id}""" ) model.push_to_hub(__a ) processor.push_to_hub(__a ) if __name__ == "__main__": __lowerCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--checkpoint""", default="""small""", type=str, help="""Checkpoint size of the MusicGen model you'd like to convert. Can be one of: `['small', 'medium', 'large']`.""", ) parser.add_argument( """--pytorch_dump_folder""", required=True, default=None, type=str, help="""Path to the output PyTorch model directory.""", ) parser.add_argument( """--push_to_hub""", default=None, type=str, help="""Where to upload the converted model on the 🤗 hub.""" ) parser.add_argument( """--device""", default="""cpu""", type=str, help="""Torch device to run the conversion, either cpu or cuda.""" ) __lowerCAmelCase = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
271
'''simple docstring''' import inspect import os import unittest from pathlib import Path import torch import accelerate from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils.testing import run_command class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Optional[Any] = inspect.getfile(accelerate.test_utils ) __UpperCAmelCase : List[str] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_cli.py'''] ) __UpperCAmelCase : Dict = ['''accelerate''', '''launch'''] __UpperCAmelCase : Dict = Path.home() / '''.cache/huggingface/accelerate''' __UpperCAmelCase : Dict = '''default_config.yaml''' __UpperCAmelCase : Optional[Any] = config_folder / config_file __UpperCAmelCase : Dict = config_folder / '''_default_config.yaml''' __UpperCAmelCase : Any = Path('''tests/test_configs''' ) @classmethod def __lowercase ( cls : int ): '''simple docstring''' if cls.config_path.is_file(): cls.config_path.rename(cls.changed_path ) @classmethod def __lowercase ( cls : List[Any] ): '''simple docstring''' if cls.changed_path.is_file(): cls.changed_path.rename(cls.config_path ) def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : Dict = self.base_cmd if torch.cuda.is_available() and (torch.cuda.device_count() > 1): cmd += ["--multi_gpu"] execute_subprocess_async(cmd + [self.test_file_path] ,env=os.environ.copy() ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' for config in sorted(self.test_config_path.glob('**/*.yaml' ) ): with self.subTest(config_file=_a ): execute_subprocess_async( self.base_cmd + ['--config_file', str(_a ), self.test_file_path] ,env=os.environ.copy() ) def __lowercase ( self : Optional[int] ): '''simple docstring''' execute_subprocess_async(['accelerate', 'test'] ,env=os.environ.copy() ) class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Optional[Any] = '''test-tpu''' __UpperCAmelCase : Any = '''us-central1-a''' __UpperCAmelCase : List[Any] = '''ls''' __UpperCAmelCase : Any = ['''accelerate''', '''tpu-config'''] __UpperCAmelCase : Dict = '''cd /usr/share''' __UpperCAmelCase : Any = '''tests/test_samples/test_command_file.sh''' __UpperCAmelCase : List[Any] = '''Running gcloud compute tpus tpu-vm ssh''' def __lowercase ( self : Dict ): '''simple docstring''' _a : Optional[Any] = run_command( self.cmd + ['--command', self.command, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug'] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" ,_a ,) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Any = run_command( self.cmd + [ '--config_file', 'tests/test_configs/0_12_0.yaml', '--command', self.command, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug', ] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" ,_a ,) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Optional[int] = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--debug'] ,return_stdout=_a ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_a ,) def __lowercase ( self : int ): '''simple docstring''' _a : Optional[Any] = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--command', self.command, '--debug'] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" ,_a ,) def __lowercase ( self : str ): '''simple docstring''' _a : List[str] = run_command( self.cmd + [ '--config_file', 'tests/test_configs/latest.yaml', '--command', self.command, '--command', 'echo "Hello World"', '--debug', ] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo \"Hello World\" --worker all""" ,_a ,) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : Any = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--command_file', self.command_file, '--debug'] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_a ,) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : Union[str, Any] = run_command( self.cmd + [ '--config_file', 'tests/test_configs/0_12_0.yaml', '--command_file', self.command_file, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug', ] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_a ,) def __lowercase ( self : Any ): '''simple docstring''' _a : Optional[int] = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--install_accelerate', '--debug'] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_a ,) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Optional[int] = run_command( self.cmd + [ '--config_file', 'tests/test_configs/latest.yaml', '--install_accelerate', '--accelerate_version', '12.0.0', '--debug', ] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_a ,)
271
1
'''simple docstring''' import logging from dataclasses import dataclass, field from pathlib import Path from typing import Optional, Union from .generation.configuration_utils import GenerationConfig from .training_args import TrainingArguments from .utils import add_start_docstrings __lowerCAmelCase = logging.getLogger(__name__) @dataclass @add_start_docstrings(TrainingArguments.__doc__ ) class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : bool = field(default=lowercase__ , metadata={'''help''': '''Whether to use SortishSampler or not.'''} ) __UpperCAmelCase : bool = field( default=lowercase__ , metadata={'''help''': '''Whether to use generate to calculate generative metrics (ROUGE, BLEU).'''} ) __UpperCAmelCase : Optional[int] = field( default=lowercase__ , metadata={ '''help''': ( '''The `max_length` to use on each evaluation loop when `predict_with_generate=True`. Will default ''' '''to the `max_length` value of the model configuration.''' ) } , ) __UpperCAmelCase : Optional[int] = field( default=lowercase__ , metadata={ '''help''': ( '''The `num_beams` to use on each evaluation loop when `predict_with_generate=True`. Will default ''' '''to the `num_beams` value of the model configuration.''' ) } , ) __UpperCAmelCase : Optional[Union[str, Path, GenerationConfig]] = field( default=lowercase__ , metadata={ '''help''': '''Model id, file path or url pointing to a GenerationConfig json file, to use during prediction.''' } , ) def __lowercase ( self : str ): '''simple docstring''' _a : Optional[int] = super().to_dict() for k, v in d.items(): if isinstance(_a ,_a ): _a : Tuple = v.to_dict() return d
271
'''simple docstring''' from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar __lowerCAmelCase = TypeVar("""T""") class UpperCAmelCase__ ( Generic[T] ): """simple docstring""" def __init__( self : Tuple ,_a : T ): '''simple docstring''' _a : List[str] = data _a : Node[T] | None = None def __str__( self : Dict ): '''simple docstring''' return F"""{self.data}""" class UpperCAmelCase__ ( Generic[T] ): """simple docstring""" def __init__( self : Optional[int] ): '''simple docstring''' _a : Node[T] | None = None def __iter__( self : str ): '''simple docstring''' _a : Tuple = self.top while node: yield node.data _a : int = node.next def __str__( self : str ): '''simple docstring''' return "->".join([str(_a ) for item in self] ) def __len__( self : Optional[Any] ): '''simple docstring''' return len(tuple(iter(self ) ) ) def __lowercase ( self : str ): '''simple docstring''' return self.top is None def __lowercase ( self : List[Any] ,_a : T ): '''simple docstring''' _a : int = Node(_a ) if not self.is_empty(): _a : Optional[Any] = self.top _a : List[str] = node def __lowercase ( self : Tuple ): '''simple docstring''' if self.is_empty(): raise IndexError('pop from empty stack' ) assert isinstance(self.top ,_a ) _a : List[Any] = self.top _a : int = self.top.next return pop_node.data def __lowercase ( self : List[str] ): '''simple docstring''' if self.is_empty(): raise IndexError('peek from empty stack' ) assert self.top is not None return self.top.data def __lowercase ( self : List[str] ): '''simple docstring''' _a : Optional[int] = None if __name__ == "__main__": from doctest import testmod testmod()
271
1
'''simple docstring''' import argparse import torch from transformers import ( EncodecConfig, EncodecFeatureExtractor, EncodecModel, logging, ) # checkpoints downloaded from: # https://dl.fbaipublicfiles.com/encodec/v0/encodec_24khz-d7cc33bc.th # https://huggingface.co/facebook/musicgen-small/resolve/main/compression_state_dict.bin # https://dl.fbaipublicfiles.com/encodec/v0/encodec_48khz-7e698e3e.th logging.set_verbosity_info() __lowerCAmelCase = logging.get_logger("""transformers.models.encodec""") __lowerCAmelCase = { """quantizer.vq.layers.*._codebook.inited""": """quantizer.layers.*.codebook.inited""", """quantizer.vq.layers.*._codebook.cluster_size""": """quantizer.layers.*.codebook.cluster_size""", """quantizer.vq.layers.*._codebook.embed""": """quantizer.layers.*.codebook.embed""", """quantizer.vq.layers.*._codebook.embed_avg""": """quantizer.layers.*.codebook.embed_avg""", } __lowerCAmelCase = { """encoder.model.0.conv.conv""": """encoder.layers.0.conv""", """encoder.model.1.block.1.conv.conv""": """encoder.layers.1.block.1.conv""", """encoder.model.1.block.3.conv.conv""": """encoder.layers.1.block.3.conv""", """encoder.model.1.shortcut.conv.conv""": """encoder.layers.1.shortcut.conv""", """encoder.model.3.conv.conv""": """encoder.layers.3.conv""", """encoder.model.4.block.1.conv.conv""": """encoder.layers.4.block.1.conv""", """encoder.model.4.block.3.conv.conv""": """encoder.layers.4.block.3.conv""", """encoder.model.4.shortcut.conv.conv""": """encoder.layers.4.shortcut.conv""", """encoder.model.6.conv.conv""": """encoder.layers.6.conv""", """encoder.model.7.block.1.conv.conv""": """encoder.layers.7.block.1.conv""", """encoder.model.7.block.3.conv.conv""": """encoder.layers.7.block.3.conv""", """encoder.model.7.shortcut.conv.conv""": """encoder.layers.7.shortcut.conv""", """encoder.model.9.conv.conv""": """encoder.layers.9.conv""", """encoder.model.10.block.1.conv.conv""": """encoder.layers.10.block.1.conv""", """encoder.model.10.block.3.conv.conv""": """encoder.layers.10.block.3.conv""", """encoder.model.10.shortcut.conv.conv""": """encoder.layers.10.shortcut.conv""", """encoder.model.12.conv.conv""": """encoder.layers.12.conv""", """encoder.model.13.lstm""": """encoder.layers.13.lstm""", """encoder.model.15.conv.conv""": """encoder.layers.15.conv""", } __lowerCAmelCase = { """encoder.model.0.conv.norm""": """encoder.layers.0.norm""", """encoder.model.1.block.1.conv.norm""": """encoder.layers.1.block.1.norm""", """encoder.model.1.block.3.conv.norm""": """encoder.layers.1.block.3.norm""", """encoder.model.1.shortcut.conv.norm""": """encoder.layers.1.shortcut.norm""", """encoder.model.3.conv.norm""": """encoder.layers.3.norm""", """encoder.model.4.block.1.conv.norm""": """encoder.layers.4.block.1.norm""", """encoder.model.4.block.3.conv.norm""": """encoder.layers.4.block.3.norm""", """encoder.model.4.shortcut.conv.norm""": """encoder.layers.4.shortcut.norm""", """encoder.model.6.conv.norm""": """encoder.layers.6.norm""", """encoder.model.7.block.1.conv.norm""": """encoder.layers.7.block.1.norm""", """encoder.model.7.block.3.conv.norm""": """encoder.layers.7.block.3.norm""", """encoder.model.7.shortcut.conv.norm""": """encoder.layers.7.shortcut.norm""", """encoder.model.9.conv.norm""": """encoder.layers.9.norm""", """encoder.model.10.block.1.conv.norm""": """encoder.layers.10.block.1.norm""", """encoder.model.10.block.3.conv.norm""": """encoder.layers.10.block.3.norm""", """encoder.model.10.shortcut.conv.norm""": """encoder.layers.10.shortcut.norm""", """encoder.model.12.conv.norm""": """encoder.layers.12.norm""", """encoder.model.15.conv.norm""": """encoder.layers.15.norm""", } __lowerCAmelCase = { """decoder.model.0.conv.conv""": """decoder.layers.0.conv""", """decoder.model.1.lstm""": """decoder.layers.1.lstm""", """decoder.model.3.convtr.convtr""": """decoder.layers.3.conv""", """decoder.model.4.block.1.conv.conv""": """decoder.layers.4.block.1.conv""", """decoder.model.4.block.3.conv.conv""": """decoder.layers.4.block.3.conv""", """decoder.model.4.shortcut.conv.conv""": """decoder.layers.4.shortcut.conv""", """decoder.model.6.convtr.convtr""": """decoder.layers.6.conv""", """decoder.model.7.block.1.conv.conv""": """decoder.layers.7.block.1.conv""", """decoder.model.7.block.3.conv.conv""": """decoder.layers.7.block.3.conv""", """decoder.model.7.shortcut.conv.conv""": """decoder.layers.7.shortcut.conv""", """decoder.model.9.convtr.convtr""": """decoder.layers.9.conv""", """decoder.model.10.block.1.conv.conv""": """decoder.layers.10.block.1.conv""", """decoder.model.10.block.3.conv.conv""": """decoder.layers.10.block.3.conv""", """decoder.model.10.shortcut.conv.conv""": """decoder.layers.10.shortcut.conv""", """decoder.model.12.convtr.convtr""": """decoder.layers.12.conv""", """decoder.model.13.block.1.conv.conv""": """decoder.layers.13.block.1.conv""", """decoder.model.13.block.3.conv.conv""": """decoder.layers.13.block.3.conv""", """decoder.model.13.shortcut.conv.conv""": """decoder.layers.13.shortcut.conv""", """decoder.model.15.conv.conv""": """decoder.layers.15.conv""", } __lowerCAmelCase = { """decoder.model.0.conv.norm""": """decoder.layers.0.norm""", """decoder.model.3.convtr.norm""": """decoder.layers.3.norm""", """decoder.model.4.block.1.conv.norm""": """decoder.layers.4.block.1.norm""", """decoder.model.4.block.3.conv.norm""": """decoder.layers.4.block.3.norm""", """decoder.model.4.shortcut.conv.norm""": """decoder.layers.4.shortcut.norm""", """decoder.model.6.convtr.norm""": """decoder.layers.6.norm""", """decoder.model.7.block.1.conv.norm""": """decoder.layers.7.block.1.norm""", """decoder.model.7.block.3.conv.norm""": """decoder.layers.7.block.3.norm""", """decoder.model.7.shortcut.conv.norm""": """decoder.layers.7.shortcut.norm""", """decoder.model.9.convtr.norm""": """decoder.layers.9.norm""", """decoder.model.10.block.1.conv.norm""": """decoder.layers.10.block.1.norm""", """decoder.model.10.block.3.conv.norm""": """decoder.layers.10.block.3.norm""", """decoder.model.10.shortcut.conv.norm""": """decoder.layers.10.shortcut.norm""", """decoder.model.12.convtr.norm""": """decoder.layers.12.norm""", """decoder.model.13.block.1.conv.norm""": """decoder.layers.13.block.1.norm""", """decoder.model.13.block.3.conv.norm""": """decoder.layers.13.block.3.norm""", """decoder.model.13.shortcut.conv.norm""": """decoder.layers.13.shortcut.norm""", """decoder.model.15.conv.norm""": """decoder.layers.15.norm""", } __lowerCAmelCase = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_DECODER, } __lowerCAmelCase = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_ENCODER_48K, **MAPPING_DECODER, **MAPPING_DECODER_48K, } __lowerCAmelCase = [] __lowerCAmelCase = [] def UpperCAmelCase_ (__a : Union[str, Any] , __a : Dict , __a : Any , __a : Dict , __a : int ): """simple docstring""" for attribute in key.split('.' ): _a : List[Any] = getattr(__a , __a ) if weight_type is not None: _a : List[Any] = getattr(__a , __a ).shape else: _a : List[str] = hf_pointer.shape if hf_shape != value.shape: raise ValueError( 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": _a : Tuple = value elif weight_type == "weight_g": _a : Dict = value elif weight_type == "weight_v": _a : str = value elif weight_type == "bias": _a : Dict = value elif weight_type == "running_mean": _a : str = value elif weight_type == "running_var": _a : str = value elif weight_type == "num_batches_tracked": _a : Optional[Any] = value elif weight_type == "weight_ih_l0": _a : List[Any] = value elif weight_type == "weight_hh_l0": _a : int = value elif weight_type == "bias_ih_l0": _a : Optional[int] = value elif weight_type == "bias_hh_l0": _a : Dict = value elif weight_type == "weight_ih_l1": _a : str = value elif weight_type == "weight_hh_l1": _a : Dict = value elif weight_type == "bias_ih_l1": _a : Union[str, Any] = value elif weight_type == "bias_hh_l1": _a : Tuple = value else: _a : Dict = value logger.info(f"""{key + ('.' + weight_type if weight_type is not None else '')} was initialized from {full_name}.""" ) def UpperCAmelCase_ (__a : Tuple , __a : Optional[Any] ): """simple docstring""" for key in ignore_keys: if key.endswith('.*' ): if name.startswith(key[:-1] ): return True elif ".*." in key: _a, _a : int = key.split('.*.' ) if prefix in name and suffix in name: return True elif key in name: return True return False def UpperCAmelCase_ (__a : List[str] , __a : str , __a : Optional[int] ): """simple docstring""" _a : Optional[int] = [] if model_name == "encodec_24khz" or "encodec_32khz": _a : Tuple = MAPPING_24K elif model_name == "encodec_48khz": _a : Any = MAPPING_48K else: raise ValueError(f"""Unsupported model: {model_name}""" ) for name, value in orig_dict.items(): if should_ignore(__a , __a ): logger.info(f"""{name} was ignored""" ) continue _a : Tuple = False for key, mapped_key in MAPPING.items(): if "*" in key: _a, _a : Union[str, Any] = key.split('.*.' ) if prefix in name and suffix in name: _a : Union[str, Any] = suffix if key in name: # HACK otherwise .embed gets initialized with .embed_avg too if key.endswith('embed' ) and name.endswith('embed_avg' ): continue _a : int = True if "*" in mapped_key: _a : int = name.split(__a )[0].split('.' )[-2] _a : Dict = mapped_key.replace('*' , __a ) if "weight_g" in name: _a : List[Any] = 'weight_g' elif "weight_v" in name: _a : List[str] = 'weight_v' elif "weight_ih_l0" in name: _a : Tuple = 'weight_ih_l0' elif "weight_hh_l0" in name: _a : Optional[Any] = 'weight_hh_l0' elif "bias_ih_l0" in name: _a : List[str] = 'bias_ih_l0' elif "bias_hh_l0" in name: _a : Union[str, Any] = 'bias_hh_l0' elif "weight_ih_l1" in name: _a : Dict = 'weight_ih_l1' elif "weight_hh_l1" in name: _a : Optional[int] = 'weight_hh_l1' elif "bias_ih_l1" in name: _a : Optional[Any] = 'bias_ih_l1' elif "bias_hh_l1" in name: _a : Dict = 'bias_hh_l1' elif "bias" in name: _a : List[Any] = 'bias' elif "weight" in name: _a : Dict = 'weight' elif "running_mean" in name: _a : Optional[Any] = 'running_mean' elif "running_var" in name: _a : List[Any] = 'running_var' elif "num_batches_tracked" in name: _a : Tuple = 'num_batches_tracked' else: _a : List[str] = None set_recursively(__a , __a , __a , __a , __a ) continue if not is_used: unused_weights.append(__a ) logger.warning(f"""Unused weights: {unused_weights}""" ) @torch.no_grad() def UpperCAmelCase_ (__a : Optional[Any] , __a : Any , __a : Dict , __a : List[str]=None , __a : str=None , ): """simple docstring""" if config_path is not None: _a : str = EncodecConfig.from_pretrained(__a ) else: _a : Optional[int] = EncodecConfig() if model_name == "encodec_24khz": pass # config is already correct elif model_name == "encodec_32khz": _a : str = [8, 5, 4, 4] _a : Tuple = [2.2] _a : Tuple = 6_4 _a : Optional[Any] = 3_2_0_0_0 _a : List[str] = 2_0_4_8 _a : Optional[int] = False _a : Optional[int] = False _a : Dict = False elif model_name == "encodec_48khz": _a : int = [8, 5, 4, 2] _a : Dict = [3.0, 6.0, 12.0, 24.0] _a : Union[str, Any] = 4_8_0_0_0 _a : Union[str, Any] = 2 _a : Tuple = False _a : str = 'time_group_norm' _a : Any = True _a : Tuple = 1.0 _a : Tuple = 0.01 else: raise ValueError(f"""Unknown model name: {model_name}""" ) _a : Union[str, Any] = EncodecModel(__a ) _a : Tuple = EncodecFeatureExtractor( feature_size=config.audio_channels , sampling_rate=config.sampling_rate , chunk_length_s=config.chunk_length_s , overlap=config.overlap , ) feature_extractor.save_pretrained(__a ) _a : Any = torch.load(__a ) if "best_state" in original_checkpoint: # we might have a training state saved, in which case discard the yaml results and just retain the weights _a : List[Any] = original_checkpoint['best_state'] recursively_load_weights(__a , __a , __a ) model.save_pretrained(__a ) if repo_id: print('Pushing to the hub...' ) feature_extractor.push_to_hub(__a ) model.push_to_hub(__a ) if __name__ == "__main__": __lowerCAmelCase = argparse.ArgumentParser() parser.add_argument( """--model""", default="""encodec_24khz""", type=str, help="""The model to convert. Should be one of 'encodec_24khz', 'encodec_32khz', 'encodec_48khz'.""", ) parser.add_argument("""--checkpoint_path""", required=True, default=None, type=str, help="""Path to original checkpoint""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--pytorch_dump_folder_path""", required=True, default=None, type=str, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--push_to_hub""", default=None, type=str, help="""Where to upload the converted model on the 🤗 hub.""" ) __lowerCAmelCase = parser.parse_args() convert_checkpoint( args.model, args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
271
'''simple docstring''' import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" @property def __lowercase ( self : List[str] ): '''simple docstring''' torch.manual_seed(0 ) _a : int = UNetaDModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=3 ,out_channels=3 ,down_block_types=('DownBlock2D', 'AttnDownBlock2D') ,up_block_types=('AttnUpBlock2D', 'UpBlock2D') ,) return model def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a : str = self.dummy_uncond_unet _a : int = PNDMScheduler() _a : str = PNDMPipeline(unet=_a ,scheduler=_a ) pndm.to(_a ) pndm.set_progress_bar_config(disable=_a ) _a : Optional[int] = torch.manual_seed(0 ) _a : Optional[Any] = pndm(generator=_a ,num_inference_steps=20 ,output_type='numpy' ).images _a : List[str] = torch.manual_seed(0 ) _a : Any = pndm(generator=_a ,num_inference_steps=20 ,output_type='numpy' ,return_dict=_a )[0] _a : List[Any] = image[0, -3:, -3:, -1] _a : Any = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _a : List[Any] = np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self : Tuple ): '''simple docstring''' _a : List[str] = 'google/ddpm-cifar10-32' _a : str = UNetaDModel.from_pretrained(_a ) _a : Union[str, Any] = PNDMScheduler() _a : Tuple = PNDMPipeline(unet=_a ,scheduler=_a ) pndm.to(_a ) pndm.set_progress_bar_config(disable=_a ) _a : str = torch.manual_seed(0 ) _a : Optional[Any] = pndm(generator=_a ,output_type='numpy' ).images _a : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _a : Tuple = np.array([0.1564, 0.1_4645, 0.1406, 0.1_4715, 0.1_2425, 0.1_4045, 0.1_3115, 0.1_2175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
271
1
'''simple docstring''' def UpperCAmelCase_ (__a : int ): """simple docstring""" _a : int = int(__a ) if n_element < 1: _a : int = ValueError('a should be a positive number' ) raise my_error _a : List[Any] = [1] _a, _a, _a : Optional[int] = (0, 0, 0) _a : Tuple = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": __lowerCAmelCase = input("""Enter the last number (nth term) of the Hamming Number Series: """) print("""Formula of Hamming Number Series => 2^i * 3^j * 5^k""") __lowerCAmelCase = hamming(int(n)) print("""-----------------------------------------------------""") print(f'''The list with nth numbers is: {hamming_numbers}''') print("""-----------------------------------------------------""")
271
'''simple docstring''' import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow __lowerCAmelCase = logging.getLogger() @unittest.skip('''Temporarily disable the doc tests.''' ) @require_torch @require_tf @slow class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self : str ,_a : Path ,_a : Union[str, None] = None ,_a : Union[List[str], None] = None ,_a : Union[str, List[str], None] = None ,_a : bool = True ,): '''simple docstring''' _a : Optional[int] = [file for file in os.listdir(_a ) if os.path.isfile(os.path.join(_a ,_a ) )] if identifier is not None: _a : List[str] = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(_a ,_a ): for n_ in n_identifier: _a : Tuple = [file for file in files if n_ not in file] else: _a : Optional[Any] = [file for file in files if n_identifier not in file] _a : List[str] = ignore_files or [] ignore_files.append('__init__.py' ) _a : Tuple = [file for file in files if file not in ignore_files] for file in files: # Open all files print('Testing' ,_a ) if only_modules: _a : Any = file.split('.' )[0] try: _a : List[str] = getattr(_a ,_a ) _a : int = doctest.DocTestSuite(_a ) _a : Any = unittest.TextTestRunner().run(_a ) self.assertIs(len(result.failures ) ,0 ) except AttributeError: logger.info(F"""{module_identifier} is not a module.""" ) else: _a : Union[str, Any] = doctest.testfile(str('..' / directory / file ) ,optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed ,0 ) def __lowercase ( self : Any ): '''simple docstring''' _a : int = Path('src/transformers' ) _a : List[Any] = 'modeling' _a : Optional[Any] = [ 'modeling_ctrl.py', 'modeling_tf_ctrl.py', ] self.analyze_directory(_a ,identifier=_a ,ignore_files=_a ) def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : Optional[Any] = Path('src/transformers' ) _a : Optional[Any] = 'tokenization' self.analyze_directory(_a ,identifier=_a ) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Dict = Path('src/transformers' ) _a : str = 'configuration' self.analyze_directory(_a ,identifier=_a ) def __lowercase ( self : Any ): '''simple docstring''' _a : Tuple = Path('src/transformers' ) _a : List[Any] = ['configuration', 'modeling', 'tokenization'] self.analyze_directory(_a ,n_identifier=_a ) def __lowercase ( self : Tuple ): '''simple docstring''' _a : List[Any] = Path('docs/source' ) _a : List[str] = ['favicon.ico'] self.analyze_directory(_a ,ignore_files=_a ,only_modules=_a )
271
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import _LazyModule __lowerCAmelCase = {"""tokenization_wav2vec2_phoneme""": ["""Wav2Vec2PhonemeCTCTokenizer"""]} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
271
'''simple docstring''' import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def UpperCAmelCase_ (__a : Optional[Any] , __a : str , __a : Optional[Any]=None ): """simple docstring""" assert torch_layer.weight.shape == weight.shape, f"""{torch_layer} layer.weight does not match""" _a : str = nn.Parameter(__a ) if bias is not None: assert torch_layer.bias.shape == bias.shape, f"""{torch_layer} layer.bias does not match""" _a : Any = nn.Parameter(__a ) def UpperCAmelCase_ (__a : int , __a : Optional[Any] , __a : int ): """simple docstring""" _a : Tuple = np.asarray(weights[0] ) _a : Union[str, Any] = np.asarray(weights[1] ) _a : Dict = np.asarray(weights[2] ) set_param( torch_layer.self_attention.query_key , torch.tensor(__a ).transpose(1 , 2 ).contiguous().view(-1 , __a ) , ) set_param( torch_layer.self_attention.value , torch.tensor(__a ).transpose(1 , 2 ).contiguous().view(-1 , __a ) , ) set_param( torch_layer.output.dense , torch.tensor(__a ).view(-1 , __a ).contiguous().transpose(0 , 1 ) , ) def UpperCAmelCase_ (__a : Optional[Any] , __a : Optional[int] , __a : List[str] ): """simple docstring""" _a : Dict = np.asarray(weights[0] ) _a : Union[str, Any] = np.asarray(weights[1] ) _a : str = np.asarray(weights[2] ) _a : int = np.asarray(weights[3] ) set_param( torch_layer.self_attention.query , torch.tensor(__a ).transpose(1 , 2 ).contiguous().view(-1 , __a ) , ) set_param( torch_layer.self_attention.key , torch.tensor(__a ).transpose(1 , 2 ).contiguous().view(-1 , __a ) , ) set_param( torch_layer.self_attention.value , torch.tensor(__a ).transpose(1 , 2 ).contiguous().view(-1 , __a ) , ) set_param( torch_layer.output.dense , torch.tensor(__a ).view(-1 , __a ).contiguous().transpose(0 , 1 ) , ) def UpperCAmelCase_ (__a : Any , __a : Any , __a : Optional[Any] ): """simple docstring""" _a : List[str] = weights[0][0][0] _a : List[Any] = np.asarray(layer_norm_a[0] ) _a : List[str] = np.asarray(layer_norm_a[1] ) set_param( torch_block.attention.layer_norm , torch.tensor(__a ) , torch.tensor(__a ) , ) # lsh weights + output _a : List[str] = weights[0][1] if len(__a ) < 4: set_layer_weights_in_torch_lsh(__a , torch_block.attention , __a ) else: set_layer_weights_in_torch_local(__a , torch_block.attention , __a ) # intermediate weighs _a : Optional[Any] = weights[2][0][1][2] # Chunked Feed Forward if len(__a ) == 4: _a : Union[str, Any] = intermediate_weights[2] # layernorm 2 _a : Any = np.asarray(intermediate_weights[0][0] ) _a : List[Any] = np.asarray(intermediate_weights[0][1] ) set_param( torch_block.feed_forward.layer_norm , torch.tensor(__a ) , torch.tensor(__a ) , ) # intermediate dense _a : Any = np.asarray(intermediate_weights[1][0] ) _a : Any = np.asarray(intermediate_weights[1][1] ) set_param( torch_block.feed_forward.dense.dense , torch.tensor(__a ).transpose(0 , 1 ).contiguous() , torch.tensor(__a ) , ) # intermediate out _a : Optional[int] = np.asarray(intermediate_weights[4][0] ) _a : int = np.asarray(intermediate_weights[4][1] ) set_param( torch_block.feed_forward.output.dense , torch.tensor(__a ).transpose(0 , 1 ).contiguous() , torch.tensor(__a ) , ) def UpperCAmelCase_ (__a : Dict , __a : Dict , __a : List[Any] ): """simple docstring""" _a : Optional[int] = torch_model.reformer # word embeds _a : Tuple = np.asarray(weights[1] ) set_param( torch_model_reformer.embeddings.word_embeddings , torch.tensor(__a ) , ) if isinstance(weights[3] , __a ): _a : Any = torch_model_reformer.embeddings.position_embeddings for emb_idx in range(len(position_embeddings.weights ) ): _a : List[Any] = np.asarray(weights[3][emb_idx][0] ) assert ( position_embeddings.weights[emb_idx].shape == emb_weights.shape ), f"""{position_embeddings[emb_idx]} emb does not match""" _a : Any = nn.Parameter(torch.tensor(__a ) ) _a : List[str] = weights[5] assert len(torch_model_reformer.encoder.layers ) * 4 == len( __a ), "HF and trax model do not have the same number of layers" for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ): _a : Tuple = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)] set_block_weights_in_torch(__a , __a , __a ) # output layer norm _a : Optional[Any] = np.asarray(weights[7][0] ) _a : int = np.asarray(weights[7][1] ) set_param( torch_model_reformer.encoder.layer_norm , torch.tensor(__a ) , torch.tensor(__a ) , ) # output embeddings _a : List[str] = np.asarray(weights[9][0] ) _a : int = np.asarray(weights[9][1] ) set_param( torch_model.lm_head.decoder , torch.tensor(__a ).transpose(0 , 1 ).contiguous() , torch.tensor(__a ) , ) def UpperCAmelCase_ (__a : Tuple , __a : Optional[Any] , __a : Dict ): """simple docstring""" _a : List[Any] = ReformerConfig.from_json_file(__a ) print(f"""Building PyTorch model from configuration: {config}""" ) _a : int = ReformerModelWithLMHead(__a ) with open(__a , 'rb' ) as f: _a : Optional[Any] = pickle.load(__a )['weights'] set_model_weights_in_torch(__a , __a , config.hidden_size ) # Save pytorch-model print(f"""Save PyTorch model to {pytorch_dump_path}""" ) torch.save(model.state_dict() , __a ) if __name__ == "__main__": __lowerCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--trax_model_pkl_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained Reformer model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) __lowerCAmelCase = parser.parse_args() convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
271
1
'''simple docstring''' import enum import os from hashlib import shaaaa from typing import Optional from .. import config from .logging import get_logger __lowerCAmelCase = get_logger(__name__) class UpperCAmelCase__ ( enum.Enum ): """simple docstring""" __UpperCAmelCase : Any = '''all_checks''' __UpperCAmelCase : Dict = '''basic_checks''' __UpperCAmelCase : Optional[Any] = '''no_checks''' class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" def UpperCAmelCase_ (__a : Optional[dict] , __a : dict , __a : int=None ): """simple docstring""" if expected_checksums is None: logger.info('Unable to verify checksums.' ) return if len(set(__a ) - set(__a ) ) > 0: raise ExpectedMoreDownloadedFiles(str(set(__a ) - set(__a ) ) ) if len(set(__a ) - set(__a ) ) > 0: raise UnexpectedDownloadedFile(str(set(__a ) - set(__a ) ) ) _a : Tuple = [url for url in expected_checksums if expected_checksums[url] != recorded_checksums[url]] _a : Optional[Any] = ' for ' + verification_name if verification_name is not None else '' if len(__a ) > 0: raise NonMatchingChecksumError( f"""Checksums didn't match{for_verification_name}:\n""" f"""{bad_urls}\n""" 'Set `verification_mode=\'no_checks\'` to skip checksums verification and ignore this error' ) logger.info('All the checksums matched successfully' + for_verification_name ) class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" def UpperCAmelCase_ (__a : Optional[dict] , __a : dict ): """simple docstring""" if expected_splits is None: logger.info('Unable to verify splits sizes.' ) return if len(set(__a ) - set(__a ) ) > 0: raise ExpectedMoreSplits(str(set(__a ) - set(__a ) ) ) if len(set(__a ) - set(__a ) ) > 0: raise UnexpectedSplits(str(set(__a ) - set(__a ) ) ) _a : Optional[Any] = [ {'expected': expected_splits[name], 'recorded': recorded_splits[name]} for name in expected_splits if expected_splits[name].num_examples != recorded_splits[name].num_examples ] if len(__a ) > 0: raise NonMatchingSplitsSizesError(str(__a ) ) logger.info('All the splits matched successfully.' ) def UpperCAmelCase_ (__a : str , __a : bool = True ): """simple docstring""" if record_checksum: _a : int = shaaaa() with open(__a , 'rb' ) as f: for chunk in iter(lambda: f.read(1 << 2_0 ) , b'' ): m.update(__a ) _a : Tuple = m.hexdigest() else: _a : List[Any] = None return {"num_bytes": os.path.getsize(__a ), "checksum": checksum} def UpperCAmelCase_ (__a : Union[str, Any] ): """simple docstring""" if dataset_size and config.IN_MEMORY_MAX_SIZE: return dataset_size < config.IN_MEMORY_MAX_SIZE else: return False
271
'''simple docstring''' import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" @property def __lowercase ( self : Union[str, Any] ): '''simple docstring''' torch.manual_seed(0 ) _a : Any = UNetaDModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=3 ,out_channels=3 ,down_block_types=('DownBlock2D', 'AttnDownBlock2D') ,up_block_types=('AttnUpBlock2D', 'UpBlock2D') ,) return model @property def __lowercase ( self : Optional[int] ): '''simple docstring''' torch.manual_seed(0 ) _a : Union[str, Any] = VQModel( block_out_channels=[32, 64] ,in_channels=3 ,out_channels=3 ,down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] ,up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] ,latent_channels=3 ,) return model @property def __lowercase ( self : Optional[int] ): '''simple docstring''' torch.manual_seed(0 ) _a : Any = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1E-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1000 ,) return CLIPTextModel(_a ) def __lowercase ( self : Tuple ): '''simple docstring''' _a : Dict = self.dummy_uncond_unet _a : List[Any] = DDIMScheduler() _a : List[Any] = self.dummy_vq_model _a : str = LDMPipeline(unet=_a ,vqvae=_a ,scheduler=_a ) ldm.to(_a ) ldm.set_progress_bar_config(disable=_a ) _a : List[str] = torch.manual_seed(0 ) _a : List[str] = ldm(generator=_a ,num_inference_steps=2 ,output_type='numpy' ).images _a : List[str] = torch.manual_seed(0 ) _a : Union[str, Any] = ldm(generator=_a ,num_inference_steps=2 ,output_type='numpy' ,return_dict=_a )[0] _a : Tuple = image[0, -3:, -3:, -1] _a : Optional[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _a : int = np.array([0.8512, 0.818, 0.6411, 0.6808, 0.4465, 0.5618, 0.46, 0.6231, 0.5172] ) _a : Any = 1E-2 if torch_device != 'mps' else 3E-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < tolerance @slow @require_torch class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a : List[str] = LDMPipeline.from_pretrained('CompVis/ldm-celebahq-256' ) ldm.to(_a ) ldm.set_progress_bar_config(disable=_a ) _a : Optional[int] = torch.manual_seed(0 ) _a : Dict = ldm(generator=_a ,num_inference_steps=5 ,output_type='numpy' ).images _a : str = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) _a : Optional[int] = np.array([0.4399, 0.4_4975, 0.4_6825, 0.474, 0.4359, 0.4581, 0.4_5095, 0.4341, 0.4447] ) _a : int = 1E-2 if torch_device != 'mps' else 3E-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance
271
1
'''simple docstring''' 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 UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self : int ): '''simple docstring''' _a : Dict = tempfile.mkdtemp() _a : str = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] _a : Dict = 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 : List[Any] = { '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 : Optional[int] = os.path.join(self.tmpdirname ,_a ) with open(self.image_processor_file ,'w' ,encoding='utf-8' ) as fp: json.dump(_a ,_a ) def __lowercase ( self : Dict ,**_a : List[str] ): '''simple docstring''' return BertTokenizer.from_pretrained(self.tmpdirname ,**_a ) def __lowercase ( self : List[Any] ,**_a : List[str] ): '''simple docstring''' return BertTokenizerFast.from_pretrained(self.tmpdirname ,**_a ) def __lowercase ( self : Union[str, Any] ,**_a : Union[str, Any] ): '''simple docstring''' return EfficientNetImageProcessor.from_pretrained(self.tmpdirname ,**_a ) def __lowercase ( self : Optional[int] ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def __lowercase ( self : int ): '''simple docstring''' _a : Tuple = [np.random.randint(255 ,size=(3, 30, 400) ,dtype=np.uinta )] _a : Tuple = [Image.fromarray(np.moveaxis(_a ,0 ,-1 ) ) for x in image_inputs] return image_inputs def __lowercase ( self : str ): '''simple docstring''' _a : Tuple = self.get_tokenizer() _a : Optional[Any] = self.get_rust_tokenizer() _a : str = self.get_image_processor() _a : Dict = AlignProcessor(tokenizer=_a ,image_processor=_a ) processor_slow.save_pretrained(self.tmpdirname ) _a : Union[str, Any] = AlignProcessor.from_pretrained(self.tmpdirname ,use_fast=_a ) _a : Union[str, Any] = AlignProcessor(tokenizer=_a ,image_processor=_a ) processor_fast.save_pretrained(self.tmpdirname ) _a : Any = 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 ,_a ) self.assertIsInstance(processor_fast.tokenizer ,_a ) 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 ,_a ) self.assertIsInstance(processor_fast.image_processor ,_a ) def __lowercase ( self : int ): '''simple docstring''' _a : Optional[Any] = AlignProcessor(tokenizer=self.get_tokenizer() ,image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) _a : int = self.get_tokenizer(bos_token='(BOS)' ,eos_token='(EOS)' ) _a : List[str] = self.get_image_processor(do_normalize=_a ,padding_value=1.0 ) _a : Union[str, Any] = AlignProcessor.from_pretrained( self.tmpdirname ,bos_token='(BOS)' ,eos_token='(EOS)' ,do_normalize=_a ,padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() ,tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer ,_a ) self.assertEqual(processor.image_processor.to_json_string() ,image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor ,_a ) def __lowercase ( self : Tuple ): '''simple docstring''' _a : Tuple = self.get_image_processor() _a : List[str] = self.get_tokenizer() _a : Optional[int] = AlignProcessor(tokenizer=_a ,image_processor=_a ) _a : List[Any] = self.prepare_image_inputs() _a : Union[str, Any] = image_processor(_a ,return_tensors='np' ) _a : Any = processor(images=_a ,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 __lowercase ( self : Tuple ): '''simple docstring''' _a : Any = self.get_image_processor() _a : Tuple = self.get_tokenizer() _a : Optional[int] = AlignProcessor(tokenizer=_a ,image_processor=_a ) _a : Union[str, Any] = 'lower newer' _a : List[Any] = processor(text=_a ) _a : Any = tokenizer(_a ,padding='max_length' ,max_length=64 ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] ,encoded_processor[key] ) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Dict = self.get_image_processor() _a : List[str] = self.get_tokenizer() _a : Union[str, Any] = AlignProcessor(tokenizer=_a ,image_processor=_a ) _a : Any = 'lower newer' _a : Tuple = self.prepare_image_inputs() _a : Dict = processor(text=_a ,images=_a ) 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(_a ): processor() def __lowercase ( self : Tuple ): '''simple docstring''' _a : Any = self.get_image_processor() _a : Any = self.get_tokenizer() _a : Any = AlignProcessor(tokenizer=_a ,image_processor=_a ) _a : Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] _a : List[str] = processor.batch_decode(_a ) _a : Optional[Any] = tokenizer.batch_decode(_a ) self.assertListEqual(_a ,_a ) def __lowercase ( self : Tuple ): '''simple docstring''' _a : Optional[int] = self.get_image_processor() _a : int = self.get_tokenizer() _a : str = AlignProcessor(tokenizer=_a ,image_processor=_a ) _a : Tuple = 'lower newer' _a : Union[str, Any] = self.prepare_image_inputs() _a : int = processor(text=_a ,images=_a ) self.assertListEqual(list(inputs.keys() ) ,processor.model_input_names )
271
'''simple docstring''' import warnings from ...utils import logging from .image_processing_beit import BeitImageProcessor __lowerCAmelCase = logging.get_logger(__name__) class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" def __init__( self : int ,*_a : Optional[int] ,**_a : str ): '''simple docstring''' warnings.warn( 'The class BeitFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use BeitImageProcessor instead.' ,_a ,) super().__init__(*_a ,**_a )
271
1
'''simple docstring''' def UpperCAmelCase_ (__a : int = 1_0_0_0 ): """simple docstring""" return sum(2 * a * ((a - 1) // 2) for a in range(3 , n + 1 ) ) if __name__ == "__main__": print(solution())
271
'''simple docstring''' from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.utils.data import DistributedSampler, RandomSampler from transformers import PreTrainedModel, Trainer, logging from transformers.integrations import is_fairscale_available from transformers.models.fsmt.configuration_fsmt import FSMTConfig from transformers.optimization 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_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.trainer_pt_utils import get_tpu_sampler from transformers.training_args import ParallelMode from transformers.utils import is_torch_tpu_available if is_fairscale_available(): from fairscale.optim import OSS __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = { """linear""": get_linear_schedule_with_warmup, """cosine""": get_cosine_schedule_with_warmup, """cosine_w_restarts""": get_cosine_with_hard_restarts_schedule_with_warmup, """polynomial""": get_polynomial_decay_schedule_with_warmup, """constant""": get_constant_schedule, """constant_w_warmup""": get_constant_schedule_with_warmup, } class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" def __init__( self : Optional[int] ,_a : Optional[Any]=None ,_a : Dict=None ,*_a : int ,**_a : str ): '''simple docstring''' super().__init__(*_a ,**_a ) if config is None: assert isinstance(self.model ,_a ), ( "If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is" F""" {self.model.__class__}""" ) _a : List[Any] = self.model.config else: _a : Optional[int] = config _a : List[str] = data_args _a : List[Any] = self.config.tgt_vocab_size if isinstance(self.config ,_a ) else self.config.vocab_size if self.args.label_smoothing != 0 or (self.data_args is not None and self.data_args.ignore_pad_token_for_loss): assert self.config.pad_token_id is not None, ( "Make sure that `config.pad_token_id` is correcly defined when ignoring `pad_token` for loss" " calculation or doing label smoothing." ) if self.config.pad_token_id is None and self.config.eos_token_id is not None: logger.warning( F"""The `config.pad_token_id` is `None`. Using `config.eos_token_id` = {self.config.eos_token_id} for""" ' padding..' ) if self.args.label_smoothing == 0: _a : List[str] = torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id ) else: # dynamically import label_smoothed_nll_loss from utils import label_smoothed_nll_loss _a : Tuple = label_smoothed_nll_loss def __lowercase ( self : List[str] ,_a : int ): '''simple docstring''' if self.optimizer is None: _a : Union[str, Any] = ['bias', 'LayerNorm.weight'] _a : Tuple = [ { 'params': [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay )], 'weight_decay': self.args.weight_decay, }, { 'params': [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay )], 'weight_decay': 0.0, }, ] _a : Optional[int] = Adafactor if self.args.adafactor else AdamW if self.args.adafactor: _a : Any = Adafactor _a : Dict = {'scale_parameter': False, 'relative_step': False} else: _a : Union[str, Any] = AdamW _a : str = { 'betas': (self.args.adam_betaa, self.args.adam_betaa), 'eps': self.args.adam_epsilon, } _a : Union[str, Any] = self.args.learning_rate if self.sharded_ddp: _a : str = OSS( params=_a ,optim=_a ,**_a ,) else: _a : Tuple = optimizer_cls(_a ,**_a ) if self.lr_scheduler is None: _a : List[Any] = self._get_lr_scheduler(_a ) else: # ignoring --lr_scheduler logger.warning('scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored.' ) def __lowercase ( self : List[Any] ,_a : List[Any] ): '''simple docstring''' _a : str = arg_to_scheduler[self.args.lr_scheduler] if self.args.lr_scheduler == "constant": _a : int = schedule_func(self.optimizer ) elif self.args.lr_scheduler == "constant_w_warmup": _a : List[str] = schedule_func(self.optimizer ,num_warmup_steps=self.args.warmup_steps ) else: _a : Optional[int] = schedule_func( self.optimizer ,num_warmup_steps=self.args.warmup_steps ,num_training_steps=_a ) return scheduler def __lowercase ( self : Tuple ): '''simple docstring''' if isinstance(self.train_dataset ,torch.utils.data.IterableDataset ): return None elif is_torch_tpu_available(): return get_tpu_sampler(self.train_dataset ) else: if self.args.sortish_sampler: self.train_dataset.make_sortish_sampler( self.args.per_device_train_batch_size ,distributed=(self.args.parallel_mode == ParallelMode.DISTRIBUTED) ,) return ( RandomSampler(self.train_dataset ) if self.args.local_rank == -1 else DistributedSampler(self.train_dataset ) ) def __lowercase ( self : Dict ,_a : Dict ,_a : Any ,_a : Dict ): '''simple docstring''' if self.args.label_smoothing == 0: if self.data_args is not None and self.data_args.ignore_pad_token_for_loss: # force training to ignore pad token _a : List[Any] = model(**_a ,use_cache=_a )[0] _a : Union[str, Any] = self.loss_fn(logits.view(-1 ,logits.shape[-1] ) ,labels.view(-1 ) ) else: # compute usual loss via models _a, _a : Union[str, Any] = model(**_a ,labels=_a ,use_cache=_a )[:2] else: # compute label smoothed loss _a : List[Any] = model(**_a ,use_cache=_a )[0] _a : Any = torch.nn.functional.log_softmax(_a ,dim=-1 ) _a, _a : List[str] = self.loss_fn(_a ,_a ,self.args.label_smoothing ,ignore_index=self.config.pad_token_id ) return loss, logits def __lowercase ( self : Optional[int] ,_a : Union[str, Any] ,_a : List[Any] ): '''simple docstring''' _a : Optional[int] = inputs.pop('labels' ) _a, _a : int = self._compute_loss(_a ,_a ,_a ) return loss def __lowercase ( self : Optional[Any] ,_a : nn.Module ,_a : Dict[str, Union[torch.Tensor, Any]] ,_a : bool ,_a : Optional[List[str]] = None ,): '''simple docstring''' _a : int = self._prepare_inputs(_a ) _a : Any = { 'max_length': self.data_args.val_max_target_length if self.data_args is not None else self.config.max_length, 'num_beams': self.data_args.eval_beams if self.data_args is not None else self.config.num_beams, } if self.args.predict_with_generate and not self.args.prediction_loss_only: _a : int = self.model.generate( inputs['input_ids'] ,attention_mask=inputs['attention_mask'] ,**_a ,) # in case the batch is shorter than max length, the output should be padded if generated_tokens.shape[-1] < gen_kwargs["max_length"]: _a : int = self._pad_tensors_to_max_len(_a ,gen_kwargs['max_length'] ) _a : Union[str, Any] = inputs.pop('labels' ) with torch.no_grad(): # compute loss on predict data _a, _a : Optional[int] = self._compute_loss(_a ,_a ,_a ) _a : Optional[Any] = loss.mean().detach() if self.args.prediction_loss_only: return (loss, None, None) _a : Optional[Any] = generated_tokens if self.args.predict_with_generate else logits if labels.shape[-1] < gen_kwargs["max_length"]: _a : Dict = self._pad_tensors_to_max_len(_a ,gen_kwargs['max_length'] ) return (loss, logits, labels) def __lowercase ( self : str ,_a : Tuple ,_a : Tuple ): '''simple docstring''' _a : List[Any] = self.config.pad_token_id if self.config.pad_token_id is not None else self.config.eos_token_id if pad_token_id is None: raise ValueError( 'Make sure that either `config.pad_token_id` or `config.eos_token_id` is defined if tensor has to be' F""" padded to `max_length`={max_length}""" ) _a : int = pad_token_id * torch.ones( (tensor.shape[0], max_length) ,dtype=tensor.dtype ,device=tensor.device ) _a : Union[str, Any] = tensor return padded_tensor
271
1
'''simple docstring''' from __future__ import annotations import math def UpperCAmelCase_ (__a : int ): """simple docstring""" if num <= 0: _a : Tuple = f"""{num}: Invalid input, please enter a positive integer.""" raise ValueError(__a ) _a : str = [True] * (num + 1) _a : Tuple = [] _a : Optional[int] = 2 _a : Dict = int(math.sqrt(__a ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(__a ) # Set multiples of start be False for i in range(start * start , num + 1 , __a ): if sieve[i] is True: _a : Optional[int] = False start += 1 for j in range(end + 1 , num + 1 ): if sieve[j] is True: prime.append(__a ) return prime if __name__ == "__main__": print(prime_sieve(int(input("""Enter a positive integer: """).strip())))
271
'''simple docstring''' import gzip import hashlib import json import multiprocessing import os import re import shutil import time from pathlib import Path import numpy as np from arguments import PreprocessingArguments from datasets import load_dataset from minhash_deduplication import deduplicate_dataset from transformers import AutoTokenizer, HfArgumentParser __lowerCAmelCase = re.compile(r"""\s+""") def UpperCAmelCase_ (__a : Any ): """simple docstring""" return {"hash": hashlib.mda(re.sub(__a , '' , example['content'] ).encode('utf-8' ) ).hexdigest()} def UpperCAmelCase_ (__a : str ): """simple docstring""" _a : List[str] = [len(__a ) for line in example['content'].splitlines()] return {"line_mean": np.mean(__a ), "line_max": max(__a )} def UpperCAmelCase_ (__a : str ): """simple docstring""" _a : Union[str, Any] = np.mean([c.isalnum() for c in example['content']] ) return {"alpha_frac": alpha_frac} def UpperCAmelCase_ (__a : Optional[int] , __a : Any ): """simple docstring""" if example["hash"] in uniques: uniques.remove(example['hash'] ) return True else: return False def UpperCAmelCase_ (__a : int , __a : Union[str, Any]=5 ): """simple docstring""" _a : Optional[int] = ['auto-generated', 'autogenerated', 'automatically generated'] _a : List[str] = example['content'].splitlines() for _, line in zip(range(__a ) , __a ): for keyword in keywords: if keyword in line.lower(): return {"autogenerated": True} else: return {"autogenerated": False} def UpperCAmelCase_ (__a : List[str] , __a : Dict=5 , __a : Tuple=0.05 ): """simple docstring""" _a : Optional[int] = ['unit tests', 'test file', 'configuration file'] _a : int = example['content'].splitlines() _a : int = 0 _a : Dict = 0 # first test for _, line in zip(range(__a ) , __a ): for keyword in keywords: if keyword in line.lower(): return {"config_or_test": True} # second test _a : int = example['content'].count('\n' ) _a : int = int(coeff * nlines ) for line in lines: count_config += line.lower().count('config' ) count_test += line.lower().count('test' ) if count_config > threshold or count_test > threshold: return {"config_or_test": True} return {"config_or_test": False} def UpperCAmelCase_ (__a : Optional[int] ): """simple docstring""" _a : List[str] = ['def ', 'class ', 'for ', 'while '] _a : str = example['content'].splitlines() for line in lines: for keyword in keywords: if keyword in line.lower(): return {"has_no_keywords": False} return {"has_no_keywords": True} def UpperCAmelCase_ (__a : int , __a : Any=4 ): """simple docstring""" _a : List[str] = example['content'].splitlines() _a : Dict = 0 for line in lines: counter += line.lower().count('=' ) if counter > minimum: return {"has_few_assignments": False} return {"has_few_assignments": True} def UpperCAmelCase_ (__a : str ): """simple docstring""" _a : Optional[Any] = tokenizer(example['content'] , truncation=__a )['input_ids'] _a : Optional[int] = len(example['content'] ) / len(__a ) return {"ratio": ratio} def UpperCAmelCase_ (__a : str ): """simple docstring""" _a : Dict = {} results.update(get_hash(__a ) ) results.update(line_stats(__a ) ) results.update(alpha_stats(__a ) ) results.update(char_token_ratio(__a ) ) results.update(is_autogenerated(__a ) ) results.update(is_config_or_test(__a ) ) results.update(has_no_keywords(__a ) ) results.update(has_few_assignments(__a ) ) return results def UpperCAmelCase_ (__a : Any , __a : Any , __a : str ): """simple docstring""" if not check_uniques(__a , __a ): return False elif example["autogenerated"]: return False elif example["line_max"] > args.line_max: return False elif example["line_mean"] > args.line_mean: return False elif example["alpha_frac"] < args.alpha_frac: return False elif example["ratio"] < args.min_token_ratio: return False elif example["config_or_test"] and np.random.rand() <= args.filter_proba: return False elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba: return False elif example["has_few_assignments"]: return False else: return True def UpperCAmelCase_ (__a : Union[str, Any] ): """simple docstring""" with open(__a , 'rb' ) as f_in: with gzip.open(str(__a ) + '.gz' , 'wb' , compresslevel=6 ) as f_out: shutil.copyfileobj(__a , __a ) os.unlink(__a ) # Settings __lowerCAmelCase = HfArgumentParser(PreprocessingArguments) __lowerCAmelCase = parser.parse_args() if args.num_workers is None: __lowerCAmelCase = multiprocessing.cpu_count() __lowerCAmelCase = AutoTokenizer.from_pretrained(args.tokenizer_dir) # Load dataset __lowerCAmelCase = time.time() __lowerCAmelCase = load_dataset(args.dataset_name, split="""train""") print(f'''Time to load dataset: {time.time()-t_start:.2f}''') # Run preprocessing __lowerCAmelCase = time.time() __lowerCAmelCase = ds.map(preprocess, num_proc=args.num_workers) print(f'''Time to preprocess dataset: {time.time()-t_start:.2f}''') # Deduplicate hashes __lowerCAmelCase = set(ds.unique("""hash""")) __lowerCAmelCase = len(uniques) / len(ds) print(f'''Fraction of duplicates: {1-frac:.2%}''') # Deduplicate data and apply heuristics __lowerCAmelCase = time.time() __lowerCAmelCase = ds.filter(filter, fn_kwargs={"""uniques""": uniques, """args""": args}) print(f'''Time to filter dataset: {time.time()-t_start:.2f}''') print(f'''Size of filtered dataset: {len(ds_filter)}''') # Deduplicate with minhash and jaccard similarity if args.near_deduplication: __lowerCAmelCase = time.time() __lowerCAmelCase , __lowerCAmelCase = deduplicate_dataset(ds_filter, args.jaccard_threshold) print(f'''Time to deduplicate dataset: {time.time()-t_start:.2f}''') print(f'''Size of deduplicate dataset: {len(ds_filter)}''') # Save data in batches of samples_per_file __lowerCAmelCase = Path(args.output_dir) output_dir.mkdir(exist_ok=True) # save duplicate_clusters in the output_dir as artifacts # not sure it is the right place the save it if args.near_deduplication: with open(output_dir / """duplicate_clusters.json""", """w""") as f: json.dump(duplicate_clusters, f) __lowerCAmelCase = output_dir / """data""" data_dir.mkdir(exist_ok=True) __lowerCAmelCase = time.time() for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)): __lowerCAmelCase = str(data_dir / f'''file-{file_number+1:012}.json''') __lowerCAmelCase = min(len(ds_filter), index + args.samples_per_file) ds_filter.select(list(range(index, end_index))).to_json(file_path) compress_file(file_path) print(f'''Time to save dataset: {time.time()-t_start:.2f}''')
271
1
'''simple docstring''' __lowerCAmelCase = """0.18.2""" from .configuration_utils import ConfigMixin from .utils import ( OptionalDependencyNotAvailable, is_flax_available, is_inflect_available, is_invisible_watermark_available, is_k_diffusion_available, is_k_diffusion_version, is_librosa_available, is_note_seq_available, is_onnx_available, is_scipy_available, is_torch_available, is_torchsde_available, is_transformers_available, is_transformers_version, is_unidecode_available, logging, ) try: if not is_onnx_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_onnx_objects import * # noqa F403 else: from .pipelines import OnnxRuntimeModel try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_pt_objects import * # noqa F403 else: from .models import ( AutoencoderKL, ControlNetModel, ModelMixin, PriorTransformer, TaFilmDecoder, TransformeraDModel, UNetaDModel, UNetaDConditionModel, UNetaDModel, UNetaDConditionModel, VQModel, ) from .optimization import ( get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, get_scheduler, ) from .pipelines import ( AudioPipelineOutput, ConsistencyModelPipeline, DanceDiffusionPipeline, DDIMPipeline, DDPMPipeline, DiffusionPipeline, DiTPipeline, ImagePipelineOutput, KarrasVePipeline, LDMPipeline, LDMSuperResolutionPipeline, PNDMPipeline, RePaintPipeline, ScoreSdeVePipeline, ) from .schedulers import ( CMStochasticIterativeScheduler, DDIMInverseScheduler, DDIMParallelScheduler, DDIMScheduler, DDPMParallelScheduler, DDPMScheduler, DEISMultistepScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, HeunDiscreteScheduler, IPNDMScheduler, KarrasVeScheduler, KDPMaAncestralDiscreteScheduler, KDPMaDiscreteScheduler, PNDMScheduler, RePaintScheduler, SchedulerMixin, ScoreSdeVeScheduler, UnCLIPScheduler, UniPCMultistepScheduler, VQDiffusionScheduler, ) from .training_utils import EMAModel try: if not (is_torch_available() and is_scipy_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_scipy_objects import * # noqa F403 else: from .schedulers import LMSDiscreteScheduler try: if not (is_torch_available() and is_torchsde_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_torchsde_objects import * # noqa F403 else: from .schedulers import DPMSolverSDEScheduler try: if not (is_torch_available() and is_transformers_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipelines import ( AltDiffusionImgaImgPipeline, AltDiffusionPipeline, AudioLDMPipeline, CycleDiffusionPipeline, IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ImageTextPipelineOutput, KandinskyImgaImgPipeline, KandinskyInpaintPipeline, KandinskyPipeline, KandinskyPriorPipeline, KandinskyVaaControlnetImgaImgPipeline, KandinskyVaaControlnetPipeline, KandinskyVaaImgaImgPipeline, KandinskyVaaInpaintPipeline, KandinskyVaaPipeline, KandinskyVaaPriorEmbaEmbPipeline, KandinskyVaaPriorPipeline, LDMTextToImagePipeline, PaintByExamplePipeline, SemanticStableDiffusionPipeline, ShapEImgaImgPipeline, ShapEPipeline, StableDiffusionAttendAndExcitePipeline, StableDiffusionControlNetImgaImgPipeline, StableDiffusionControlNetInpaintPipeline, StableDiffusionControlNetPipeline, StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionImageVariationPipeline, StableDiffusionImgaImgPipeline, StableDiffusionInpaintPipeline, StableDiffusionInpaintPipelineLegacy, StableDiffusionInstructPixaPixPipeline, StableDiffusionLatentUpscalePipeline, StableDiffusionLDMaDPipeline, StableDiffusionModelEditingPipeline, StableDiffusionPanoramaPipeline, StableDiffusionParadigmsPipeline, StableDiffusionPipeline, StableDiffusionPipelineSafe, StableDiffusionPixaPixZeroPipeline, StableDiffusionSAGPipeline, StableDiffusionUpscalePipeline, StableUnCLIPImgaImgPipeline, StableUnCLIPPipeline, TextToVideoSDPipeline, TextToVideoZeroPipeline, UnCLIPImageVariationPipeline, UnCLIPPipeline, UniDiffuserModel, UniDiffuserPipeline, UniDiffuserTextDecoder, VersatileDiffusionDualGuidedPipeline, VersatileDiffusionImageVariationPipeline, VersatileDiffusionPipeline, VersatileDiffusionTextToImagePipeline, VideoToVideoSDPipeline, VQDiffusionPipeline, ) try: if not (is_torch_available() and is_transformers_available() and is_invisible_watermark_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_invisible_watermark_objects import * # noqa F403 else: from .pipelines import StableDiffusionXLImgaImgPipeline, StableDiffusionXLPipeline try: if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipelines import StableDiffusionKDiffusionPipeline try: if not (is_torch_available() and is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_onnx_objects import * # noqa F403 else: from .pipelines import ( OnnxStableDiffusionImgaImgPipeline, OnnxStableDiffusionInpaintPipeline, OnnxStableDiffusionInpaintPipelineLegacy, OnnxStableDiffusionPipeline, OnnxStableDiffusionUpscalePipeline, StableDiffusionOnnxPipeline, ) try: if not (is_torch_available() and is_librosa_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_librosa_objects import * # noqa F403 else: from .pipelines import AudioDiffusionPipeline, Mel try: if not (is_transformers_available() and is_torch_available() and is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403 else: from .pipelines import SpectrogramDiffusionPipeline try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_flax_objects import * # noqa F403 else: from .models.controlnet_flax import FlaxControlNetModel from .models.modeling_flax_utils import FlaxModelMixin from .models.unet_ad_condition_flax import FlaxUNetaDConditionModel from .models.vae_flax import FlaxAutoencoderKL from .pipelines import FlaxDiffusionPipeline from .schedulers import ( FlaxDDIMScheduler, FlaxDDPMScheduler, FlaxDPMSolverMultistepScheduler, FlaxKarrasVeScheduler, FlaxLMSDiscreteScheduler, FlaxPNDMScheduler, FlaxSchedulerMixin, FlaxScoreSdeVeScheduler, ) try: if not (is_flax_available() and is_transformers_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_flax_and_transformers_objects import * # noqa F403 else: from .pipelines import ( FlaxStableDiffusionControlNetPipeline, FlaxStableDiffusionImgaImgPipeline, FlaxStableDiffusionInpaintPipeline, FlaxStableDiffusionPipeline, ) try: if not (is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_note_seq_objects import * # noqa F403 else: from .pipelines import MidiProcessor
271
'''simple docstring''' import argparse from typing import List import evaluate import numpy as np import torch from datasets import DatasetDict, load_dataset # New Code # # We'll be using StratifiedKFold for this example from sklearn.model_selection import StratifiedKFold from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to perform Cross Validation, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## __lowerCAmelCase = 1_6 __lowerCAmelCase = 3_2 def UpperCAmelCase_ (__a : Accelerator , __a : DatasetDict , __a : List[int] , __a : List[int] , __a : int = 1_6 ): """simple docstring""" _a : Union[str, Any] = AutoTokenizer.from_pretrained('bert-base-cased' ) _a : str = DatasetDict( { 'train': dataset['train'].select(__a ), 'validation': dataset['train'].select(__a ), 'test': dataset['validation'], } ) def tokenize_function(__a : List[Any] ): # max_length=None => use the model max length (it's actually the default) _a : Optional[int] = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=__a , max_length=__a ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): _a : List[str] = datasets.map( __a , batched=__a , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _a : List[Any] = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(__a : int ): # On TPU it's best to pad everything to the same length or training will be very slow. _a : Dict = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _a : Tuple = 1_6 elif accelerator.mixed_precision != "no": _a : List[Any] = 8 else: _a : List[Any] = None return tokenizer.pad( __a , padding='longest' , max_length=__a , pad_to_multiple_of=__a , return_tensors='pt' , ) # Instantiate dataloaders. _a : Any = DataLoader( tokenized_datasets['train'] , shuffle=__a , collate_fn=__a , batch_size=__a ) _a : Optional[int] = DataLoader( tokenized_datasets['validation'] , shuffle=__a , collate_fn=__a , batch_size=__a ) _a : Optional[Any] = DataLoader( tokenized_datasets['test'] , shuffle=__a , collate_fn=__a , batch_size=__a ) return train_dataloader, eval_dataloader, test_dataloader def UpperCAmelCase_ (__a : Any , __a : Union[str, Any] ): """simple docstring""" _a : Dict = [] # Download the dataset _a : Tuple = load_dataset('glue' , 'mrpc' ) # Create our splits _a : Union[str, Any] = StratifiedKFold(n_splits=int(args.num_folds ) ) # Initialize accelerator _a : Any = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _a : Optional[Any] = config['lr'] _a : Optional[int] = int(config['num_epochs'] ) _a : Dict = int(config['seed'] ) _a : Dict = int(config['batch_size'] ) _a : Optional[int] = evaluate.load('glue' , 'mrpc' ) # If the batch size is too big we use gradient accumulation _a : List[Any] = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: _a : Any = batch_size // MAX_GPU_BATCH_SIZE _a : List[str] = MAX_GPU_BATCH_SIZE set_seed(__a ) # New Code # # Create our folds: _a : int = kfold.split(np.zeros(datasets['train'].num_rows ) , datasets['train']['label'] ) _a : Any = [] # Iterate over them for i, (train_idxs, valid_idxs) in enumerate(__a ): _a, _a, _a : Optional[Any] = get_fold_dataloaders( __a , __a , __a , __a , ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _a : Dict = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=__a ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _a : List[Any] = model.to(accelerator.device ) # Instantiate optimizer _a : List[str] = AdamW(params=model.parameters() , lr=__a ) # Instantiate scheduler _a : List[Any] = get_linear_schedule_with_warmup( optimizer=__a , num_warmup_steps=1_0_0 , num_training_steps=(len(__a ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _a, _a, _a, _a, _a : Union[str, Any] = accelerator.prepare( __a , __a , __a , __a , __a ) # Now we train the model for epoch in range(__a ): model.train() for step, batch in enumerate(__a ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _a : Dict = model(**__a ) _a : int = outputs.loss _a : Any = loss / gradient_accumulation_steps accelerator.backward(__a ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__a ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _a : Union[str, Any] = model(**__a ) _a : Tuple = outputs.logits.argmax(dim=-1 ) _a, _a : Any = accelerator.gather_for_metrics((predictions, batch['labels']) ) metric.add_batch( predictions=__a , references=__a , ) _a : List[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" , __a ) # New Code # # We also run predictions on the test set at the very end _a : Any = [] for step, batch in enumerate(__a ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _a : Tuple = model(**__a ) _a : Dict = outputs.logits _a, _a : Optional[int] = accelerator.gather_for_metrics((predictions, batch['labels']) ) fold_predictions.append(predictions.cpu() ) if i == 0: # We need all of the test predictions test_references.append(references.cpu() ) # Use accelerator.print to print only on the main process. test_predictions.append(torch.cat(__a , dim=0 ) ) # We now need to release all our memory and get rid of the current model, optimizer, etc accelerator.free_memory() # New Code # # Finally we check the accuracy of our folded results: _a : Dict = torch.cat(__a , dim=0 ) _a : Any = torch.stack(__a , dim=0 ).sum(dim=0 ).div(int(args.num_folds ) ).argmax(dim=-1 ) _a : str = metric.compute(predictions=__a , references=__a ) accelerator.print('Average test metrics from all folds:' , __a ) def UpperCAmelCase_ (): """simple docstring""" _a : Any = argparse.ArgumentParser(description='Simple example of training script.' ) parser.add_argument( '--mixed_precision' , type=__a , default=__a , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.' ) # New Code # parser.add_argument('--num_folds' , type=__a , default=3 , help='The number of splits to perform across the dataset' ) _a : Any = parser.parse_args() _a : int = {'lr': 2e-5, 'num_epochs': 3, 'seed': 4_2, 'batch_size': 1_6} training_function(__a , __a ) if __name__ == "__main__": main()
271
1
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = """▁""" __lowerCAmelCase = {"""vocab_file""": """sentencepiece.bpe.model"""} __lowerCAmelCase = { """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""" ), } } __lowerCAmelCase = { """facebook/mbart-large-en-ro""": 1_0_2_4, """facebook/mbart-large-cc25""": 1_0_2_4, } # fmt: off __lowerCAmelCase = ["""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 UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : List[Any] = VOCAB_FILES_NAMES __UpperCAmelCase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Tuple = ['''input_ids''', '''attention_mask'''] __UpperCAmelCase : List[int] = [] __UpperCAmelCase : List[int] = [] def __init__( self : Any ,_a : Dict ,_a : Tuple="<s>" ,_a : Optional[Any]="</s>" ,_a : Optional[int]="</s>" ,_a : Optional[Any]="<s>" ,_a : Dict="<unk>" ,_a : List[str]="<pad>" ,_a : Optional[Any]="<mask>" ,_a : str=None ,_a : Union[str, Any]=None ,_a : Optional[int]=None ,_a : Optional[Dict[str, Any]] = None ,_a : List[str]=None ,**_a : Any ,): '''simple docstring''' _a : Dict = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else mask_token _a : List[str] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_a ,eos_token=_a ,unk_token=_a ,sep_token=_a ,cls_token=_a ,pad_token=_a ,mask_token=_a ,tokenizer_file=_a ,src_lang=_a ,tgt_lang=_a ,additional_special_tokens=_a ,sp_model_kwargs=self.sp_model_kwargs ,**_a ,) _a : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_a ) ) _a : str = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token _a : Dict = {'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab _a : Optional[int] = 1 _a : List[Any] = len(self.sp_model ) _a : List[str] = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(_a ) } _a : Optional[int] = {v: k for k, v in self.lang_code_to_id.items()} _a : List[str] = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) _a : int = {v: k for k, v in self.fairseq_tokens_to_ids.items()} _a : List[Any] = list(self.lang_code_to_id.keys() ) if additional_special_tokens is not None: # Only add those special tokens if they are not already there. self._additional_special_tokens.extend( [t for t in additional_special_tokens if t not in self._additional_special_tokens] ) _a : List[Any] = src_lang if src_lang is not None else 'en_XX' _a : Optional[int] = self.lang_code_to_id[self._src_lang] _a : Dict = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self : int ): '''simple docstring''' _a : int = self.__dict__.copy() _a : Tuple = None _a : List[str] = self.sp_model.serialized_model_proto() return state def __setstate__( self : int ,_a : List[str] ): '''simple docstring''' _a : int = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs' ): _a : Dict = {} _a : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) @property def __lowercase ( self : List[Any] ): '''simple docstring''' return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def __lowercase ( self : int ): '''simple docstring''' return self._src_lang @src_lang.setter def __lowercase ( self : List[str] ,_a : str ): '''simple docstring''' _a : List[str] = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __lowercase ( self : Optional[Any] ,_a : List[int] ,_a : Optional[List[int]] = None ,_a : bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a ,token_ids_a=_a ,already_has_special_tokens=_a ) _a : str = [1] * len(self.prefix_tokens ) _a : Dict = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(_a )) + suffix_ones return prefix_ones + ([0] * len(_a )) + ([0] * len(_a )) + suffix_ones def __lowercase ( self : Optional[int] ,_a : List[int] ,_a : Optional[List[int]] = None ): '''simple docstring''' 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 __lowercase ( self : List[Any] ,_a : List[int] ,_a : Optional[List[int]] = None ): '''simple docstring''' _a : Optional[int] = [self.sep_token_id] _a : str = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __lowercase ( self : Union[str, Any] ,_a : Union[str, Any] ,_a : str ,_a : Optional[str] ,_a : Optional[str] ,**_a : Any ): '''simple docstring''' if src_lang is None or tgt_lang is None: raise ValueError('Translation requires a `src_lang` and a `tgt_lang` for this model' ) _a : Dict = src_lang _a : str = self(_a ,add_special_tokens=_a ,return_tensors=_a ,**_a ) _a : int = self.convert_tokens_to_ids(_a ) _a : Any = tgt_lang_id return inputs def __lowercase ( self : Dict ): '''simple docstring''' _a : Any = {self.convert_ids_to_tokens(_a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __lowercase ( self : Any ,_a : str ): '''simple docstring''' return self.sp_model.encode(_a ,out_type=_a ) def __lowercase ( self : Tuple ,_a : Dict ): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] _a : str = self.sp_model.PieceToId(_a ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def __lowercase ( self : int ,_a : int ): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def __lowercase ( self : Optional[int] ,_a : str ): '''simple docstring''' _a : str = ''.join(_a ).replace(_a ,' ' ).strip() return out_string def __lowercase ( self : Union[str, Any] ,_a : str ,_a : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(_a ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _a : str = os.path.join( _a ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,_a ) elif not os.path.isfile(self.vocab_file ): with open(_a ,'wb' ) as fi: _a : Optional[int] = self.sp_model.serialized_model_proto() fi.write(_a ) return (out_vocab_file,) def __lowercase ( self : Union[str, Any] ,_a : List[str] ,_a : str = "en_XX" ,_a : Optional[List[str]] = None ,_a : str = "ro_RO" ,**_a : List[str] ,): '''simple docstring''' _a : Any = src_lang _a : int = tgt_lang return super().prepare_seqaseq_batch(_a ,_a ,**_a ) def __lowercase ( self : int ): '''simple docstring''' return self.set_src_lang_special_tokens(self.src_lang ) def __lowercase ( self : List[Any] ): '''simple docstring''' return self.set_tgt_lang_special_tokens(self.tgt_lang ) def __lowercase ( self : int ,_a : Optional[int] ): '''simple docstring''' _a : Any = self.lang_code_to_id[src_lang] _a : List[Any] = [] _a : Any = [self.eos_token_id, self.cur_lang_code] def __lowercase ( self : List[str] ,_a : str ): '''simple docstring''' _a : Any = self.lang_code_to_id[lang] _a : Dict = [] _a : Optional[int] = [self.eos_token_id, self.cur_lang_code]
271
'''simple docstring''' from __future__ import annotations __lowerCAmelCase = [-1_0, -5, 0, 5, 5.1, 1_1, 1_3, 2_1, 3, 4, -2_1, -1_0, -5, -1, 0] __lowerCAmelCase = [-5, 0, 5, 5.1, 1_1, 1_3, 2_1, -1, 4, -1, -1_0, -5, -1, 0, -1] def UpperCAmelCase_ (__a : list[float] ): """simple docstring""" _a : Optional[int] = [] _a : int = len(__a ) for i in range(__a ): _a : float = -1 for j in range(i + 1 , __a ): if arr[i] < arr[j]: _a : Any = arr[j] break result.append(__a ) return result def UpperCAmelCase_ (__a : list[float] ): """simple docstring""" _a : Tuple = [] for i, outer in enumerate(__a ): _a : float = -1 for inner in arr[i + 1 :]: if outer < inner: _a : Dict = inner break result.append(__a ) return result def UpperCAmelCase_ (__a : list[float] ): """simple docstring""" _a : int = len(__a ) _a : list[float] = [] _a : list[float] = [-1] * arr_size for index in reversed(range(__a ) ): if stack: while stack[-1] <= arr[index]: stack.pop() if not stack: break if stack: _a : Dict = stack[-1] stack.append(arr[index] ) return result if __name__ == "__main__": from doctest import testmod from timeit import timeit testmod() print(next_greatest_element_slow(arr)) print(next_greatest_element_fast(arr)) print(next_greatest_element(arr)) __lowerCAmelCase = ( """from __main__ import arr, next_greatest_element_slow, """ """next_greatest_element_fast, next_greatest_element""" ) print( """next_greatest_element_slow():""", timeit("""next_greatest_element_slow(arr)""", setup=setup), ) print( """next_greatest_element_fast():""", timeit("""next_greatest_element_fast(arr)""", setup=setup), ) print( """ next_greatest_element():""", timeit("""next_greatest_element(arr)""", setup=setup), )
271
1
'''simple docstring''' import inspect import logging import os import random import shutil import tempfile import unittest import pytest import torch from torch import nn from torch.utils.data import DataLoader, TensorDataset from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_cuda from accelerate.utils import ProjectConfiguration, set_seed __lowerCAmelCase = logging.getLogger(__name__) def UpperCAmelCase_ (__a : Optional[int]=2 , __a : Optional[int]=3 , __a : int=1_6 , __a : int = 1_0 , __a : int = 2 ): """simple docstring""" def get_dataset(__a : Any ): _a : Any = torch.randn(batch_size * n_batches , 1 ) return TensorDataset(__a , a * x + b + 0.1 * torch.randn(batch_size * n_batches , 1 ) ) _a : Dict = get_dataset(__a ) _a : Optional[Any] = get_dataset(__a ) _a : int = DataLoader(__a , shuffle=__a , batch_size=__a , num_workers=4 ) _a : List[str] = DataLoader(__a , shuffle=__a , batch_size=__a , num_workers=4 ) return (train_dataloader, valid_dataloader) def UpperCAmelCase_ (__a : List[str] , __a : int , __a : str , __a : Union[str, Any] , __a : Any , __a : Optional[Any]=None ): """simple docstring""" _a : Dict = [] for epoch in range(__a ): # Train quickly model.train() for batch in dataloader: _a, _a : int = batch _a : Any = model(__a ) _a : List[Any] = torch.nn.functional.mse_loss(__a , __a ) accelerator.backward(__a ) optimizer.step() optimizer.zero_grad() rands.append(random.random() ) # Introduce some randomness if scheduler is not None: scheduler.step() return rands class UpperCAmelCase__ ( nn.Module ): """simple docstring""" def __init__( self : List[Any] ): '''simple docstring''' super().__init__() _a : Union[str, Any] = nn.Parameter(torch.randn(1 ) ) _a : Optional[Any] = nn.Parameter(torch.randn(1 ) ) def __lowercase ( self : Optional[Any] ,_a : Tuple ): '''simple docstring''' return x * self.a + self.b class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self : Dict ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) _a : Optional[int] = DummyModel() _a : Tuple = torch.optim.Adam(params=model.parameters() ,lr=1E-3 ) _a, _a : List[Any] = dummy_dataloaders() _a : int = ProjectConfiguration(total_limit=1 ,project_dir=_a ,automatic_checkpoint_naming=_a ) # Train baseline _a : int = Accelerator(project_config=_a ) _a, _a, _a, _a : str = accelerator.prepare( _a ,_a ,_a ,_a ) # Save initial accelerator.save_state() # Save second state accelerator.save_state() self.assertEqual(len(os.listdir(accelerator.project_dir ) ) ,1 ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) _a : List[Any] = DummyModel() _a : Any = torch.optim.Adam(params=model.parameters() ,lr=1E-3 ) _a, _a : str = dummy_dataloaders() # Train baseline _a : Union[str, Any] = Accelerator() _a, _a, _a, _a : Union[str, Any] = accelerator.prepare( _a ,_a ,_a ,_a ) # Save initial _a : int = os.path.join(_a ,'initial' ) accelerator.save_state(_a ) ((_a), (_a)) : List[Any] = model.a.item(), model.b.item() _a : Optional[Any] = optimizer.state_dict() _a : List[Any] = train(3 ,_a ,_a ,_a ,_a ) ((_a), (_a)) : Any = model.a.item(), model.b.item() _a : Tuple = optimizer.state_dict() # Train partially set_seed(42 ) _a : Dict = DummyModel() _a : List[Any] = torch.optim.Adam(params=model.parameters() ,lr=1E-3 ) _a, _a : Tuple = dummy_dataloaders() _a : Tuple = Accelerator() _a, _a, _a, _a : Optional[int] = accelerator.prepare( _a ,_a ,_a ,_a ) accelerator.load_state(_a ) ((_a), (_a)) : Union[str, Any] = model.a.item(), model.b.item() _a : Any = optimizer.state_dict() self.assertEqual(_a ,_a ) self.assertEqual(_a ,_a ) self.assertEqual(_a ,_a ) _a : List[Any] = train(2 ,_a ,_a ,_a ,_a ) # Save everything _a : Tuple = os.path.join(_a ,'checkpoint' ) accelerator.save_state(_a ) # Load everything back in and make sure all states work accelerator.load_state(_a ) test_rands += train(1 ,_a ,_a ,_a ,_a ) ((_a), (_a)) : Dict = model.a.item(), model.b.item() _a : Union[str, Any] = optimizer.state_dict() self.assertEqual(_a ,_a ) self.assertEqual(_a ,_a ) self.assertEqual(_a ,_a ) self.assertEqual(_a ,_a ) def __lowercase ( self : Any ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) _a : Tuple = DummyModel() _a : List[Any] = torch.optim.Adam(params=model.parameters() ,lr=1E-3 ) _a, _a : Optional[Any] = dummy_dataloaders() _a : Optional[int] = ProjectConfiguration(automatic_checkpoint_naming=_a ) # Train baseline _a : List[Any] = Accelerator(project_dir=_a ,project_config=_a ) _a, _a, _a, _a : Optional[Any] = accelerator.prepare( _a ,_a ,_a ,_a ) # Save initial accelerator.save_state() ((_a), (_a)) : List[str] = model.a.item(), model.b.item() _a : Optional[int] = optimizer.state_dict() _a : Optional[Any] = train(3 ,_a ,_a ,_a ,_a ) ((_a), (_a)) : Optional[Any] = model.a.item(), model.b.item() _a : Dict = optimizer.state_dict() # Train partially set_seed(42 ) _a : Tuple = DummyModel() _a : Union[str, Any] = torch.optim.Adam(params=model.parameters() ,lr=1E-3 ) _a, _a : Union[str, Any] = dummy_dataloaders() _a : Optional[Any] = ProjectConfiguration(iteration=1 ,automatic_checkpoint_naming=_a ) _a : Any = Accelerator(project_dir=_a ,project_config=_a ) _a, _a, _a, _a : Optional[int] = accelerator.prepare( _a ,_a ,_a ,_a ) accelerator.load_state(os.path.join(_a ,'checkpoints' ,'checkpoint_0' ) ) ((_a), (_a)) : Optional[int] = model.a.item(), model.b.item() _a : Optional[int] = optimizer.state_dict() self.assertEqual(_a ,_a ) self.assertEqual(_a ,_a ) self.assertEqual(_a ,_a ) _a : List[str] = train(2 ,_a ,_a ,_a ,_a ) # Save everything accelerator.save_state() # Load everything back in and make sure all states work accelerator.load_state(os.path.join(_a ,'checkpoints' ,'checkpoint_1' ) ) test_rands += train(1 ,_a ,_a ,_a ,_a ) ((_a), (_a)) : int = model.a.item(), model.b.item() _a : int = optimizer.state_dict() self.assertEqual(_a ,_a ) self.assertEqual(_a ,_a ) self.assertEqual(_a ,_a ) self.assertEqual(_a ,_a ) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : Dict = torch.tensor([1, 2, 3] ) _a : Union[str, Any] = torch.tensor([2, 3, 4] ) _a : Optional[Any] = DummyModel() _a : int = torch.optim.Adam(net.parameters() ) _a : Dict = Accelerator() with self.assertRaises(_a ) as ve: accelerator.register_for_checkpointing(_a ,_a ,_a ,_a ) _a : str = str(ve.exception ) self.assertTrue('Item at index 0' in message ) self.assertTrue('Item at index 1' in message ) self.assertFalse('Item at index 2' in message ) self.assertFalse('Item at index 3' in message ) def __lowercase ( self : Dict ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) _a : int = DummyModel() _a : Optional[int] = torch.optim.Adam(params=model.parameters() ,lr=1E-3 ) _a : Any = torch.optim.lr_scheduler.StepLR(_a ,step_size=1 ,gamma=0.99 ) _a, _a : Dict = dummy_dataloaders() _a : int = ProjectConfiguration(automatic_checkpoint_naming=_a ) # Train baseline _a : Tuple = Accelerator(project_dir=_a ,project_config=_a ) _a, _a, _a, _a, _a : str = accelerator.prepare( _a ,_a ,_a ,_a ,_a ) # Save initial accelerator.save_state() _a : Optional[int] = scheduler.state_dict() train(3 ,_a ,_a ,_a ,_a ,_a ) self.assertNotEqual(_a ,scheduler.state_dict() ) # Load everything back in and make sure all states work accelerator.load_state(os.path.join(_a ,'checkpoints' ,'checkpoint_0' ) ) self.assertEqual(_a ,scheduler.state_dict() ) def __lowercase ( self : int ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) _a : Any = DummyModel() _a : List[Any] = ProjectConfiguration(automatic_checkpoint_naming=_a ,total_limit=2 ) # Train baseline _a : Dict = Accelerator(project_dir=_a ,project_config=_a ) _a : List[str] = accelerator.prepare(_a ) # Save 3 states: for _ in range(11 ): accelerator.save_state() self.assertTrue(not os.path.exists(os.path.join(_a ,'checkpoints' ,'checkpoint_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(_a ,'checkpoints' ,'checkpoint_9' ) ) ) self.assertTrue(os.path.exists(os.path.join(_a ,'checkpoints' ,'checkpoint_10' ) ) ) @require_cuda def __lowercase ( self : Dict ): '''simple docstring''' _a : Union[str, Any] = ['torchrun', F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__ )] execute_subprocess_async(_a ,env=os.environ.copy() ) if __name__ == "__main__": __lowerCAmelCase = """/tmp/accelerate/state_checkpointing""" __lowerCAmelCase = DummyModel() __lowerCAmelCase = torch.optim.Adam(params=model.parameters(), lr=1e-3) __lowerCAmelCase = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99) __lowerCAmelCase , __lowerCAmelCase = dummy_dataloaders() __lowerCAmelCase = ProjectConfiguration(automatic_checkpoint_naming=True) # Train baseline __lowerCAmelCase = Accelerator(project_dir=savedir, project_config=project_config, mixed_precision="""no""") if accelerator.process_index == 0: if os.path.exists(savedir): shutil.rmtree(savedir) os.makedirs(savedir) __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = accelerator.prepare( model, optimizer, train_dataloader, valid_dataloader, scheduler ) __lowerCAmelCase , __lowerCAmelCase = accelerator.prepare(model, optimizer) train(3, model, train_dataloader, optimizer, accelerator, scheduler) # Check that the intial optimizer is loaded on the GPU for group in optimizer.param_groups: __lowerCAmelCase = group["""params"""][0].device break assert param_device.type == accelerator.device.type __lowerCAmelCase = model.cpu() accelerator.wait_for_everyone() accelerator.save_state() accelerator.wait_for_everyone() # Check CPU state accelerator.load_state(os.path.join(savedir, """checkpoints""", """checkpoint_0"""), map_location="""cpu""") for group in optimizer.param_groups: __lowerCAmelCase = group["""params"""][0].device break assert ( param_device.type == torch.device("""cpu""").type ), f"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}" # Check device state model.to(accelerator.device) accelerator.load_state(os.path.join(savedir, """checkpoints""", """checkpoint_0"""), map_location="""on_device""") for group in optimizer.param_groups: __lowerCAmelCase = group["""params"""][0].device break assert ( param_device.type == accelerator.device.type ), f"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}" # Check error with pytest.raises(TypeError, match="""Unsupported optimizer map location passed"""): accelerator.load_state(os.path.join(savedir, """checkpoints""", """checkpoint_0"""), map_location="""invalid""") accelerator.wait_for_everyone() if accelerator.process_index == 0: shutil.rmtree(savedir) accelerator.wait_for_everyone()
271
'''simple docstring''' import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home __lowerCAmelCase = HUGGINGFACE_HUB_CACHE __lowerCAmelCase = """config.json""" __lowerCAmelCase = """diffusion_pytorch_model.bin""" __lowerCAmelCase = """diffusion_flax_model.msgpack""" __lowerCAmelCase = """model.onnx""" __lowerCAmelCase = """diffusion_pytorch_model.safetensors""" __lowerCAmelCase = """weights.pb""" __lowerCAmelCase = """https://huggingface.co""" __lowerCAmelCase = default_cache_path __lowerCAmelCase = """diffusers_modules""" __lowerCAmelCase = os.getenv("""HF_MODULES_CACHE""", os.path.join(hf_cache_home, """modules""")) __lowerCAmelCase = ["""fp16""", """non-ema"""] __lowerCAmelCase = """.self_attn"""
271
1
'''simple docstring''' import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow __lowerCAmelCase = logging.getLogger() @unittest.skip('''Temporarily disable the doc tests.''' ) @require_torch @require_tf @slow class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self : str ,_a : Path ,_a : Union[str, None] = None ,_a : Union[List[str], None] = None ,_a : Union[str, List[str], None] = None ,_a : bool = True ,): '''simple docstring''' _a : Optional[int] = [file for file in os.listdir(_a ) if os.path.isfile(os.path.join(_a ,_a ) )] if identifier is not None: _a : List[str] = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(_a ,_a ): for n_ in n_identifier: _a : Tuple = [file for file in files if n_ not in file] else: _a : Optional[Any] = [file for file in files if n_identifier not in file] _a : List[str] = ignore_files or [] ignore_files.append('__init__.py' ) _a : Tuple = [file for file in files if file not in ignore_files] for file in files: # Open all files print('Testing' ,_a ) if only_modules: _a : Any = file.split('.' )[0] try: _a : List[str] = getattr(_a ,_a ) _a : int = doctest.DocTestSuite(_a ) _a : Any = unittest.TextTestRunner().run(_a ) self.assertIs(len(result.failures ) ,0 ) except AttributeError: logger.info(F"""{module_identifier} is not a module.""" ) else: _a : Union[str, Any] = doctest.testfile(str('..' / directory / file ) ,optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed ,0 ) def __lowercase ( self : Any ): '''simple docstring''' _a : int = Path('src/transformers' ) _a : List[Any] = 'modeling' _a : Optional[Any] = [ 'modeling_ctrl.py', 'modeling_tf_ctrl.py', ] self.analyze_directory(_a ,identifier=_a ,ignore_files=_a ) def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : Optional[Any] = Path('src/transformers' ) _a : Optional[Any] = 'tokenization' self.analyze_directory(_a ,identifier=_a ) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Dict = Path('src/transformers' ) _a : str = 'configuration' self.analyze_directory(_a ,identifier=_a ) def __lowercase ( self : Any ): '''simple docstring''' _a : Tuple = Path('src/transformers' ) _a : List[Any] = ['configuration', 'modeling', 'tokenization'] self.analyze_directory(_a ,n_identifier=_a ) def __lowercase ( self : Tuple ): '''simple docstring''' _a : List[Any] = Path('docs/source' ) _a : List[str] = ['favicon.ico'] self.analyze_directory(_a ,ignore_files=_a ,only_modules=_a )
271
'''simple docstring''' import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class UpperCAmelCase__ : """simple docstring""" def __init__( self : int ,_a : Any ,_a : Optional[int]=2 ,_a : Optional[Any]=True ,_a : Dict=False ,_a : Dict=10 ,_a : Any=3 ,_a : str=32 * 8 ,_a : Optional[int]=32 * 8 ,_a : int=4 ,_a : str=64 ,): '''simple docstring''' _a : Dict = parent _a : Union[str, Any] = batch_size _a : Tuple = is_training _a : List[str] = use_auxiliary_loss _a : Optional[Any] = num_queries _a : str = num_channels _a : List[str] = min_size _a : int = max_size _a : Optional[int] = num_labels _a : List[str] = hidden_dim _a : int = hidden_dim def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : Tuple = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( _a ) _a : Optional[Any] = torch.ones([self.batch_size, self.min_size, self.max_size] ,device=_a ) _a : Union[str, Any] = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] ,device=_a ) > 0.5 ).float() _a : Tuple = (torch.rand((self.batch_size, self.num_labels) ,device=_a ) > 0.5).long() _a : Dict = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : int = MaskaFormerConfig( hidden_size=self.hidden_dim ,) _a : str = self.num_queries _a : Union[str, Any] = self.num_labels _a : Tuple = [1, 1, 1, 1] _a : Dict = self.num_channels _a : str = 64 _a : Tuple = 128 _a : Optional[Any] = self.hidden_dim _a : Union[str, Any] = self.hidden_dim _a : List[Any] = self.hidden_dim return config def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a, _a, _a, _a, _a : Optional[Any] = self.prepare_config_and_inputs() _a : str = {'pixel_values': pixel_values, 'pixel_mask': pixel_mask} return config, inputs_dict def __lowercase ( self : List[str] ,_a : Optional[Any] ,_a : str ): '''simple docstring''' _a : str = output.encoder_hidden_states _a : Any = output.pixel_decoder_hidden_states _a : Optional[Any] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(_a ) ,len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_a ) ,len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_a ) ,config.decoder_layers ) def __lowercase ( self : List[str] ,_a : str ,_a : List[Any] ,_a : Any ,_a : Union[str, Any]=False ): '''simple docstring''' with torch.no_grad(): _a : str = MaskaFormerModel(config=_a ) model.to(_a ) model.eval() _a : Any = model(pixel_values=_a ,pixel_mask=_a ) _a : Optional[Any] = model(_a ,output_hidden_states=_a ) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape ,(self.batch_size, self.num_queries, self.hidden_dim) ,) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(_a ,_a ) def __lowercase ( self : Tuple ,_a : List[Any] ,_a : Union[str, Any] ,_a : Tuple ,_a : List[str] ,_a : Any ): '''simple docstring''' _a : int = MaskaFormerForUniversalSegmentation(config=_a ) model.to(_a ) model.eval() def comm_check_on_output(_a : Any ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape ,(self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) ,) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape ,(self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): _a : Any = model(pixel_values=_a ,pixel_mask=_a ) _a : Optional[int] = model(_a ) comm_check_on_output(_a ) _a : List[str] = model( pixel_values=_a ,pixel_mask=_a ,mask_labels=_a ,class_labels=_a ) comm_check_on_output(_a ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape ,torch.Size([1] ) ) @require_torch class UpperCAmelCase__ ( lowercase__ , lowercase__ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Optional[int] = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () __UpperCAmelCase : Dict = {'''feature-extraction''': MaskaFormerModel} if is_torch_available() else {} __UpperCAmelCase : Dict = False __UpperCAmelCase : Tuple = False __UpperCAmelCase : Dict = False __UpperCAmelCase : List[Any] = False def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : Union[str, Any] = MaskaFormerModelTester(self ) _a : Dict = ConfigTester(self ,config_class=_a ,has_text_modality=_a ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' self.config_tester.run_common_tests() def __lowercase ( self : Optional[int] ): '''simple docstring''' _a, _a : List[str] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(_a ,**_a ,output_hidden_states=_a ) def __lowercase ( self : str ): '''simple docstring''' _a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*_a ) @unittest.skip(reason='Mask2Former does not use inputs_embeds' ) def __lowercase ( self : Any ): '''simple docstring''' pass @unittest.skip(reason='Mask2Former does not have a get_input_embeddings method' ) def __lowercase ( self : str ): '''simple docstring''' pass @unittest.skip(reason='Mask2Former is not a generative model' ) def __lowercase ( self : List[Any] ): '''simple docstring''' pass @unittest.skip(reason='Mask2Former does not use token embeddings' ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' pass @require_torch_multi_gpu @unittest.skip( reason='Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def __lowercase ( self : Dict ): '''simple docstring''' pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def __lowercase ( self : List[Any] ): '''simple docstring''' pass def __lowercase ( self : int ): '''simple docstring''' _a, _a : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : Union[str, Any] = model_class(_a ) _a : List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _a : Optional[Any] = [*signature.parameters.keys()] _a : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] ,_a ) @slow def __lowercase ( self : List[str] ): '''simple docstring''' for model_name in ["facebook/mask2former-swin-small-coco-instance"]: _a : Dict = MaskaFormerModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def __lowercase ( self : List[Any] ): '''simple docstring''' _a : int = (self.model_tester.min_size,) * 2 _a : Any = { 'pixel_values': torch.randn((2, 3, *size) ,device=_a ), 'mask_labels': torch.randn((2, 10, *size) ,device=_a ), 'class_labels': torch.zeros(2 ,10 ,device=_a ).long(), } _a : List[Any] = self.model_tester.get_config() _a : int = MaskaFormerForUniversalSegmentation(_a ).to(_a ) _a : str = model(**_a ) self.assertTrue(outputs.loss is not None ) def __lowercase ( self : List[str] ): '''simple docstring''' _a, _a : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(_a ,**_a ,output_hidden_states=_a ) def __lowercase ( self : int ): '''simple docstring''' _a, _a : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : Any = model_class(_a ).to(_a ) _a : Optional[int] = model(**_a ,output_attentions=_a ) self.assertTrue(outputs.attentions is not None ) def __lowercase ( self : Tuple ): '''simple docstring''' if not self.model_tester.is_training: return _a : List[str] = self.all_model_classes[1] _a, _a, _a, _a, _a : List[str] = self.model_tester.prepare_config_and_inputs() _a : Any = model_class(_a ) model.to(_a ) model.train() _a : Union[str, Any] = model(_a ,mask_labels=_a ,class_labels=_a ).loss loss.backward() def __lowercase ( self : int ): '''simple docstring''' _a : int = self.all_model_classes[1] _a, _a, _a, _a, _a : List[Any] = self.model_tester.prepare_config_and_inputs() _a : str = True _a : str = True _a : List[str] = model_class(_a ).to(_a ) model.train() _a : Optional[int] = model(_a ,mask_labels=_a ,class_labels=_a ) _a : Tuple = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() _a : str = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() _a : Dict = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() _a : List[str] = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=_a ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) __lowerCAmelCase = 1e-4 def UpperCAmelCase_ (): """simple docstring""" _a : int = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_vision @slow class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" @cached_property def __lowercase ( self : Union[str, Any] ): '''simple docstring''' return "facebook/mask2former-swin-small-coco-instance" @cached_property def __lowercase ( self : Any ): '''simple docstring''' return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None def __lowercase ( self : Any ): '''simple docstring''' _a : List[str] = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(_a ) _a : int = self.default_image_processor _a : Tuple = prepare_img() _a : Any = image_processor(_a ,return_tensors='pt' ).to(_a ) _a : Union[str, Any] = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(_a ,(1, 3, 384, 384) ) with torch.no_grad(): _a : Optional[Any] = model(**_a ) _a : List[Any] = torch.tensor( [[-0.2790, -1.0717, -1.1668], [-0.5128, -0.3128, -0.4987], [-0.5832, 0.1971, -0.0197]] ).to(_a ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] ,_a ,atol=_a ) ) _a : str = torch.tensor( [[0.8973, 1.1847, 1.1776], [1.1934, 1.5040, 1.5128], [1.1153, 1.4486, 1.4951]] ).to(_a ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] ,_a ,atol=_a ) ) _a : Any = torch.tensor( [[2.1152, 1.7000, -0.8603], [1.5808, 1.8004, -0.9353], [1.6043, 1.7495, -0.5999]] ).to(_a ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] ,_a ,atol=_a ) ) def __lowercase ( self : Tuple ): '''simple docstring''' _a : List[Any] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(_a ).eval() _a : Optional[Any] = self.default_image_processor _a : List[Any] = prepare_img() _a : str = image_processor(_a ,return_tensors='pt' ).to(_a ) _a : Any = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(_a ,(1, 3, 384, 384) ) with torch.no_grad(): _a : Optional[int] = model(**_a ) # masks_queries_logits _a : Dict = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape ,(1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ) _a : Dict = [ [-8.7839, -9.0056, -8.8121], [-7.4104, -7.0313, -6.5401], [-6.6105, -6.3427, -6.4675], ] _a : Optional[Any] = torch.tensor(_a ).to(_a ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] ,_a ,atol=_a ) ) # class_queries_logits _a : str = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape ,(1, model.config.num_queries, model.config.num_labels + 1) ) _a : str = torch.tensor( [ [1.8324, -8.0835, -4.1922], [0.8450, -9.0050, -3.6053], [0.3045, -7.7293, -3.0275], ] ).to(_a ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] ,_a ,atol=_a ) ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a : Any = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(_a ).eval() _a : Tuple = self.default_image_processor _a : Tuple = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] ,segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] ,return_tensors='pt' ,) _a : str = inputs['pixel_values'].to(_a ) _a : str = [el.to(_a ) for el in inputs['mask_labels']] _a : Dict = [el.to(_a ) for el in inputs['class_labels']] with torch.no_grad(): _a : List[str] = model(**_a ) self.assertTrue(outputs.loss is not None )
271
1
'''simple docstring''' from transformers import BertTokenizer, EncoderDecoderModel, SeqaSeqTrainer, SeqaSeqTrainingArguments from transformers.testing_utils import TestCasePlus, require_torch, slow from transformers.utils import is_datasets_available if is_datasets_available(): import datasets class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" @slow @require_torch def __lowercase ( self : str ): '''simple docstring''' _a : List[str] = EncoderDecoderModel.from_encoder_decoder_pretrained('prajjwal1/bert-tiny' ,'prajjwal1/bert-tiny' ) _a : Any = BertTokenizer.from_pretrained('bert-base-uncased' ) _a : Tuple = bertabert.config.encoder.vocab_size _a : List[str] = tokenizer.sep_token_id _a : Optional[Any] = tokenizer.cls_token_id _a : Dict = 128 _a : Union[str, Any] = datasets.load_dataset('cnn_dailymail' ,'3.0.0' ,split='train[:1%]' ) _a : Tuple = datasets.load_dataset('cnn_dailymail' ,'3.0.0' ,split='validation[:1%]' ) _a : Optional[Any] = train_dataset.select(range(32 ) ) _a : List[Any] = val_dataset.select(range(16 ) ) _a : List[str] = 4 def _map_to_encoder_decoder_inputs(_a : str ): # Tokenizer will automatically set [BOS] <text> [EOS] _a : Optional[int] = tokenizer(batch['article'] ,padding='max_length' ,truncation=_a ,max_length=512 ) _a : Optional[int] = tokenizer(batch['highlights'] ,padding='max_length' ,truncation=_a ,max_length=128 ) _a : int = inputs.input_ids _a : Optional[Any] = inputs.attention_mask _a : Optional[int] = outputs.input_ids _a : Union[str, Any] = outputs.input_ids.copy() _a : List[Any] = [ [-100 if token == tokenizer.pad_token_id else token for token in labels] for labels in batch['labels'] ] _a : Tuple = outputs.attention_mask assert all(len(_a ) == 512 for x in inputs.input_ids ) assert all(len(_a ) == 128 for x in outputs.input_ids ) return batch def _compute_metrics(_a : Union[str, Any] ): _a : List[str] = pred.label_ids _a : Union[str, Any] = pred.predictions # all unnecessary tokens are removed _a : Tuple = tokenizer.batch_decode(_a ,skip_special_tokens=_a ) _a : Union[str, Any] = tokenizer.batch_decode(_a ,skip_special_tokens=_a ) _a : str = sum([int(pred_str[i] == label_str[i] ) for i in range(len(_a ) )] ) / len(_a ) return {"accuracy": accuracy} # map train dataset _a : Any = train_dataset.map( _map_to_encoder_decoder_inputs ,batched=_a ,batch_size=_a ,remove_columns=['article', 'highlights'] ,) train_dataset.set_format( type='torch' ,columns=['input_ids', 'attention_mask', 'decoder_input_ids', 'decoder_attention_mask', 'labels'] ,) # same for validation dataset _a : Union[str, Any] = val_dataset.map( _map_to_encoder_decoder_inputs ,batched=_a ,batch_size=_a ,remove_columns=['article', 'highlights'] ,) val_dataset.set_format( type='torch' ,columns=['input_ids', 'attention_mask', 'decoder_input_ids', 'decoder_attention_mask', 'labels'] ,) _a : Tuple = self.get_auto_remove_tmp_dir() _a : Union[str, Any] = SeqaSeqTrainingArguments( output_dir=_a ,per_device_train_batch_size=_a ,per_device_eval_batch_size=_a ,predict_with_generate=_a ,evaluation_strategy='steps' ,do_train=_a ,do_eval=_a ,warmup_steps=0 ,eval_steps=2 ,logging_steps=2 ,) # instantiate trainer _a : Any = SeqaSeqTrainer( model=_a ,args=_a ,compute_metrics=_compute_metrics ,train_dataset=_a ,eval_dataset=_a ,tokenizer=_a ,) # start training trainer.train()
271
'''simple docstring''' import argparse import json from typing import List from ltp import LTP from transformers import BertTokenizer def UpperCAmelCase_ (__a : List[Any] ): """simple docstring""" if ( (cp >= 0x4E_00 and cp <= 0x9F_FF) or (cp >= 0x34_00 and cp <= 0x4D_BF) # or (cp >= 0x2_00_00 and cp <= 0x2_A6_DF) # or (cp >= 0x2_A7_00 and cp <= 0x2_B7_3F) # or (cp >= 0x2_B7_40 and cp <= 0x2_B8_1F) # or (cp >= 0x2_B8_20 and cp <= 0x2_CE_AF) # or (cp >= 0xF9_00 and cp <= 0xFA_FF) or (cp >= 0x2_F8_00 and cp <= 0x2_FA_1F) # ): # return True return False def UpperCAmelCase_ (__a : str ): """simple docstring""" for char in word: _a : Union[str, Any] = ord(__a ) if not _is_chinese_char(__a ): return 0 return 1 def UpperCAmelCase_ (__a : List[str] ): """simple docstring""" _a : Dict = set() for token in tokens: _a : str = len(__a ) > 1 and is_chinese(__a ) if chinese_word: word_set.add(__a ) _a : Optional[Any] = list(__a ) return word_list def UpperCAmelCase_ (__a : List[str] , __a : set() ): """simple docstring""" if not chinese_word_set: return bert_tokens _a : Optional[Any] = max([len(__a ) for w in chinese_word_set] ) _a : Optional[int] = bert_tokens _a, _a : Any = 0, len(__a ) while start < end: _a : Tuple = True if is_chinese(bert_word[start] ): _a : Union[str, Any] = min(end - start , __a ) for i in range(__a , 1 , -1 ): _a : Optional[Any] = ''.join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1 , start + i ): _a : Any = '##' + bert_word[j] _a : Union[str, Any] = start + i _a : int = False break if single_word: start += 1 return bert_word def UpperCAmelCase_ (__a : List[str] , __a : LTP , __a : BertTokenizer ): """simple docstring""" _a : int = [] for i in range(0 , len(__a ) , 1_0_0 ): _a : Union[str, Any] = ltp_tokenizer.seg(lines[i : i + 1_0_0] )[0] _a : Optional[Any] = [get_chinese_word(__a ) for r in res] ltp_res.extend(__a ) assert len(__a ) == len(__a ) _a : str = [] for i in range(0 , len(__a ) , 1_0_0 ): _a : List[str] = bert_tokenizer(lines[i : i + 1_0_0] , add_special_tokens=__a , truncation=__a , max_length=5_1_2 ) bert_res.extend(res['input_ids'] ) assert len(__a ) == len(__a ) _a : List[str] = [] for input_ids, chinese_word in zip(__a , __a ): _a : int = [] for id in input_ids: _a : Optional[int] = bert_tokenizer._convert_id_to_token(__a ) input_tokens.append(__a ) _a : List[str] = add_sub_symbol(__a , __a ) _a : Tuple = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(__a ): if token[:2] == "##": _a : str = token[2:] # save chinese tokens' pos if len(__a ) == 1 and _is_chinese_char(ord(__a ) ): ref_id.append(__a ) ref_ids.append(__a ) assert len(__a ) == len(__a ) return ref_ids def UpperCAmelCase_ (__a : Optional[Any] ): """simple docstring""" with open(args.file_name , 'r' , encoding='utf-8' ) as f: _a : Dict = f.readlines() _a : int = [line.strip() for line in data if len(__a ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' _a : int = LTP(args.ltp ) # faster in GPU device _a : Tuple = BertTokenizer.from_pretrained(args.bert ) _a : int = prepare_ref(__a , __a , __a ) with open(args.save_path , 'w' , encoding='utf-8' ) as f: _a : Optional[Any] = [json.dumps(__a ) + '\n' for ref in ref_ids] f.writelines(__a ) if __name__ == "__main__": __lowerCAmelCase = argparse.ArgumentParser(description="""prepare_chinese_ref""") parser.add_argument( """--file_name""", type=str, default="""./resources/chinese-demo.txt""", help="""file need process, same as training data in lm""", ) parser.add_argument( """--ltp""", type=str, default="""./resources/ltp""", help="""resources for LTP tokenizer, usually a path""" ) parser.add_argument("""--bert""", type=str, default="""./resources/robert""", help="""resources for Bert tokenizer""") parser.add_argument("""--save_path""", type=str, default="""./resources/ref.txt""", help="""path to save res""") __lowerCAmelCase = parser.parse_args() main(args)
271
1
'''simple docstring''' import argparse from collections import defaultdict import yaml __lowerCAmelCase = """docs/source/en/_toctree.yml""" def UpperCAmelCase_ (__a : Optional[int] ): """simple docstring""" _a : Dict = defaultdict(__a ) _a : Dict = [] _a : List[Any] = [] for doc in doc_list: if "local" in doc: counts[doc["local"]] += 1 if doc["title"].lower() == "overview": overview_doc.append({'local': doc['local'], 'title': doc['title']} ) else: new_doc_list.append(__a ) _a : List[str] = new_doc_list _a : Any = [key for key, value in counts.items() if value > 1] _a : Optional[Any] = [] for duplicate_key in duplicates: _a : Dict = list({doc['title'] for doc in doc_list if doc['local'] == duplicate_key} ) if len(__a ) > 1: raise ValueError( f"""{duplicate_key} is present several times in the documentation table of content at """ '`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the ' 'others.' ) # Only add this once new_doc.append({'local': duplicate_key, 'title': titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in doc_list if 'local' not in counts or counts[doc['local']] == 1] ) _a : Union[str, Any] = sorted(__a , key=lambda __a : s["title"].lower() ) # "overview" gets special treatment and is always first if len(__a ) > 1: raise ValueError('{doc_list} has two \'overview\' docs which is not allowed.' ) overview_doc.extend(__a ) # Sort return overview_doc def UpperCAmelCase_ (__a : int=False ): """simple docstring""" with open(__a , encoding='utf-8' ) as f: _a : Optional[Any] = yaml.safe_load(f.read() ) # Get to the API doc _a : Union[str, Any] = 0 while content[api_idx]["title"] != "API": api_idx += 1 _a : Any = content[api_idx]['sections'] # Then to the model doc _a : Any = 0 while api_doc[scheduler_idx]["title"] != "Schedulers": scheduler_idx += 1 _a : Optional[int] = api_doc[scheduler_idx]['sections'] _a : Optional[Any] = clean_doc_toc(__a ) _a : List[str] = False if new_scheduler_doc != scheduler_doc: _a : Dict = True if overwrite: _a : Optional[Any] = new_scheduler_doc if diff: if overwrite: _a : int = api_doc with open(__a , 'w' , encoding='utf-8' ) as f: f.write(yaml.dump(__a , allow_unicode=__a ) ) else: raise ValueError( 'The model doc part of the table of content is not properly sorted, run `make style` to fix this.' ) def UpperCAmelCase_ (__a : int=False ): """simple docstring""" with open(__a , encoding='utf-8' ) as f: _a : Optional[int] = yaml.safe_load(f.read() ) # Get to the API doc _a : int = 0 while content[api_idx]["title"] != "API": api_idx += 1 _a : Tuple = content[api_idx]['sections'] # Then to the model doc _a : List[str] = 0 while api_doc[pipeline_idx]["title"] != "Pipelines": pipeline_idx += 1 _a : str = False _a : Dict = api_doc[pipeline_idx]['sections'] _a : List[str] = [] # sort sub pipeline docs for pipeline_doc in pipeline_docs: if "section" in pipeline_doc: _a : List[str] = pipeline_doc['section'] _a : int = clean_doc_toc(__a ) if overwrite: _a : Any = new_sub_pipeline_doc new_pipeline_docs.append(__a ) # sort overall pipeline doc _a : int = clean_doc_toc(__a ) if new_pipeline_docs != pipeline_docs: _a : str = True if overwrite: _a : Tuple = new_pipeline_docs if diff: if overwrite: _a : str = api_doc with open(__a , 'w' , encoding='utf-8' ) as f: f.write(yaml.dump(__a , allow_unicode=__a ) ) else: raise ValueError( 'The model doc part of the table of content is not properly sorted, run `make style` to fix this.' ) if __name__ == "__main__": __lowerCAmelCase = argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") __lowerCAmelCase = parser.parse_args() check_scheduler_doc(args.fix_and_overwrite) check_pipeline_doc(args.fix_and_overwrite)
271
'''simple docstring''' import warnings from ...utils import logging from .image_processing_videomae import VideoMAEImageProcessor __lowerCAmelCase = logging.get_logger(__name__) class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" def __init__( self : Tuple ,*_a : List[str] ,**_a : Any ): '''simple docstring''' warnings.warn( 'The class VideoMAEFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use VideoMAEImageProcessor instead.' ,_a ,) super().__init__(*_a ,**_a )
271
1
'''simple docstring''' import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : Dict = ['''image_processor''', '''tokenizer'''] __UpperCAmelCase : Optional[int] = '''ViTImageProcessor''' __UpperCAmelCase : List[str] = ('''CLIPTokenizer''', '''CLIPTokenizerFast''') def __init__( self : Dict ,_a : List[str]=None ,_a : List[Any]=None ,**_a : int ): '''simple docstring''' _a : Dict = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' ,_a ,) _a : Tuple = kwargs.pop('feature_extractor' ) _a : Any = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(_a ,_a ) def __call__( self : str ,_a : Tuple=None ,_a : str=None ,_a : Tuple=None ,_a : int=None ,**_a : Any ): '''simple docstring''' if text is None and visual_prompt is None and images is None: raise ValueError('You have to specify either text, visual prompt or images.' ) if text is not None and visual_prompt is not None: raise ValueError('You have to specify exactly one type of prompt. Either text or visual prompt.' ) if text is not None: _a : str = self.tokenizer(_a ,return_tensors=_a ,**_a ) if visual_prompt is not None: _a : Optional[int] = self.image_processor(_a ,return_tensors=_a ,**_a ) if images is not None: _a : Optional[Any] = self.image_processor(_a ,return_tensors=_a ,**_a ) if visual_prompt is not None and images is not None: _a : List[str] = { 'pixel_values': image_features.pixel_values, 'conditional_pixel_values': prompt_features.pixel_values, } return encoding elif text is not None and images is not None: _a : List[Any] = image_features.pixel_values return encoding elif text is not None: return encoding elif visual_prompt is not None: _a : List[str] = { 'conditional_pixel_values': prompt_features.pixel_values, } return encoding else: return BatchEncoding(data=dict(**_a ) ,tensor_type=_a ) def __lowercase ( self : List[Any] ,*_a : Dict ,**_a : Any ): '''simple docstring''' return self.tokenizer.batch_decode(*_a ,**_a ) def __lowercase ( self : str ,*_a : Optional[int] ,**_a : List[Any] ): '''simple docstring''' return self.tokenizer.decode(*_a ,**_a ) @property def __lowercase ( self : Optional[int] ): '''simple docstring''' warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' ,_a ,) return self.image_processor_class @property def __lowercase ( self : Dict ): '''simple docstring''' warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' ,_a ,) return self.image_processor
271
'''simple docstring''' from __future__ import annotations from random import choice def UpperCAmelCase_ (__a : str ): """simple docstring""" return choice(__a ) def UpperCAmelCase_ (__a : list[int] , __a : int ): """simple docstring""" _a : Dict = random_pivot(__a ) # partition based on pivot # linear time _a : Optional[int] = [e for e in lst if e < pivot] _a : List[str] = [e for e in lst if e > pivot] # if we get lucky, pivot might be the element we want. # we can easily see this: # small (elements smaller than k) # + pivot (kth element) # + big (elements larger than k) if len(__a ) == k - 1: return pivot # pivot is in elements bigger than k elif len(__a ) < k - 1: return kth_number(__a , k - len(__a ) - 1 ) # pivot is in elements smaller than k else: return kth_number(__a , __a ) if __name__ == "__main__": import doctest doctest.testmod()
271
1
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionAttendAndExcitePipeline, UNetaDConditionModel, ) from diffusers.utils import load_numpy, skip_mps, slow from diffusers.utils.testing_utils import require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin __lowerCAmelCase = False @skip_mps class UpperCAmelCase__ ( lowercase__ , lowercase__ , lowercase__ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : List[str] = StableDiffusionAttendAndExcitePipeline __UpperCAmelCase : Optional[Any] = False __UpperCAmelCase : Optional[int] = TEXT_TO_IMAGE_PARAMS __UpperCAmelCase : int = TEXT_TO_IMAGE_BATCH_PARAMS.union({'''token_indices'''} ) __UpperCAmelCase : Any = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCAmelCase : Dict = TEXT_TO_IMAGE_IMAGE_PARAMS @classmethod def __lowercase ( cls : Optional[int] ): '''simple docstring''' super().setUpClass() torch.use_deterministic_algorithms(_a ) @classmethod def __lowercase ( cls : Tuple ): '''simple docstring''' super().tearDownClass() torch.use_deterministic_algorithms(_a ) def __lowercase ( self : str ): '''simple docstring''' torch.manual_seed(0 ) _a : Union[str, Any] = UNetaDConditionModel( block_out_channels=(32, 64) ,layers_per_block=1 ,sample_size=32 ,in_channels=4 ,out_channels=4 ,down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') ,up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') ,cross_attention_dim=32 ,attention_head_dim=(2, 4) ,use_linear_projection=_a ,) _a : List[Any] = DDIMScheduler( beta_start=0.0_0085 ,beta_end=0.012 ,beta_schedule='scaled_linear' ,clip_sample=_a ,set_alpha_to_one=_a ,) torch.manual_seed(0 ) _a : str = AutoencoderKL( block_out_channels=[32, 64] ,in_channels=3 ,out_channels=3 ,down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] ,up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] ,latent_channels=4 ,sample_size=128 ,) torch.manual_seed(0 ) _a : Optional[int] = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1E-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1000 ,hidden_act='gelu' ,projection_dim=512 ,) _a : int = CLIPTextModel(_a ) _a : Optional[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) _a : Tuple = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def __lowercase ( self : Optional[Any] ,_a : str ,_a : Union[str, Any]=0 ): '''simple docstring''' if str(_a ).startswith('mps' ): _a : List[str] = torch.manual_seed(_a ) else: _a : str = torch.Generator(device=_a ).manual_seed(_a ) _a : Any = { 'prompt': 'a cat and a frog', 'token_indices': [2, 5], 'generator': generator, 'num_inference_steps': 1, 'guidance_scale': 6.0, 'output_type': 'numpy', 'max_iter_to_alter': 2, 'thresholds': {0: 0.7}, } return inputs def __lowercase ( self : List[str] ): '''simple docstring''' _a : Any = 'cpu' _a : Dict = self.get_dummy_components() _a : Tuple = self.pipeline_class(**_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) _a : List[str] = self.get_dummy_inputs(_a ) _a : Tuple = pipe(**_a ).images _a : Union[str, Any] = image[0, -3:, -3:, -1] self.assertEqual(image.shape ,(1, 64, 64, 3) ) _a : List[str] = np.array( [0.6390_5364, 0.6289_7307, 0.4859_9017, 0.513_3624, 0.555_0048, 0.4576_9516, 0.5032_6973, 0.502_3139, 0.4538_4496] ) _a : List[Any] = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_a ,1E-3 ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' super().test_cpu_offload_forward_pass(expected_max_diff=5E-4 ) def __lowercase ( self : Optional[int] ): '''simple docstring''' self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def __lowercase ( self : List[str] ): '''simple docstring''' self._test_inference_batch_single_identical(batch_size=2 ,expected_max_diff=7E-4 ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3 ) def __lowercase ( self : int ): '''simple docstring''' super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5E-4 ) def __lowercase ( self : int ): '''simple docstring''' super().test_save_load_local(expected_max_difference=5E-4 ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' super().test_save_load_optional_components(expected_max_difference=4E-4 ) @require_torch_gpu @slow class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" @classmethod def __lowercase ( cls : List[str] ): '''simple docstring''' super().setUpClass() torch.use_deterministic_algorithms(_a ) @classmethod def __lowercase ( cls : List[Any] ): '''simple docstring''' super().tearDownClass() torch.use_deterministic_algorithms(_a ) def __lowercase ( self : Optional[int] ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a : Tuple = torch.manual_seed(51 ) _a : str = StableDiffusionAttendAndExcitePipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' ,safety_checker=_a ,torch_dtype=torch.floataa ) pipe.to('cuda' ) _a : Any = 'a painting of an elephant with glasses' _a : List[str] = [5, 7] _a : List[Any] = pipe( prompt=_a ,token_indices=_a ,guidance_scale=7.5 ,generator=_a ,num_inference_steps=5 ,max_iter_to_alter=5 ,output_type='numpy' ,).images[0] _a : Dict = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/attend-and-excite/elephant_glasses.npy' ) assert np.abs((expected_image - image).max() ) < 5E-1
271
'''simple docstring''' class UpperCAmelCase__ : """simple docstring""" def __init__( self : Dict ): '''simple docstring''' _a : Dict = {} def __lowercase ( self : Union[str, Any] ): '''simple docstring''' print(self.vertex ) for i in self.vertex: print(_a ,' -> ' ,' -> '.join([str(_a ) for j in self.vertex[i]] ) ) def __lowercase ( self : Dict ,_a : int ,_a : int ): '''simple docstring''' if from_vertex in self.vertex: self.vertex[from_vertex].append(_a ) else: # else make a new vertex _a : int = [to_vertex] def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : Tuple = [False] * len(self.vertex ) # call the recursive helper function for i in range(len(self.vertex ) ): if not visited[i]: self.dfs_recursive(_a ,_a ) def __lowercase ( self : Union[str, Any] ,_a : int ,_a : list ): '''simple docstring''' _a : List[Any] = True print(_a ,end=' ' ) # Recur for all the vertices that are adjacent to this node for i in self.vertex: if not visited[i]: self.dfs_recursive(_a ,_a ) if __name__ == "__main__": __lowerCAmelCase = Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) g.print_graph() print("""DFS:""") g.dfs() # OUTPUT: # 0 -> 1 -> 2 # 1 -> 2 # 2 -> 0 -> 3 # 3 -> 3 # DFS: # 0 1 2 3
271
1
'''simple docstring''' import argparse import os import numpy as np import tensorflow as tf import torch from transformers import BertModel def UpperCAmelCase_ (__a : BertModel , __a : str , __a : str ): """simple docstring""" _a : List[str] = ('dense.weight', 'attention.self.query', 'attention.self.key', 'attention.self.value') _a : List[Any] = ( ('layer.', 'layer_'), ('word_embeddings.weight', 'word_embeddings'), ('position_embeddings.weight', 'position_embeddings'), ('token_type_embeddings.weight', 'token_type_embeddings'), ('.', '/'), ('LayerNorm/weight', 'LayerNorm/gamma'), ('LayerNorm/bias', 'LayerNorm/beta'), ('weight', 'kernel'), ) if not os.path.isdir(__a ): os.makedirs(__a ) _a : List[str] = model.state_dict() def to_tf_var_name(__a : str ): for patt, repl in iter(__a ): _a : Optional[Any] = name.replace(__a , __a ) return f"""bert/{name}""" def create_tf_var(__a : np.ndarray , __a : str , __a : tf.Session ): _a : Dict = tf.dtypes.as_dtype(tensor.dtype ) _a : Tuple = tf.get_variable(dtype=__a , shape=tensor.shape , name=__a , initializer=tf.zeros_initializer() ) session.run(tf.variables_initializer([tf_var] ) ) session.run(__a ) return tf_var tf.reset_default_graph() with tf.Session() as session: for var_name in state_dict: _a : str = to_tf_var_name(__a ) _a : Union[str, Any] = state_dict[var_name].numpy() if any(x in var_name for x in tensors_to_transpose ): _a : Optional[int] = torch_tensor.T _a : List[str] = create_tf_var(tensor=__a , name=__a , session=__a ) tf.keras.backend.set_value(__a , __a ) _a : List[Any] = session.run(__a ) print(f"""Successfully created {tf_name}: {np.allclose(__a , __a )}""" ) _a : Tuple = tf.train.Saver(tf.trainable_variables() ) saver.save(__a , os.path.join(__a , model_name.replace('-' , '_' ) + '.ckpt' ) ) def UpperCAmelCase_ (__a : Optional[int]=None ): """simple docstring""" _a : List[str] = argparse.ArgumentParser() parser.add_argument('--model_name' , type=__a , required=__a , help='model name e.g. bert-base-uncased' ) parser.add_argument( '--cache_dir' , type=__a , default=__a , required=__a , help='Directory containing pytorch model' ) parser.add_argument('--pytorch_model_path' , type=__a , required=__a , help='/path/to/<pytorch-model-name>.bin' ) parser.add_argument('--tf_cache_dir' , type=__a , required=__a , help='Directory in which to save tensorflow model' ) _a : Any = parser.parse_args(__a ) _a : str = BertModel.from_pretrained( pretrained_model_name_or_path=args.model_name , state_dict=torch.load(args.pytorch_model_path ) , cache_dir=args.cache_dir , ) convert_pytorch_checkpoint_to_tf(model=__a , ckpt_dir=args.tf_cache_dir , model_name=args.model_name ) if __name__ == "__main__": main()
271
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = """▁""" __lowerCAmelCase = {"""vocab_file""": """sentencepiece.bpe.model""", """monolingual_vocab_file""": """dict.txt"""} __lowerCAmelCase = { """vocab_file""": { """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model""", }, """monolingual_vocab_file""": { """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt""", }, } __lowerCAmelCase = {"""vinai/bartpho-syllable""": 1_0_2_4} class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : Optional[Any] = VOCAB_FILES_NAMES __UpperCAmelCase : Dict = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Dict = ['''input_ids''', '''attention_mask'''] def __init__( self : str ,_a : str ,_a : Any ,_a : Any="<s>" ,_a : Dict="</s>" ,_a : int="</s>" ,_a : Union[str, Any]="<s>" ,_a : List[Any]="<unk>" ,_a : Optional[Any]="<pad>" ,_a : List[str]="<mask>" ,_a : Optional[Dict[str, Any]] = None ,**_a : int ,): '''simple docstring''' _a : Any = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else mask_token _a : Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_a ,eos_token=_a ,unk_token=_a ,sep_token=_a ,cls_token=_a ,pad_token=_a ,mask_token=_a ,sp_model_kwargs=self.sp_model_kwargs ,**_a ,) _a : Optional[int] = vocab_file _a : Union[str, Any] = monolingual_vocab_file _a : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_a ) ) # Load the reduced vocab # Keep order of special tokens for backward compatibility _a : Union[str, Any] = {} _a : int = 0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(_a ) not in self.fairseq_tokens_to_ids: _a : int = cnt cnt += 1 with open(_a ,'r' ,encoding='utf-8' ) as f: for line in f.readlines(): _a : str = line.strip().split()[0] _a : Tuple = len(self.fairseq_tokens_to_ids ) if str(_a ) not in self.fairseq_tokens_to_ids: _a : List[str] = len(self.fairseq_tokens_to_ids ) _a : Tuple = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : Union[str, Any] ): '''simple docstring''' _a : int = self.__dict__.copy() _a : str = None _a : Optional[Any] = self.sp_model.serialized_model_proto() return state def __setstate__( self : Tuple ,_a : Tuple ): '''simple docstring''' _a : Tuple = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs' ): _a : List[str] = {} _a : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def __lowercase ( self : Dict ,_a : List[int] ,_a : Optional[List[int]] = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _a : Dict = [self.cls_token_id] _a : int = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def __lowercase ( self : int ,_a : List[int] ,_a : Optional[List[int]] = None ,_a : bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a ,token_ids_a=_a ,already_has_special_tokens=_a ) if token_ids_a is None: return [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1, 1] + ([0] * len(_a )) + [1] def __lowercase ( self : Tuple ,_a : List[int] ,_a : Optional[List[int]] = None ): '''simple docstring''' _a : List[str] = [self.sep_token_id] _a : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def __lowercase ( self : Dict ): '''simple docstring''' return len(self.fairseq_ids_to_tokens ) def __lowercase ( self : Dict ): '''simple docstring''' _a : List[str] = {self.convert_ids_to_tokens(_a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __lowercase ( self : Tuple ,_a : str ): '''simple docstring''' return self.sp_model.encode(_a ,out_type=_a ) def __lowercase ( self : Union[str, Any] ,_a : Union[str, Any] ): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def __lowercase ( self : Any ,_a : int ): '''simple docstring''' return self.fairseq_ids_to_tokens[index] def __lowercase ( self : Tuple ,_a : Union[str, Any] ): '''simple docstring''' _a : str = ''.join(_a ).replace(_a ,' ' ).strip() return out_string def __lowercase ( self : Union[str, Any] ,_a : str ,_a : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(_a ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _a : int = os.path.join( _a ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) _a : int = os.path.join( _a ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['monolingual_vocab_file'] ,) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,_a ) elif not os.path.isfile(self.vocab_file ): with open(_a ,'wb' ) as fi: _a : List[Any] = self.sp_model.serialized_model_proto() fi.write(_a ) if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath( _a ) and os.path.isfile(self.monolingual_vocab_file ): copyfile(self.monolingual_vocab_file ,_a ) elif not os.path.isfile(self.monolingual_vocab_file ): with open(_a ,'w' ,encoding='utf-8' ) as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(F"""{str(_a )} \n""" ) return out_vocab_file, out_monolingual_vocab_file
271
1
'''simple docstring''' import unittest from transformers import BarthezTokenizer, BarthezTokenizerFast, BatchEncoding from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers @require_sentencepiece @slow # see https://github.com/huggingface/transformers/issues/11457 class UpperCAmelCase__ ( lowercase__ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : List[str] = BarthezTokenizer __UpperCAmelCase : Optional[Any] = BarthezTokenizerFast __UpperCAmelCase : List[str] = True __UpperCAmelCase : str = True def __lowercase ( self : Tuple ): '''simple docstring''' super().setUp() _a : str = BarthezTokenizerFast.from_pretrained('moussaKam/mbarthez' ) tokenizer.save_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ,legacy_format=_a ) _a : List[str] = tokenizer def __lowercase ( self : List[Any] ): '''simple docstring''' _a : str = '<pad>' _a : str = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_a ) ,_a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_a ) ,_a ) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] ,'<s>' ) self.assertEqual(vocab_keys[1] ,'<pad>' ) self.assertEqual(vocab_keys[-1] ,'<mask>' ) self.assertEqual(len(_a ) ,10_1122 ) def __lowercase ( self : List[Any] ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size ,10_1122 ) @require_torch def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : Any = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] _a : Optional[Any] = [0, 57, 3018, 7_0307, 91, 2] _a : Optional[int] = self.tokenizer( _a ,max_length=len(_a ) ,padding=_a ,truncation=_a ,return_tensors='pt' ) self.assertIsInstance(_a ,_a ) self.assertEqual((2, 6) ,batch.input_ids.shape ) self.assertEqual((2, 6) ,batch.attention_mask.shape ) _a : List[Any] = batch.input_ids.tolist()[0] self.assertListEqual(_a ,_a ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' if not self.test_rust_tokenizer: return _a : Dict = self.get_tokenizer() _a : Optional[Any] = self.get_rust_tokenizer() _a : Union[str, Any] = 'I was born in 92000, and this is falsé.' _a : int = tokenizer.tokenize(_a ) _a : Optional[Any] = rust_tokenizer.tokenize(_a ) self.assertListEqual(_a ,_a ) _a : List[str] = tokenizer.encode(_a ,add_special_tokens=_a ) _a : List[Any] = rust_tokenizer.encode(_a ,add_special_tokens=_a ) self.assertListEqual(_a ,_a ) _a : Optional[int] = self.get_rust_tokenizer() _a : List[str] = tokenizer.encode(_a ) _a : int = rust_tokenizer.encode(_a ) self.assertListEqual(_a ,_a ) @slow def __lowercase ( self : List[Any] ): '''simple docstring''' _a : List[Any] = {'input_ids': [[0, 490, 1_4328, 4507, 354, 47, 4_3669, 95, 25, 7_8117, 2_0215, 1_9779, 190, 22, 400, 4, 3_5343, 8_0310, 603, 86, 2_4937, 105, 3_3438, 9_4762, 196, 3_9642, 7, 15, 1_5933, 173, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 1_0534, 87, 25, 66, 3358, 196, 5_5289, 8, 8_2961, 81, 2204, 7_5203, 7, 15, 763, 1_2956, 216, 178, 1_4328, 9595, 1377, 6_9693, 7, 448, 7_1021, 196, 1_8106, 1437, 1_3974, 108, 9083, 4, 4_9315, 7, 39, 86, 1326, 2793, 4_6333, 4, 448, 196, 7_4588, 7, 4_9315, 7, 39, 21, 822, 3_8470, 74, 21, 6_6723, 6_2480, 8, 2_2050, 5, 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, 0, 0, 0, 0, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # moussaKam/mbarthez is a french model. So we also use french texts. _a : Tuple = [ 'Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ' 'utilisé principalement dans le domaine du traitement automatique des langues (TAL).', 'À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ' 'pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ' 'telles que la traduction et la synthèse de texte.', ] self.tokenizer_integration_test_util( expected_encoding=_a ,model_name='moussaKam/mbarthez' ,revision='c2e4ecbca5e3cd2c37fe1ac285ca4fbdf1366fb6' ,sequences=_a ,)
271
'''simple docstring''' import numpy as np from transformers import BatchFeature from transformers.testing_utils import require_tf, require_torch from .test_feature_extraction_common import FeatureExtractionSavingTestMixin class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = None __UpperCAmelCase : List[Any] = None @property def __lowercase ( self : Dict ): '''simple docstring''' return self.feat_extract_tester.prepare_feat_extract_dict() def __lowercase ( self : str ): '''simple docstring''' _a : Dict = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(_a ,'feature_size' ) ) self.assertTrue(hasattr(_a ,'sampling_rate' ) ) self.assertTrue(hasattr(_a ,'padding_value' ) ) def __lowercase ( self : int ): '''simple docstring''' _a : Any = self.feat_extract_tester.prepare_inputs_for_common() _a : str = self.feature_extraction_class(**self.feat_extract_dict ) _a : int = feat_extract.model_input_names[0] _a : List[Any] = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(_a ) == len(_a ) for x, y in zip(_a ,processed_features[input_name] ) ) ) _a : Any = self.feat_extract_tester.prepare_inputs_for_common(equal_length=_a ) _a : Union[str, Any] = BatchFeature({input_name: speech_inputs} ,tensor_type='np' ) _a : Union[str, Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: _a : Optional[int] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_torch def __lowercase ( self : Any ): '''simple docstring''' _a : List[Any] = self.feat_extract_tester.prepare_inputs_for_common(equal_length=_a ) _a : Dict = self.feature_extraction_class(**self.feat_extract_dict ) _a : int = feat_extract.model_input_names[0] _a : str = BatchFeature({input_name: speech_inputs} ,tensor_type='pt' ) _a : str = processed_features[input_name] if len(batch_features_input.shape ) < 3: _a : str = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_tf def __lowercase ( self : int ): '''simple docstring''' _a : int = self.feat_extract_tester.prepare_inputs_for_common(equal_length=_a ) _a : Dict = self.feature_extraction_class(**self.feat_extract_dict ) _a : Tuple = feat_extract.model_input_names[0] _a : int = BatchFeature({input_name: speech_inputs} ,tensor_type='tf' ) _a : Optional[int] = processed_features[input_name] if len(batch_features_input.shape ) < 3: _a : Optional[Any] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) def __lowercase ( self : Dict ,_a : Any=False ): '''simple docstring''' def _inputs_have_equal_length(_a : Tuple ): _a : Tuple = len(input[0] ) for input_slice in input[1:]: if len(_a ) != length: return False return True def _inputs_are_equal(_a : Optional[Any] ,_a : Union[str, Any] ): if len(_a ) != len(_a ): return False for input_slice_a, input_slice_a in zip(_a ,_a ): if not np.allclose(np.asarray(_a ) ,np.asarray(_a ) ,atol=1E-3 ): return False return True _a : int = self.feature_extraction_class(**self.feat_extract_dict ) _a : Tuple = self.feat_extract_tester.prepare_inputs_for_common(numpify=_a ) _a : Union[str, Any] = feat_extract.model_input_names[0] _a : Tuple = BatchFeature({input_name: speech_inputs} ) _a : str = self.feat_extract_tester.seq_length_diff _a : Dict = self.feat_extract_tester.max_seq_length + pad_diff _a : Dict = self.feat_extract_tester.min_seq_length _a : Optional[Any] = self.feat_extract_tester.batch_size _a : Tuple = self.feat_extract_tester.feature_size # test padding for List[int] + numpy _a : int = feat_extract.pad(_a ,padding=_a ) _a : List[Any] = input_a[input_name] _a : Tuple = feat_extract.pad(_a ,padding='longest' ) _a : Any = input_a[input_name] _a : Optional[Any] = feat_extract.pad(_a ,padding='max_length' ,max_length=len(speech_inputs[-1] ) ) _a : List[str] = input_a[input_name] _a : List[str] = feat_extract.pad(_a ,padding='longest' ,return_tensors='np' ) _a : str = input_a[input_name] # max_length parameter has to be provided when setting `padding="max_length"` with self.assertRaises(_a ): feat_extract.pad(_a ,padding='max_length' )[input_name] _a : int = feat_extract.pad( _a ,padding='max_length' ,max_length=_a ,return_tensors='np' ) _a : Optional[int] = input_a[input_name] self.assertFalse(_inputs_have_equal_length(_a ) ) self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertTrue(_inputs_are_equal(_a ,_a ) ) self.assertTrue(len(input_a[0] ) == pad_min_length ) self.assertTrue(len(input_a[1] ) == pad_min_length + pad_diff ) self.assertTrue(input_a.shape[:2] == (batch_size, len(input_a[0] )) ) self.assertTrue(input_a.shape[:2] == (batch_size, pad_max_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == input_a.shape[2] == feature_size ) # test padding for `pad_to_multiple_of` for List[int] + numpy _a : Tuple = feat_extract.pad(_a ,pad_to_multiple_of=10 ) _a : List[str] = input_a[input_name] _a : str = feat_extract.pad(_a ,padding='longest' ,pad_to_multiple_of=10 ) _a : Tuple = input_a[input_name] _a : Optional[int] = feat_extract.pad( _a ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=_a ) _a : Any = input_a[input_name] _a : Optional[int] = feat_extract.pad( _a ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=_a ,return_tensors='np' ,) _a : Dict = input_a[input_name] self.assertTrue(all(len(_a ) % 10 == 0 for x in input_a ) ) self.assertTrue(_inputs_are_equal(_a ,_a ) ) _a : List[str] = pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10 self.assertTrue(all(len(_a ) == expected_mult_pad_length for x in input_a ) ) self.assertEqual(input_a.shape[:2] ,(batch_size, expected_mult_pad_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == feature_size ) # Check padding value is correct _a : Any = (np.ones(self.feat_extract_tester.feature_size ) * feat_extract.padding_value).sum() self.assertTrue( abs(np.asarray(input_a[0] )[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1E-3 ) self.assertTrue( abs( np.asarray(input_a[1] )[pad_min_length + pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff) ) < 1E-3 ) self.assertTrue( abs( np.asarray(input_a[2] )[pad_min_length + 2 * pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff) ) < 1E-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1E-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length) ) < 1E-3 ) def __lowercase ( self : List[Any] ,_a : Optional[int]=False ): '''simple docstring''' def _inputs_have_equal_length(_a : List[str] ): _a : Union[str, Any] = len(input[0] ) for input_slice in input[1:]: if len(_a ) != length: return False return True def _inputs_are_equal(_a : List[str] ,_a : List[str] ): if len(_a ) != len(_a ): return False for input_slice_a, input_slice_a in zip(_a ,_a ): if not np.allclose(np.asarray(_a ) ,np.asarray(_a ) ,atol=1E-3 ): return False return True _a : Dict = self.feature_extraction_class(**self.feat_extract_dict ) _a : str = self.feat_extract_tester.prepare_inputs_for_common(numpify=_a ) _a : Any = feat_extract.model_input_names[0] _a : List[Any] = BatchFeature({input_name: speech_inputs} ) # truncate to smallest _a : Union[str, Any] = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,truncation=_a ) _a : str = input_a[input_name] _a : List[str] = feat_extract.pad(_a ,padding='max_length' ,max_length=len(speech_inputs[0] ) ) _a : Tuple = input_a[input_name] self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertFalse(_inputs_have_equal_length(_a ) ) # truncate to smallest with np _a : Dict = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ,truncation=_a ,) _a : Any = input_a[input_name] _a : List[Any] = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ) _a : int = input_a[input_name] self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertTrue(input_a.shape[1] == len(speech_inputs[0] ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(_a ) ) # truncate to middle _a : Dict = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=_a ,return_tensors='np' ,) _a : List[Any] = input_a[input_name] _a : Tuple = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=_a ) _a : Tuple = input_a[input_name] _a : Tuple = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,return_tensors='np' ) _a : Dict = input_a[input_name] self.assertTrue(input_a.shape[1] == len(speech_inputs[1] ) ) self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertTrue(_inputs_are_equal(_a ,_a ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(_a ) ) self.assertTrue(len(input_a[-1] ) == len(speech_inputs[-1] ) ) # padding has to be max_length when setting `truncation=True` with self.assertRaises(_a ): feat_extract.pad(_a ,truncation=_a )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(_a ): feat_extract.pad(_a ,padding='longest' ,truncation=_a )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(_a ): feat_extract.pad(_a ,padding='longest' ,truncation=_a )[input_name] # max_length parameter has to be provided when setting `truncation=True` and padding="max_length" with self.assertRaises(_a ): feat_extract.pad(_a ,padding='max_length' ,truncation=_a )[input_name] # test truncation for `pad_to_multiple_of` for List[int] + numpy _a : Optional[Any] = 12 _a : List[Any] = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=_a ,truncation=_a ,) _a : Tuple = input_a[input_name] _a : str = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=_a ,) _a : List[Any] = input_a[input_name] # retrieve expected_length as multiple of pad_to_multiple_of _a : List[Any] = len(speech_inputs[0] ) if expected_length % pad_to_multiple_of != 0: _a : Union[str, Any] = ((len(speech_inputs[0] ) // pad_to_multiple_of) + 1) * pad_to_multiple_of self.assertTrue(len(input_a[0] ) == expected_length ) self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertFalse(_inputs_have_equal_length(_a ) ) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' self._check_padding(numpify=_a ) def __lowercase ( self : Tuple ): '''simple docstring''' self._check_padding(numpify=_a ) def __lowercase ( self : Dict ): '''simple docstring''' self._check_truncation(numpify=_a ) def __lowercase ( self : str ): '''simple docstring''' self._check_truncation(numpify=_a ) @require_torch def __lowercase ( self : Dict ): '''simple docstring''' _a : Any = self.feature_extraction_class(**self.feat_extract_dict ) _a : List[Any] = self.feat_extract_tester.prepare_inputs_for_common() _a : Union[str, Any] = feat_extract.model_input_names[0] _a : Optional[int] = BatchFeature({input_name: speech_inputs} ) _a : List[Any] = feat_extract.pad(_a ,padding='longest' ,return_tensors='np' )[input_name] _a : List[str] = feat_extract.pad(_a ,padding='longest' ,return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1E-2 ) @require_tf def __lowercase ( self : int ): '''simple docstring''' _a : List[str] = self.feature_extraction_class(**self.feat_extract_dict ) _a : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_common() _a : Dict = feat_extract.model_input_names[0] _a : Optional[Any] = BatchFeature({input_name: speech_inputs} ) _a : Dict = feat_extract.pad(_a ,padding='longest' ,return_tensors='np' )[input_name] _a : Any = feat_extract.pad(_a ,padding='longest' ,return_tensors='tf' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_tf.numpy().astype(np.floataa ).sum() ) < 1E-2 ) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : str = self.feat_extract_dict _a : List[Any] = True _a : Optional[int] = self.feature_extraction_class(**_a ) _a : List[Any] = self.feat_extract_tester.prepare_inputs_for_common() _a : Tuple = [len(_a ) for x in speech_inputs] _a : int = feat_extract.model_input_names[0] _a : Optional[Any] = BatchFeature({input_name: speech_inputs} ) _a : str = feat_extract.pad(_a ,padding='longest' ,return_tensors='np' ) self.assertIn('attention_mask' ,_a ) self.assertListEqual(list(processed.attention_mask.shape ) ,list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() ,_a ) def __lowercase ( self : int ): '''simple docstring''' _a : Any = self.feat_extract_dict _a : Tuple = True _a : Optional[int] = self.feature_extraction_class(**_a ) _a : Dict = self.feat_extract_tester.prepare_inputs_for_common() _a : Dict = [len(_a ) for x in speech_inputs] _a : Union[str, Any] = feat_extract.model_input_names[0] _a : Any = BatchFeature({input_name: speech_inputs} ) _a : List[Any] = min(_a ) _a : Dict = feat_extract.pad( _a ,padding='max_length' ,max_length=_a ,truncation=_a ,return_tensors='np' ) self.assertIn('attention_mask' ,_a ) self.assertListEqual( list(processed_pad.attention_mask.shape ) ,[processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() ,[max_length for x in speech_inputs] )
271
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCAmelCase = { """configuration_git""": ["""GIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GitConfig""", """GitVisionConfig"""], """processing_git""": ["""GitProcessor"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ """GIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """GitForCausalLM""", """GitModel""", """GitPreTrainedModel""", """GitVisionModel""", ] if TYPE_CHECKING: from .configuration_git import GIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GitConfig, GitVisionConfig from .processing_git import GitProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_git import ( GIT_PRETRAINED_MODEL_ARCHIVE_LIST, GitForCausalLM, GitModel, GitPreTrainedModel, GitVisionModel, ) else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
271
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import KarrasVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : UNetaDModel __UpperCAmelCase : KarrasVeScheduler def __init__( self : Union[str, Any] ,_a : UNetaDModel ,_a : KarrasVeScheduler ): '''simple docstring''' super().__init__() self.register_modules(unet=_a ,scheduler=_a ) @torch.no_grad() def __call__( self : List[Any] ,_a : int = 1 ,_a : int = 50 ,_a : Optional[Union[torch.Generator, List[torch.Generator]]] = None ,_a : Optional[str] = "pil" ,_a : bool = True ,**_a : List[Any] ,): '''simple docstring''' _a : Any = self.unet.config.sample_size _a : Optional[int] = (batch_size, 3, img_size, img_size) _a : Dict = self.unet # sample x_0 ~ N(0, sigma_0^2 * I) _a : Dict = randn_tensor(_a ,generator=_a ,device=self.device ) * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(_a ) for t in self.progress_bar(self.scheduler.timesteps ): # here sigma_t == t_i from the paper _a : Optional[int] = self.scheduler.schedule[t] _a : List[str] = self.scheduler.schedule[t - 1] if t > 0 else 0 # 1. Select temporarily increased noise level sigma_hat # 2. Add new noise to move from sample_i to sample_hat _a, _a : List[Any] = self.scheduler.add_noise_to_input(_a ,_a ,generator=_a ) # 3. Predict the noise residual given the noise magnitude `sigma_hat` # The model inputs and output are adjusted by following eq. (213) in [1]. _a : Optional[int] = (sigma_hat / 2) * model((sample_hat + 1) / 2 ,sigma_hat / 2 ).sample # 4. Evaluate dx/dt at sigma_hat # 5. Take Euler step from sigma to sigma_prev _a : Tuple = self.scheduler.step(_a ,_a ,_a ,_a ) if sigma_prev != 0: # 6. Apply 2nd order correction # The model inputs and output are adjusted by following eq. (213) in [1]. _a : Optional[int] = (sigma_prev / 2) * model((step_output.prev_sample + 1) / 2 ,sigma_prev / 2 ).sample _a : Optional[Any] = self.scheduler.step_correct( _a ,_a ,_a ,_a ,step_output.prev_sample ,step_output['derivative'] ,) _a : Dict = step_output.prev_sample _a : Tuple = (sample / 2 + 0.5).clamp(0 ,1 ) _a : Optional[Any] = sample.cpu().permute(0 ,2 ,3 ,1 ).numpy() if output_type == "pil": _a : List[str] = self.numpy_to_pil(_a ) if not return_dict: return (image,) return ImagePipelineOutput(images=_a )
271
1
'''simple docstring''' def UpperCAmelCase_ (__a : list[int] ): """simple docstring""" if not numbers: return 0 if not isinstance(__a , (list, tuple) ) or not all( isinstance(__a , __a ) for number in numbers ): raise ValueError('numbers must be an iterable of integers' ) _a : Any = numbers[0] for i in range(1 , len(__a ) ): # update the maximum and minimum subarray products _a : str = numbers[i] if number < 0: _a, _a : List[Any] = min_till_now, max_till_now _a : Optional[int] = max(__a , max_till_now * number ) _a : Tuple = min(__a , min_till_now * number ) # update the maximum product found till now _a : Union[str, Any] = max(__a , __a ) return max_prod
271
'''simple docstring''' import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version from .. import __version__ from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging __lowerCAmelCase = ( """https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py""" ) __lowerCAmelCase = logging.get_logger(__name__) # pylint: disable=invalid-name def UpperCAmelCase_ (): """simple docstring""" _a : Optional[int] = 'https://pypi.org/pypi/diffusers/json' _a : int = json.loads(request.urlopen(__a ).read() )['releases'].keys() return sorted(__a , key=lambda __a : version.Version(__a ) ) def UpperCAmelCase_ (): """simple docstring""" if HF_MODULES_CACHE in sys.path: return sys.path.append(__a ) os.makedirs(__a , exist_ok=__a ) _a : str = Path(__a ) / '__init__.py' if not init_path.exists(): init_path.touch() def UpperCAmelCase_ (__a : Union[str, os.PathLike] ): """simple docstring""" init_hf_modules() _a : Dict = Path(__a ) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent ) os.makedirs(__a , exist_ok=__a ) _a : Optional[int] = dynamic_module_path / '__init__.py' if not init_path.exists(): init_path.touch() def UpperCAmelCase_ (__a : str ): """simple docstring""" with open(__a , 'r' , encoding='utf-8' ) as f: _a : int = f.read() # Imports of the form `import .xxx` _a : Tuple = re.findall('^\s*import\s+\.(\S+)\s*$' , __a , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall('^\s*from\s+\.(\S+)\s+import' , __a , flags=re.MULTILINE ) # Unique-ify return list(set(__a ) ) def UpperCAmelCase_ (__a : Any ): """simple docstring""" _a : Optional[int] = False _a : Optional[int] = [module_file] _a : List[str] = [] # Let's recurse through all relative imports while not no_change: _a : str = [] for f in files_to_check: new_imports.extend(get_relative_imports(__a ) ) _a : Union[str, Any] = Path(__a ).parent _a : str = [str(module_path / m ) for m in new_imports] _a : Tuple = [f for f in new_import_files if f not in all_relative_imports] _a : Dict = [f"""{f}.py""" for f in new_import_files] _a : List[str] = len(__a ) == 0 all_relative_imports.extend(__a ) return all_relative_imports def UpperCAmelCase_ (__a : Tuple ): """simple docstring""" with open(__a , 'r' , encoding='utf-8' ) as f: _a : Dict = f.read() # Imports of the form `import xxx` _a : Optional[int] = re.findall('^\s*import\s+(\S+)\s*$' , __a , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall('^\s*from\s+(\S+)\s+import' , __a , flags=re.MULTILINE ) # Only keep the top-level module _a : List[str] = [imp.split('.' )[0] for imp in imports if not imp.startswith('.' )] # Unique-ify and test we got them all _a : Optional[int] = list(set(__a ) ) _a : List[str] = [] for imp in imports: try: importlib.import_module(__a ) except ImportError: missing_packages.append(__a ) if len(__a ) > 0: raise ImportError( 'This modeling file requires the following packages that were not found in your environment: ' f"""{', '.join(__a )}. Run `pip install {' '.join(__a )}`""" ) return get_relative_imports(__a ) def UpperCAmelCase_ (__a : Any , __a : str ): """simple docstring""" _a : Any = module_path.replace(os.path.sep , '.' ) _a : Union[str, Any] = importlib.import_module(__a ) if class_name is None: return find_pipeline_class(__a ) return getattr(__a , __a ) def UpperCAmelCase_ (__a : Optional[int] ): """simple docstring""" from ..pipelines import DiffusionPipeline _a : List[str] = dict(inspect.getmembers(__a , inspect.isclass ) ) _a : str = None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , __a ) and cls.__module__.split('.' )[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( f"""Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:""" f""" {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in""" f""" {loaded_module}.""" ) _a : Any = cls return pipeline_class def UpperCAmelCase_ (__a : Union[str, os.PathLike] , __a : str , __a : Optional[Union[str, os.PathLike]] = None , __a : bool = False , __a : bool = False , __a : Optional[Dict[str, str]] = None , __a : Optional[Union[bool, str]] = None , __a : Optional[str] = None , __a : bool = False , ): """simple docstring""" _a : str = str(__a ) _a : Optional[Any] = os.path.join(__a , __a ) if os.path.isfile(__a ): _a : Tuple = module_file_or_url _a : Optional[Any] = 'local' elif pretrained_model_name_or_path.count('/' ) == 0: _a : int = get_diffusers_versions() # cut ".dev0" _a : Any = 'v' + '.'.join(__version__.split('.' )[:3] ) # retrieve github version that matches if revision is None: _a : Any = latest_version if latest_version[1:] in available_versions else 'main' logger.info(f"""Defaulting to latest_version: {revision}.""" ) elif revision in available_versions: _a : Any = f"""v{revision}""" elif revision == "main": _a : Optional[int] = revision else: raise ValueError( f"""`custom_revision`: {revision} does not exist. Please make sure to choose one of""" f""" {', '.join(available_versions + ['main'] )}.""" ) # community pipeline on GitHub _a : Tuple = COMMUNITY_PIPELINES_URL.format(revision=__a , pipeline=__a ) try: _a : Any = cached_download( __a , cache_dir=__a , force_download=__a , proxies=__a , resume_download=__a , local_files_only=__a , use_auth_token=__a , ) _a : List[Any] = 'git' _a : Any = pretrained_model_name_or_path + '.py' except EnvironmentError: logger.error(f"""Could not locate the {module_file} inside {pretrained_model_name_or_path}.""" ) raise else: try: # Load from URL or cache if already cached _a : Optional[Any] = hf_hub_download( __a , __a , cache_dir=__a , force_download=__a , proxies=__a , resume_download=__a , local_files_only=__a , use_auth_token=__a , ) _a : List[Any] = os.path.join('local' , '--'.join(pretrained_model_name_or_path.split('/' ) ) ) except EnvironmentError: logger.error(f"""Could not locate the {module_file} inside {pretrained_model_name_or_path}.""" ) raise # Check we have all the requirements in our environment _a : Optional[int] = check_imports(__a ) # Now we move the module inside our cached dynamic modules. _a : Optional[Any] = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(__a ) _a : Any = Path(__a ) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copy(__a , submodule_path / module_file ) for module_needed in modules_needed: _a : Dict = f"""{module_needed}.py""" shutil.copy(os.path.join(__a , __a ) , submodule_path / module_needed ) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. if isinstance(__a , __a ): _a : Optional[Any] = use_auth_token elif use_auth_token is True: _a : List[Any] = HfFolder.get_token() else: _a : Dict = None _a : int = model_info(__a , revision=__a , token=__a ).sha # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. _a : Optional[int] = submodule_path / commit_hash _a : str = full_submodule + os.path.sep + commit_hash create_dynamic_module(__a ) if not (submodule_path / module_file).exists(): shutil.copy(__a , submodule_path / module_file ) # Make sure we also have every file with relative for module_needed in modules_needed: if not (submodule_path / module_needed).exists(): get_cached_module_file( __a , f"""{module_needed}.py""" , cache_dir=__a , force_download=__a , resume_download=__a , proxies=__a , use_auth_token=__a , revision=__a , local_files_only=__a , ) return os.path.join(__a , __a ) def UpperCAmelCase_ (__a : Union[str, os.PathLike] , __a : str , __a : Optional[str] = None , __a : Optional[Union[str, os.PathLike]] = None , __a : bool = False , __a : bool = False , __a : Optional[Dict[str, str]] = None , __a : Optional[Union[bool, str]] = None , __a : Optional[str] = None , __a : bool = False , **__a : str , ): """simple docstring""" _a : Dict = get_cached_module_file( __a , __a , cache_dir=__a , force_download=__a , resume_download=__a , proxies=__a , use_auth_token=__a , revision=__a , local_files_only=__a , ) return get_class_in_module(__a , final_module.replace('.py' , '' ) )
271
1
'''simple docstring''' import numpy as np from transformers import BatchFeature from transformers.testing_utils import require_tf, require_torch from .test_feature_extraction_common import FeatureExtractionSavingTestMixin class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = None __UpperCAmelCase : List[Any] = None @property def __lowercase ( self : Dict ): '''simple docstring''' return self.feat_extract_tester.prepare_feat_extract_dict() def __lowercase ( self : str ): '''simple docstring''' _a : Dict = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(_a ,'feature_size' ) ) self.assertTrue(hasattr(_a ,'sampling_rate' ) ) self.assertTrue(hasattr(_a ,'padding_value' ) ) def __lowercase ( self : int ): '''simple docstring''' _a : Any = self.feat_extract_tester.prepare_inputs_for_common() _a : str = self.feature_extraction_class(**self.feat_extract_dict ) _a : int = feat_extract.model_input_names[0] _a : List[Any] = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(_a ) == len(_a ) for x, y in zip(_a ,processed_features[input_name] ) ) ) _a : Any = self.feat_extract_tester.prepare_inputs_for_common(equal_length=_a ) _a : Union[str, Any] = BatchFeature({input_name: speech_inputs} ,tensor_type='np' ) _a : Union[str, Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: _a : Optional[int] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_torch def __lowercase ( self : Any ): '''simple docstring''' _a : List[Any] = self.feat_extract_tester.prepare_inputs_for_common(equal_length=_a ) _a : Dict = self.feature_extraction_class(**self.feat_extract_dict ) _a : int = feat_extract.model_input_names[0] _a : str = BatchFeature({input_name: speech_inputs} ,tensor_type='pt' ) _a : str = processed_features[input_name] if len(batch_features_input.shape ) < 3: _a : str = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_tf def __lowercase ( self : int ): '''simple docstring''' _a : int = self.feat_extract_tester.prepare_inputs_for_common(equal_length=_a ) _a : Dict = self.feature_extraction_class(**self.feat_extract_dict ) _a : Tuple = feat_extract.model_input_names[0] _a : int = BatchFeature({input_name: speech_inputs} ,tensor_type='tf' ) _a : Optional[int] = processed_features[input_name] if len(batch_features_input.shape ) < 3: _a : Optional[Any] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) def __lowercase ( self : Dict ,_a : Any=False ): '''simple docstring''' def _inputs_have_equal_length(_a : Tuple ): _a : Tuple = len(input[0] ) for input_slice in input[1:]: if len(_a ) != length: return False return True def _inputs_are_equal(_a : Optional[Any] ,_a : Union[str, Any] ): if len(_a ) != len(_a ): return False for input_slice_a, input_slice_a in zip(_a ,_a ): if not np.allclose(np.asarray(_a ) ,np.asarray(_a ) ,atol=1E-3 ): return False return True _a : int = self.feature_extraction_class(**self.feat_extract_dict ) _a : Tuple = self.feat_extract_tester.prepare_inputs_for_common(numpify=_a ) _a : Union[str, Any] = feat_extract.model_input_names[0] _a : Tuple = BatchFeature({input_name: speech_inputs} ) _a : str = self.feat_extract_tester.seq_length_diff _a : Dict = self.feat_extract_tester.max_seq_length + pad_diff _a : Dict = self.feat_extract_tester.min_seq_length _a : Optional[Any] = self.feat_extract_tester.batch_size _a : Tuple = self.feat_extract_tester.feature_size # test padding for List[int] + numpy _a : int = feat_extract.pad(_a ,padding=_a ) _a : List[Any] = input_a[input_name] _a : Tuple = feat_extract.pad(_a ,padding='longest' ) _a : Any = input_a[input_name] _a : Optional[Any] = feat_extract.pad(_a ,padding='max_length' ,max_length=len(speech_inputs[-1] ) ) _a : List[str] = input_a[input_name] _a : List[str] = feat_extract.pad(_a ,padding='longest' ,return_tensors='np' ) _a : str = input_a[input_name] # max_length parameter has to be provided when setting `padding="max_length"` with self.assertRaises(_a ): feat_extract.pad(_a ,padding='max_length' )[input_name] _a : int = feat_extract.pad( _a ,padding='max_length' ,max_length=_a ,return_tensors='np' ) _a : Optional[int] = input_a[input_name] self.assertFalse(_inputs_have_equal_length(_a ) ) self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertTrue(_inputs_are_equal(_a ,_a ) ) self.assertTrue(len(input_a[0] ) == pad_min_length ) self.assertTrue(len(input_a[1] ) == pad_min_length + pad_diff ) self.assertTrue(input_a.shape[:2] == (batch_size, len(input_a[0] )) ) self.assertTrue(input_a.shape[:2] == (batch_size, pad_max_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == input_a.shape[2] == feature_size ) # test padding for `pad_to_multiple_of` for List[int] + numpy _a : Tuple = feat_extract.pad(_a ,pad_to_multiple_of=10 ) _a : List[str] = input_a[input_name] _a : str = feat_extract.pad(_a ,padding='longest' ,pad_to_multiple_of=10 ) _a : Tuple = input_a[input_name] _a : Optional[int] = feat_extract.pad( _a ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=_a ) _a : Any = input_a[input_name] _a : Optional[int] = feat_extract.pad( _a ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=_a ,return_tensors='np' ,) _a : Dict = input_a[input_name] self.assertTrue(all(len(_a ) % 10 == 0 for x in input_a ) ) self.assertTrue(_inputs_are_equal(_a ,_a ) ) _a : List[str] = pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10 self.assertTrue(all(len(_a ) == expected_mult_pad_length for x in input_a ) ) self.assertEqual(input_a.shape[:2] ,(batch_size, expected_mult_pad_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == feature_size ) # Check padding value is correct _a : Any = (np.ones(self.feat_extract_tester.feature_size ) * feat_extract.padding_value).sum() self.assertTrue( abs(np.asarray(input_a[0] )[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1E-3 ) self.assertTrue( abs( np.asarray(input_a[1] )[pad_min_length + pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff) ) < 1E-3 ) self.assertTrue( abs( np.asarray(input_a[2] )[pad_min_length + 2 * pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff) ) < 1E-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1E-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length) ) < 1E-3 ) def __lowercase ( self : List[Any] ,_a : Optional[int]=False ): '''simple docstring''' def _inputs_have_equal_length(_a : List[str] ): _a : Union[str, Any] = len(input[0] ) for input_slice in input[1:]: if len(_a ) != length: return False return True def _inputs_are_equal(_a : List[str] ,_a : List[str] ): if len(_a ) != len(_a ): return False for input_slice_a, input_slice_a in zip(_a ,_a ): if not np.allclose(np.asarray(_a ) ,np.asarray(_a ) ,atol=1E-3 ): return False return True _a : Dict = self.feature_extraction_class(**self.feat_extract_dict ) _a : str = self.feat_extract_tester.prepare_inputs_for_common(numpify=_a ) _a : Any = feat_extract.model_input_names[0] _a : List[Any] = BatchFeature({input_name: speech_inputs} ) # truncate to smallest _a : Union[str, Any] = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,truncation=_a ) _a : str = input_a[input_name] _a : List[str] = feat_extract.pad(_a ,padding='max_length' ,max_length=len(speech_inputs[0] ) ) _a : Tuple = input_a[input_name] self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertFalse(_inputs_have_equal_length(_a ) ) # truncate to smallest with np _a : Dict = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ,truncation=_a ,) _a : Any = input_a[input_name] _a : List[Any] = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ) _a : int = input_a[input_name] self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertTrue(input_a.shape[1] == len(speech_inputs[0] ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(_a ) ) # truncate to middle _a : Dict = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=_a ,return_tensors='np' ,) _a : List[Any] = input_a[input_name] _a : Tuple = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=_a ) _a : Tuple = input_a[input_name] _a : Tuple = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,return_tensors='np' ) _a : Dict = input_a[input_name] self.assertTrue(input_a.shape[1] == len(speech_inputs[1] ) ) self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertTrue(_inputs_are_equal(_a ,_a ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(_a ) ) self.assertTrue(len(input_a[-1] ) == len(speech_inputs[-1] ) ) # padding has to be max_length when setting `truncation=True` with self.assertRaises(_a ): feat_extract.pad(_a ,truncation=_a )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(_a ): feat_extract.pad(_a ,padding='longest' ,truncation=_a )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(_a ): feat_extract.pad(_a ,padding='longest' ,truncation=_a )[input_name] # max_length parameter has to be provided when setting `truncation=True` and padding="max_length" with self.assertRaises(_a ): feat_extract.pad(_a ,padding='max_length' ,truncation=_a )[input_name] # test truncation for `pad_to_multiple_of` for List[int] + numpy _a : Optional[Any] = 12 _a : List[Any] = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=_a ,truncation=_a ,) _a : Tuple = input_a[input_name] _a : str = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=_a ,) _a : List[Any] = input_a[input_name] # retrieve expected_length as multiple of pad_to_multiple_of _a : List[Any] = len(speech_inputs[0] ) if expected_length % pad_to_multiple_of != 0: _a : Union[str, Any] = ((len(speech_inputs[0] ) // pad_to_multiple_of) + 1) * pad_to_multiple_of self.assertTrue(len(input_a[0] ) == expected_length ) self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertFalse(_inputs_have_equal_length(_a ) ) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' self._check_padding(numpify=_a ) def __lowercase ( self : Tuple ): '''simple docstring''' self._check_padding(numpify=_a ) def __lowercase ( self : Dict ): '''simple docstring''' self._check_truncation(numpify=_a ) def __lowercase ( self : str ): '''simple docstring''' self._check_truncation(numpify=_a ) @require_torch def __lowercase ( self : Dict ): '''simple docstring''' _a : Any = self.feature_extraction_class(**self.feat_extract_dict ) _a : List[Any] = self.feat_extract_tester.prepare_inputs_for_common() _a : Union[str, Any] = feat_extract.model_input_names[0] _a : Optional[int] = BatchFeature({input_name: speech_inputs} ) _a : List[Any] = feat_extract.pad(_a ,padding='longest' ,return_tensors='np' )[input_name] _a : List[str] = feat_extract.pad(_a ,padding='longest' ,return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1E-2 ) @require_tf def __lowercase ( self : int ): '''simple docstring''' _a : List[str] = self.feature_extraction_class(**self.feat_extract_dict ) _a : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_common() _a : Dict = feat_extract.model_input_names[0] _a : Optional[Any] = BatchFeature({input_name: speech_inputs} ) _a : Dict = feat_extract.pad(_a ,padding='longest' ,return_tensors='np' )[input_name] _a : Any = feat_extract.pad(_a ,padding='longest' ,return_tensors='tf' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_tf.numpy().astype(np.floataa ).sum() ) < 1E-2 ) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : str = self.feat_extract_dict _a : List[Any] = True _a : Optional[int] = self.feature_extraction_class(**_a ) _a : List[Any] = self.feat_extract_tester.prepare_inputs_for_common() _a : Tuple = [len(_a ) for x in speech_inputs] _a : int = feat_extract.model_input_names[0] _a : Optional[Any] = BatchFeature({input_name: speech_inputs} ) _a : str = feat_extract.pad(_a ,padding='longest' ,return_tensors='np' ) self.assertIn('attention_mask' ,_a ) self.assertListEqual(list(processed.attention_mask.shape ) ,list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() ,_a ) def __lowercase ( self : int ): '''simple docstring''' _a : Any = self.feat_extract_dict _a : Tuple = True _a : Optional[int] = self.feature_extraction_class(**_a ) _a : Dict = self.feat_extract_tester.prepare_inputs_for_common() _a : Dict = [len(_a ) for x in speech_inputs] _a : Union[str, Any] = feat_extract.model_input_names[0] _a : Any = BatchFeature({input_name: speech_inputs} ) _a : List[Any] = min(_a ) _a : Dict = feat_extract.pad( _a ,padding='max_length' ,max_length=_a ,truncation=_a ,return_tensors='np' ) self.assertIn('attention_mask' ,_a ) self.assertListEqual( list(processed_pad.attention_mask.shape ) ,[processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() ,[max_length for x in speech_inputs] )
271
'''simple docstring''' def UpperCAmelCase_ (__a : list , __a : list , __a : int ): """simple docstring""" _a : Optional[Any] = len(__a ) _a : int = [[0] * n for i in range(__a )] for i in range(__a ): _a : Tuple = y_points[i] for i in range(2 , __a ): for j in range(__a , __a ): _a : Tuple = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
271
1
'''simple docstring''' from __future__ import annotations def UpperCAmelCase_ (__a : list[int] ): """simple docstring""" _a : Optional[Any] = len(__a ) // 2 # choose the middle 3 elements _a : Optional[int] = lst[m - 1 : m + 2] # if middle element is peak if three[1] > three[0] and three[1] > three[2]: return three[1] # if increasing, recurse on right elif three[0] < three[2]: if len(lst[:m] ) == 2: m -= 1 return peak(lst[m:] ) # decreasing else: if len(lst[:m] ) == 2: m += 1 return peak(lst[:m] ) if __name__ == "__main__": import doctest doctest.testmod()
271
'''simple docstring''' import inspect import os import unittest from pathlib import Path import torch import accelerate from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils.testing import run_command class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Optional[Any] = inspect.getfile(accelerate.test_utils ) __UpperCAmelCase : List[str] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_cli.py'''] ) __UpperCAmelCase : Dict = ['''accelerate''', '''launch'''] __UpperCAmelCase : Dict = Path.home() / '''.cache/huggingface/accelerate''' __UpperCAmelCase : Dict = '''default_config.yaml''' __UpperCAmelCase : Optional[Any] = config_folder / config_file __UpperCAmelCase : Dict = config_folder / '''_default_config.yaml''' __UpperCAmelCase : Any = Path('''tests/test_configs''' ) @classmethod def __lowercase ( cls : int ): '''simple docstring''' if cls.config_path.is_file(): cls.config_path.rename(cls.changed_path ) @classmethod def __lowercase ( cls : List[Any] ): '''simple docstring''' if cls.changed_path.is_file(): cls.changed_path.rename(cls.config_path ) def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : Dict = self.base_cmd if torch.cuda.is_available() and (torch.cuda.device_count() > 1): cmd += ["--multi_gpu"] execute_subprocess_async(cmd + [self.test_file_path] ,env=os.environ.copy() ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' for config in sorted(self.test_config_path.glob('**/*.yaml' ) ): with self.subTest(config_file=_a ): execute_subprocess_async( self.base_cmd + ['--config_file', str(_a ), self.test_file_path] ,env=os.environ.copy() ) def __lowercase ( self : Optional[int] ): '''simple docstring''' execute_subprocess_async(['accelerate', 'test'] ,env=os.environ.copy() ) class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Optional[Any] = '''test-tpu''' __UpperCAmelCase : Any = '''us-central1-a''' __UpperCAmelCase : List[Any] = '''ls''' __UpperCAmelCase : Any = ['''accelerate''', '''tpu-config'''] __UpperCAmelCase : Dict = '''cd /usr/share''' __UpperCAmelCase : Any = '''tests/test_samples/test_command_file.sh''' __UpperCAmelCase : List[Any] = '''Running gcloud compute tpus tpu-vm ssh''' def __lowercase ( self : Dict ): '''simple docstring''' _a : Optional[Any] = run_command( self.cmd + ['--command', self.command, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug'] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" ,_a ,) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Any = run_command( self.cmd + [ '--config_file', 'tests/test_configs/0_12_0.yaml', '--command', self.command, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug', ] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" ,_a ,) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Optional[int] = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--debug'] ,return_stdout=_a ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_a ,) def __lowercase ( self : int ): '''simple docstring''' _a : Optional[Any] = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--command', self.command, '--debug'] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" ,_a ,) def __lowercase ( self : str ): '''simple docstring''' _a : List[str] = run_command( self.cmd + [ '--config_file', 'tests/test_configs/latest.yaml', '--command', self.command, '--command', 'echo "Hello World"', '--debug', ] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo \"Hello World\" --worker all""" ,_a ,) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : Any = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--command_file', self.command_file, '--debug'] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_a ,) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : Union[str, Any] = run_command( self.cmd + [ '--config_file', 'tests/test_configs/0_12_0.yaml', '--command_file', self.command_file, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug', ] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_a ,) def __lowercase ( self : Any ): '''simple docstring''' _a : Optional[int] = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--install_accelerate', '--debug'] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_a ,) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Optional[int] = run_command( self.cmd + [ '--config_file', 'tests/test_configs/latest.yaml', '--install_accelerate', '--accelerate_version', '12.0.0', '--debug', ] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_a ,)
271
1
'''simple docstring''' import warnings from ...utils import logging from .image_processing_perceiver import PerceiverImageProcessor __lowerCAmelCase = logging.get_logger(__name__) class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" def __init__( self : Any ,*_a : List[Any] ,**_a : Any ): '''simple docstring''' warnings.warn( 'The class PerceiverFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use PerceiverImageProcessor instead.' ,_a ,) super().__init__(*_a ,**_a )
271
'''simple docstring''' from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar __lowerCAmelCase = TypeVar("""T""") class UpperCAmelCase__ ( Generic[T] ): """simple docstring""" def __init__( self : Tuple ,_a : T ): '''simple docstring''' _a : List[str] = data _a : Node[T] | None = None def __str__( self : Dict ): '''simple docstring''' return F"""{self.data}""" class UpperCAmelCase__ ( Generic[T] ): """simple docstring""" def __init__( self : Optional[int] ): '''simple docstring''' _a : Node[T] | None = None def __iter__( self : str ): '''simple docstring''' _a : Tuple = self.top while node: yield node.data _a : int = node.next def __str__( self : str ): '''simple docstring''' return "->".join([str(_a ) for item in self] ) def __len__( self : Optional[Any] ): '''simple docstring''' return len(tuple(iter(self ) ) ) def __lowercase ( self : str ): '''simple docstring''' return self.top is None def __lowercase ( self : List[Any] ,_a : T ): '''simple docstring''' _a : int = Node(_a ) if not self.is_empty(): _a : Optional[Any] = self.top _a : List[str] = node def __lowercase ( self : Tuple ): '''simple docstring''' if self.is_empty(): raise IndexError('pop from empty stack' ) assert isinstance(self.top ,_a ) _a : List[Any] = self.top _a : int = self.top.next return pop_node.data def __lowercase ( self : List[str] ): '''simple docstring''' if self.is_empty(): raise IndexError('peek from empty stack' ) assert self.top is not None return self.top.data def __lowercase ( self : List[str] ): '''simple docstring''' _a : Optional[int] = None if __name__ == "__main__": from doctest import testmod testmod()
271
1
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TextClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. __lowerCAmelCase = {"""LayoutLMv2Config""", """LayoutLMv3Config"""} @is_pipeline_test class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase : str = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING __UpperCAmelCase : int = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: __UpperCAmelCase : List[str] = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: __UpperCAmelCase : List[str] = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } @require_torch def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : Any = pipeline( task='text-classification' ,model='hf-internal-testing/tiny-random-distilbert' ,framework='pt' ) _a : List[Any] = text_classifier('This is great !' ) self.assertEqual(nested_simplify(_a ) ,[{'label': 'LABEL_0', 'score': 0.504}] ) _a : Union[str, Any] = text_classifier('This is great !' ,top_k=2 ) self.assertEqual( nested_simplify(_a ) ,[{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}] ) _a : Dict = text_classifier(['This is great !', 'This is bad'] ,top_k=2 ) self.assertEqual( nested_simplify(_a ) ,[ [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}], [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}], ] ,) _a : str = text_classifier('This is great !' ,top_k=1 ) self.assertEqual(nested_simplify(_a ) ,[{'label': 'LABEL_0', 'score': 0.504}] ) # Legacy behavior _a : List[str] = text_classifier('This is great !' ,return_all_scores=_a ) self.assertEqual(nested_simplify(_a ) ,[{'label': 'LABEL_0', 'score': 0.504}] ) _a : Optional[Any] = text_classifier('This is great !' ,return_all_scores=_a ) self.assertEqual( nested_simplify(_a ) ,[[{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}]] ) _a : Union[str, Any] = text_classifier(['This is great !', 'Something else'] ,return_all_scores=_a ) self.assertEqual( nested_simplify(_a ) ,[ [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}], [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}], ] ,) _a : Optional[int] = text_classifier(['This is great !', 'Something else'] ,return_all_scores=_a ) self.assertEqual( nested_simplify(_a ) ,[ {'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_0', 'score': 0.504}, ] ,) @require_torch def __lowercase ( self : str ): '''simple docstring''' import torch _a : Tuple = pipeline( task='text-classification' ,model='hf-internal-testing/tiny-random-distilbert' ,framework='pt' ,device=torch.device('cpu' ) ,) _a : List[str] = text_classifier('This is great !' ) self.assertEqual(nested_simplify(_a ) ,[{'label': 'LABEL_0', 'score': 0.504}] ) @require_tf def __lowercase ( self : List[Any] ): '''simple docstring''' _a : int = pipeline( task='text-classification' ,model='hf-internal-testing/tiny-random-distilbert' ,framework='tf' ) _a : List[str] = text_classifier('This is great !' ) self.assertEqual(nested_simplify(_a ) ,[{'label': 'LABEL_0', 'score': 0.504}] ) @slow @require_torch def __lowercase ( self : str ): '''simple docstring''' _a : Tuple = pipeline('text-classification' ) _a : List[str] = text_classifier('This is great !' ) self.assertEqual(nested_simplify(_a ) ,[{'label': 'POSITIVE', 'score': 1.0}] ) _a : List[str] = text_classifier('This is bad !' ) self.assertEqual(nested_simplify(_a ) ,[{'label': 'NEGATIVE', 'score': 1.0}] ) _a : List[Any] = text_classifier('Birds are a type of animal' ) self.assertEqual(nested_simplify(_a ) ,[{'label': 'POSITIVE', 'score': 0.988}] ) @slow @require_tf def __lowercase ( self : Tuple ): '''simple docstring''' _a : Tuple = pipeline('text-classification' ,framework='tf' ) _a : Optional[int] = text_classifier('This is great !' ) self.assertEqual(nested_simplify(_a ) ,[{'label': 'POSITIVE', 'score': 1.0}] ) _a : Optional[int] = text_classifier('This is bad !' ) self.assertEqual(nested_simplify(_a ) ,[{'label': 'NEGATIVE', 'score': 1.0}] ) _a : Tuple = text_classifier('Birds are a type of animal' ) self.assertEqual(nested_simplify(_a ) ,[{'label': 'POSITIVE', 'score': 0.988}] ) def __lowercase ( self : str ,_a : int ,_a : Optional[Any] ,_a : int ): '''simple docstring''' _a : List[str] = TextClassificationPipeline(model=_a ,tokenizer=_a ) return text_classifier, ["HuggingFace is in", "This is another test"] def __lowercase ( self : Tuple ,_a : Dict ,_a : Optional[Any] ): '''simple docstring''' _a : Any = text_classifier.model # Small inputs because BartTokenizer tiny has maximum position embeddings = 22 _a : str = 'HuggingFace is in' _a : Union[str, Any] = text_classifier(_a ) self.assertEqual(nested_simplify(_a ) ,[{'label': ANY(_a ), 'score': ANY(_a )}] ) self.assertTrue(outputs[0]['label'] in model.config.idalabel.values() ) _a : Tuple = ['HuggingFace is in ', 'Paris is in France'] _a : str = text_classifier(_a ) self.assertEqual( nested_simplify(_a ) ,[{'label': ANY(_a ), 'score': ANY(_a )}, {'label': ANY(_a ), 'score': ANY(_a )}] ,) self.assertTrue(outputs[0]['label'] in model.config.idalabel.values() ) self.assertTrue(outputs[1]['label'] in model.config.idalabel.values() ) # Forcing to get all results with `top_k=None` # This is NOT the legacy format _a : Union[str, Any] = text_classifier(_a ,top_k=_a ) _a : Optional[int] = len(model.config.idalabel.values() ) self.assertEqual( nested_simplify(_a ) ,[[{'label': ANY(_a ), 'score': ANY(_a )}] * N, [{'label': ANY(_a ), 'score': ANY(_a )}] * N] ,) _a : Union[str, Any] = {'text': 'HuggingFace is in ', 'text_pair': 'Paris is in France'} _a : Union[str, Any] = text_classifier(_a ) self.assertEqual( nested_simplify(_a ) ,{'label': ANY(_a ), 'score': ANY(_a )} ,) self.assertTrue(outputs['label'] in model.config.idalabel.values() ) # This might be used a text pair, but tokenizer + pipe interaction # makes it hard to understand that it's not using the pair properly # https://github.com/huggingface/transformers/issues/17305 # We disabled this usage instead as it was outputting wrong outputs. _a : Dict = [['HuggingFace is in ', 'Paris is in France']] with self.assertRaises(_a ): text_classifier(_a ) # This used to be valid for doing text pairs # We're keeping it working because of backward compatibility _a : Optional[Any] = text_classifier([[['HuggingFace is in ', 'Paris is in France']]] ) self.assertEqual( nested_simplify(_a ) ,[{'label': ANY(_a ), 'score': ANY(_a )}] ,) self.assertTrue(outputs[0]['label'] in model.config.idalabel.values() )
271
'''simple docstring''' import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" @property def __lowercase ( self : List[str] ): '''simple docstring''' torch.manual_seed(0 ) _a : int = UNetaDModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=3 ,out_channels=3 ,down_block_types=('DownBlock2D', 'AttnDownBlock2D') ,up_block_types=('AttnUpBlock2D', 'UpBlock2D') ,) return model def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a : str = self.dummy_uncond_unet _a : int = PNDMScheduler() _a : str = PNDMPipeline(unet=_a ,scheduler=_a ) pndm.to(_a ) pndm.set_progress_bar_config(disable=_a ) _a : Optional[int] = torch.manual_seed(0 ) _a : Optional[Any] = pndm(generator=_a ,num_inference_steps=20 ,output_type='numpy' ).images _a : List[str] = torch.manual_seed(0 ) _a : Any = pndm(generator=_a ,num_inference_steps=20 ,output_type='numpy' ,return_dict=_a )[0] _a : List[Any] = image[0, -3:, -3:, -1] _a : Any = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _a : List[Any] = np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self : Tuple ): '''simple docstring''' _a : List[str] = 'google/ddpm-cifar10-32' _a : str = UNetaDModel.from_pretrained(_a ) _a : Union[str, Any] = PNDMScheduler() _a : Tuple = PNDMPipeline(unet=_a ,scheduler=_a ) pndm.to(_a ) pndm.set_progress_bar_config(disable=_a ) _a : str = torch.manual_seed(0 ) _a : Optional[Any] = pndm(generator=_a ,output_type='numpy' ).images _a : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _a : Tuple = np.array([0.1564, 0.1_4645, 0.1406, 0.1_4715, 0.1_2425, 0.1_4045, 0.1_3115, 0.1_2175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
271
1
'''simple docstring''' import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from ...models.controlnet import ControlNetModel, ControlNetOutput from ...models.modeling_utils import ModelMixin from ...utils import logging __lowerCAmelCase = logging.get_logger(__name__) class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" def __init__( self : Optional[Any] ,_a : Union[List[ControlNetModel], Tuple[ControlNetModel]] ): '''simple docstring''' super().__init__() _a : Union[str, Any] = nn.ModuleList(_a ) def __lowercase ( self : Any ,_a : torch.FloatTensor ,_a : Union[torch.Tensor, float, int] ,_a : torch.Tensor ,_a : List[torch.tensor] ,_a : List[float] ,_a : Optional[torch.Tensor] = None ,_a : Optional[torch.Tensor] = None ,_a : Optional[torch.Tensor] = None ,_a : Optional[Dict[str, Any]] = None ,_a : bool = False ,_a : bool = True ,): '''simple docstring''' for i, (image, scale, controlnet) in enumerate(zip(_a ,_a ,self.nets ) ): _a, _a : int = controlnet( _a ,_a ,_a ,_a ,_a ,_a ,_a ,_a ,_a ,_a ,_a ,) # merge samples if i == 0: _a, _a : List[str] = down_samples, mid_sample else: _a : str = [ samples_prev + samples_curr for samples_prev, samples_curr in zip(_a ,_a ) ] mid_block_res_sample += mid_sample return down_block_res_samples, mid_block_res_sample def __lowercase ( self : int ,_a : Union[str, os.PathLike] ,_a : bool = True ,_a : Callable = None ,_a : bool = False ,_a : Optional[str] = None ,): '''simple docstring''' _a : Dict = 0 _a : int = save_directory for controlnet in self.nets: controlnet.save_pretrained( _a ,is_main_process=_a ,save_function=_a ,safe_serialization=_a ,variant=_a ,) idx += 1 _a : Optional[Any] = model_path_to_save + F"""_{idx}""" @classmethod def __lowercase ( cls : str ,_a : Optional[Union[str, os.PathLike]] ,**_a : List[str] ): '''simple docstring''' _a : Union[str, Any] = 0 _a : str = [] # load controlnet and append to list until no controlnet directory exists anymore # first controlnet has to be saved under `./mydirectory/controlnet` to be compliant with `DiffusionPipeline.from_prertained` # second, third, ... controlnets have to be saved under `./mydirectory/controlnet_1`, `./mydirectory/controlnet_2`, ... _a : Optional[Any] = pretrained_model_path while os.path.isdir(_a ): _a : str = ControlNetModel.from_pretrained(_a ,**_a ) controlnets.append(_a ) idx += 1 _a : Optional[int] = pretrained_model_path + F"""_{idx}""" logger.info(F"""{len(_a )} controlnets loaded from {pretrained_model_path}.""" ) if len(_a ) == 0: raise ValueError( F"""No ControlNets found under {os.path.dirname(_a )}. Expected at least {pretrained_model_path + '_0'}.""" ) return cls(_a )
271
'''simple docstring''' import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow __lowerCAmelCase = logging.getLogger() @unittest.skip('''Temporarily disable the doc tests.''' ) @require_torch @require_tf @slow class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self : str ,_a : Path ,_a : Union[str, None] = None ,_a : Union[List[str], None] = None ,_a : Union[str, List[str], None] = None ,_a : bool = True ,): '''simple docstring''' _a : Optional[int] = [file for file in os.listdir(_a ) if os.path.isfile(os.path.join(_a ,_a ) )] if identifier is not None: _a : List[str] = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(_a ,_a ): for n_ in n_identifier: _a : Tuple = [file for file in files if n_ not in file] else: _a : Optional[Any] = [file for file in files if n_identifier not in file] _a : List[str] = ignore_files or [] ignore_files.append('__init__.py' ) _a : Tuple = [file for file in files if file not in ignore_files] for file in files: # Open all files print('Testing' ,_a ) if only_modules: _a : Any = file.split('.' )[0] try: _a : List[str] = getattr(_a ,_a ) _a : int = doctest.DocTestSuite(_a ) _a : Any = unittest.TextTestRunner().run(_a ) self.assertIs(len(result.failures ) ,0 ) except AttributeError: logger.info(F"""{module_identifier} is not a module.""" ) else: _a : Union[str, Any] = doctest.testfile(str('..' / directory / file ) ,optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed ,0 ) def __lowercase ( self : Any ): '''simple docstring''' _a : int = Path('src/transformers' ) _a : List[Any] = 'modeling' _a : Optional[Any] = [ 'modeling_ctrl.py', 'modeling_tf_ctrl.py', ] self.analyze_directory(_a ,identifier=_a ,ignore_files=_a ) def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : Optional[Any] = Path('src/transformers' ) _a : Optional[Any] = 'tokenization' self.analyze_directory(_a ,identifier=_a ) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Dict = Path('src/transformers' ) _a : str = 'configuration' self.analyze_directory(_a ,identifier=_a ) def __lowercase ( self : Any ): '''simple docstring''' _a : Tuple = Path('src/transformers' ) _a : List[Any] = ['configuration', 'modeling', 'tokenization'] self.analyze_directory(_a ,n_identifier=_a ) def __lowercase ( self : Tuple ): '''simple docstring''' _a : List[Any] = Path('docs/source' ) _a : List[str] = ['favicon.ico'] self.analyze_directory(_a ,ignore_files=_a ,only_modules=_a )
271
1
'''simple docstring''' import math from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = { """facebook/data2vec-base-960h""": """https://huggingface.co/facebook/data2vec-audio-base-960h/resolve/main/config.json""", # See all Data2VecAudio models at https://huggingface.co/models?filter=data2vec-audio } class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : Tuple = '''data2vec-audio''' def __init__( self : int ,_a : int=32 ,_a : str=768 ,_a : List[str]=12 ,_a : List[str]=12 ,_a : Dict=3072 ,_a : str="gelu" ,_a : List[str]=0.1 ,_a : Union[str, Any]=0.1 ,_a : Dict=0.1 ,_a : Optional[int]=0.0 ,_a : Optional[Any]=0.1 ,_a : Optional[Any]=0.1 ,_a : int=0.02 ,_a : Union[str, Any]=1E-5 ,_a : str="gelu" ,_a : List[str]=(512, 512, 512, 512, 512, 512, 512) ,_a : int=(5, 2, 2, 2, 2, 2, 2) ,_a : Optional[Any]=(10, 3, 3, 3, 3, 2, 2) ,_a : List[Any]=False ,_a : str=16 ,_a : Optional[Any]=19 ,_a : str=5 ,_a : Dict=0.05 ,_a : Optional[Any]=10 ,_a : Union[str, Any]=2 ,_a : str=0.0 ,_a : str=10 ,_a : List[str]=0 ,_a : str="sum" ,_a : Union[str, Any]=False ,_a : Tuple=False ,_a : Any=256 ,_a : Tuple=(512, 512, 512, 512, 1500) ,_a : Tuple=(5, 3, 3, 1, 1) ,_a : int=(1, 2, 3, 1, 1) ,_a : Optional[int]=512 ,_a : Optional[int]=0 ,_a : List[Any]=1 ,_a : Tuple=2 ,_a : int=False ,_a : int=3 ,_a : Optional[Any]=2 ,_a : str=3 ,_a : Union[str, Any]=None ,**_a : int ,): '''simple docstring''' super().__init__(**_a ,pad_token_id=_a ,bos_token_id=_a ,eos_token_id=_a ) _a : str = hidden_size _a : Dict = feat_extract_activation _a : str = list(_a ) _a : Any = list(_a ) _a : Any = list(_a ) _a : Union[str, Any] = conv_bias _a : List[str] = num_conv_pos_embeddings _a : Any = num_conv_pos_embedding_groups _a : Dict = conv_pos_kernel_size _a : Optional[Any] = len(self.conv_dim ) _a : Optional[int] = num_hidden_layers _a : Union[str, Any] = intermediate_size _a : Union[str, Any] = hidden_act _a : Dict = num_attention_heads _a : List[Any] = hidden_dropout _a : Optional[int] = attention_dropout _a : Optional[Any] = activation_dropout _a : Any = feat_proj_dropout _a : List[str] = final_dropout _a : List[Any] = layerdrop _a : List[str] = layer_norm_eps _a : Any = initializer_range _a : List[str] = vocab_size _a : Dict = use_weighted_layer_sum if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==' ' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =' F""" {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,""" F""" `len(config.conv_kernel) = {len(self.conv_kernel )}`.""" ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 _a : Any = mask_time_prob _a : Any = mask_time_length _a : Optional[int] = mask_time_min_masks _a : List[Any] = mask_feature_prob _a : Optional[Any] = mask_feature_length _a : Union[str, Any] = mask_feature_min_masks # ctc loss _a : List[str] = ctc_loss_reduction _a : Any = ctc_zero_infinity # adapter _a : Union[str, Any] = add_adapter _a : int = adapter_kernel_size _a : Any = adapter_stride _a : Optional[int] = num_adapter_layers _a : Optional[Any] = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. _a : Dict = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. _a : Optional[int] = list(_a ) _a : Dict = list(_a ) _a : Optional[Any] = list(_a ) _a : Any = xvector_output_dim @property def __lowercase ( self : Union[str, Any] ): '''simple docstring''' return math.prod(self.conv_stride )
271
'''simple docstring''' import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def UpperCAmelCase_ (__a : Optional[Any] , __a : str , __a : Optional[Any]=None ): """simple docstring""" assert torch_layer.weight.shape == weight.shape, f"""{torch_layer} layer.weight does not match""" _a : str = nn.Parameter(__a ) if bias is not None: assert torch_layer.bias.shape == bias.shape, f"""{torch_layer} layer.bias does not match""" _a : Any = nn.Parameter(__a ) def UpperCAmelCase_ (__a : int , __a : Optional[Any] , __a : int ): """simple docstring""" _a : Tuple = np.asarray(weights[0] ) _a : Union[str, Any] = np.asarray(weights[1] ) _a : Dict = np.asarray(weights[2] ) set_param( torch_layer.self_attention.query_key , torch.tensor(__a ).transpose(1 , 2 ).contiguous().view(-1 , __a ) , ) set_param( torch_layer.self_attention.value , torch.tensor(__a ).transpose(1 , 2 ).contiguous().view(-1 , __a ) , ) set_param( torch_layer.output.dense , torch.tensor(__a ).view(-1 , __a ).contiguous().transpose(0 , 1 ) , ) def UpperCAmelCase_ (__a : Optional[Any] , __a : Optional[int] , __a : List[str] ): """simple docstring""" _a : Dict = np.asarray(weights[0] ) _a : Union[str, Any] = np.asarray(weights[1] ) _a : str = np.asarray(weights[2] ) _a : int = np.asarray(weights[3] ) set_param( torch_layer.self_attention.query , torch.tensor(__a ).transpose(1 , 2 ).contiguous().view(-1 , __a ) , ) set_param( torch_layer.self_attention.key , torch.tensor(__a ).transpose(1 , 2 ).contiguous().view(-1 , __a ) , ) set_param( torch_layer.self_attention.value , torch.tensor(__a ).transpose(1 , 2 ).contiguous().view(-1 , __a ) , ) set_param( torch_layer.output.dense , torch.tensor(__a ).view(-1 , __a ).contiguous().transpose(0 , 1 ) , ) def UpperCAmelCase_ (__a : Any , __a : Any , __a : Optional[Any] ): """simple docstring""" _a : List[str] = weights[0][0][0] _a : List[Any] = np.asarray(layer_norm_a[0] ) _a : List[str] = np.asarray(layer_norm_a[1] ) set_param( torch_block.attention.layer_norm , torch.tensor(__a ) , torch.tensor(__a ) , ) # lsh weights + output _a : List[str] = weights[0][1] if len(__a ) < 4: set_layer_weights_in_torch_lsh(__a , torch_block.attention , __a ) else: set_layer_weights_in_torch_local(__a , torch_block.attention , __a ) # intermediate weighs _a : Optional[Any] = weights[2][0][1][2] # Chunked Feed Forward if len(__a ) == 4: _a : Union[str, Any] = intermediate_weights[2] # layernorm 2 _a : Any = np.asarray(intermediate_weights[0][0] ) _a : List[Any] = np.asarray(intermediate_weights[0][1] ) set_param( torch_block.feed_forward.layer_norm , torch.tensor(__a ) , torch.tensor(__a ) , ) # intermediate dense _a : Any = np.asarray(intermediate_weights[1][0] ) _a : Any = np.asarray(intermediate_weights[1][1] ) set_param( torch_block.feed_forward.dense.dense , torch.tensor(__a ).transpose(0 , 1 ).contiguous() , torch.tensor(__a ) , ) # intermediate out _a : Optional[int] = np.asarray(intermediate_weights[4][0] ) _a : int = np.asarray(intermediate_weights[4][1] ) set_param( torch_block.feed_forward.output.dense , torch.tensor(__a ).transpose(0 , 1 ).contiguous() , torch.tensor(__a ) , ) def UpperCAmelCase_ (__a : Dict , __a : Dict , __a : List[Any] ): """simple docstring""" _a : Optional[int] = torch_model.reformer # word embeds _a : Tuple = np.asarray(weights[1] ) set_param( torch_model_reformer.embeddings.word_embeddings , torch.tensor(__a ) , ) if isinstance(weights[3] , __a ): _a : Any = torch_model_reformer.embeddings.position_embeddings for emb_idx in range(len(position_embeddings.weights ) ): _a : List[Any] = np.asarray(weights[3][emb_idx][0] ) assert ( position_embeddings.weights[emb_idx].shape == emb_weights.shape ), f"""{position_embeddings[emb_idx]} emb does not match""" _a : Any = nn.Parameter(torch.tensor(__a ) ) _a : List[str] = weights[5] assert len(torch_model_reformer.encoder.layers ) * 4 == len( __a ), "HF and trax model do not have the same number of layers" for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ): _a : Tuple = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)] set_block_weights_in_torch(__a , __a , __a ) # output layer norm _a : Optional[Any] = np.asarray(weights[7][0] ) _a : int = np.asarray(weights[7][1] ) set_param( torch_model_reformer.encoder.layer_norm , torch.tensor(__a ) , torch.tensor(__a ) , ) # output embeddings _a : List[str] = np.asarray(weights[9][0] ) _a : int = np.asarray(weights[9][1] ) set_param( torch_model.lm_head.decoder , torch.tensor(__a ).transpose(0 , 1 ).contiguous() , torch.tensor(__a ) , ) def UpperCAmelCase_ (__a : Tuple , __a : Optional[Any] , __a : Dict ): """simple docstring""" _a : List[Any] = ReformerConfig.from_json_file(__a ) print(f"""Building PyTorch model from configuration: {config}""" ) _a : int = ReformerModelWithLMHead(__a ) with open(__a , 'rb' ) as f: _a : Optional[Any] = pickle.load(__a )['weights'] set_model_weights_in_torch(__a , __a , config.hidden_size ) # Save pytorch-model print(f"""Save PyTorch model to {pytorch_dump_path}""" ) torch.save(model.state_dict() , __a ) if __name__ == "__main__": __lowerCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--trax_model_pkl_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained Reformer model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) __lowerCAmelCase = parser.parse_args() convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
271
1
'''simple docstring''' import collections import inspect import unittest from transformers import FocalNetConfig 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_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, ) from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class UpperCAmelCase__ : """simple docstring""" def __init__( self : Optional[int] ,_a : List[Any] ,_a : Optional[Any]=13 ,_a : List[Any]=32 ,_a : Tuple=2 ,_a : Union[str, Any]=3 ,_a : str=16 ,_a : Optional[Any]=[32, 64, 128] ,_a : Tuple=[1, 2, 1] ,_a : Any=[2, 2, 4] ,_a : List[Any]=2 ,_a : Dict=2.0 ,_a : Union[str, Any]=True ,_a : Any=0.0 ,_a : List[str]=0.0 ,_a : Dict=0.1 ,_a : List[str]="gelu" ,_a : Union[str, Any]=False ,_a : Optional[int]=True ,_a : int=0.02 ,_a : Optional[Any]=1E-5 ,_a : str=True ,_a : Any=None ,_a : Union[str, Any]=True ,_a : Union[str, Any]=10 ,_a : Optional[int]=8 ,_a : List[Any]=["stage1", "stage2"] ,_a : Optional[Any]=[1, 2] ,): '''simple docstring''' _a : Any = parent _a : Union[str, Any] = batch_size _a : Dict = image_size _a : str = patch_size _a : List[str] = num_channels _a : Any = embed_dim _a : Dict = hidden_sizes _a : List[str] = depths _a : Optional[Any] = num_heads _a : str = window_size _a : Optional[int] = mlp_ratio _a : Union[str, Any] = qkv_bias _a : int = hidden_dropout_prob _a : Union[str, Any] = attention_probs_dropout_prob _a : int = drop_path_rate _a : List[str] = hidden_act _a : Any = use_absolute_embeddings _a : List[Any] = patch_norm _a : Tuple = layer_norm_eps _a : List[str] = initializer_range _a : Dict = is_training _a : Any = scope _a : List[str] = use_labels _a : List[Any] = type_sequence_label_size _a : List[Any] = encoder_stride _a : Tuple = out_features _a : Optional[int] = out_indices def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _a : Union[str, Any] = None if self.use_labels: _a : Union[str, Any] = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) _a : str = self.get_config() return config, pixel_values, labels def __lowercase ( self : Optional[Any] ): '''simple docstring''' return FocalNetConfig( image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,embed_dim=self.embed_dim ,hidden_sizes=self.hidden_sizes ,depths=self.depths ,num_heads=self.num_heads ,window_size=self.window_size ,mlp_ratio=self.mlp_ratio ,qkv_bias=self.qkv_bias ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,drop_path_rate=self.drop_path_rate ,hidden_act=self.hidden_act ,use_absolute_embeddings=self.use_absolute_embeddings ,path_norm=self.patch_norm ,layer_norm_eps=self.layer_norm_eps ,initializer_range=self.initializer_range ,encoder_stride=self.encoder_stride ,out_features=self.out_features ,out_indices=self.out_indices ,) def __lowercase ( self : Any ,_a : Optional[int] ,_a : List[str] ,_a : Tuple ): '''simple docstring''' _a : Dict = FocalNetModel(config=_a ) model.to(_a ) model.eval() _a : Optional[Any] = model(_a ) _a : Dict = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) _a : int = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, expected_seq_len, expected_dim) ) def __lowercase ( self : int ,_a : List[str] ,_a : Optional[Any] ,_a : Any ): '''simple docstring''' _a : Any = FocalNetBackbone(config=_a ) model.to(_a ) model.eval() _a : Optional[int] = model(_a ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) ,len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) ,[self.batch_size, self.image_size, 8, 8] ) # verify channels self.parent.assertEqual(len(model.channels ) ,len(config.out_features ) ) self.parent.assertListEqual(model.channels ,config.hidden_sizes[:-1] ) # verify backbone works with out_features=None _a : Any = None _a : List[str] = FocalNetBackbone(config=_a ) model.to(_a ) model.eval() _a : str = model(_a ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) ,1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) ,[self.batch_size, self.image_size * 2, 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) ,1 ) self.parent.assertListEqual(model.channels ,[config.hidden_sizes[-1]] ) def __lowercase ( self : Dict ,_a : int ,_a : Tuple ,_a : Tuple ): '''simple docstring''' _a : List[Any] = FocalNetForMaskedImageModeling(config=_a ) model.to(_a ) model.eval() _a : List[str] = model(_a ) self.parent.assertEqual( result.reconstruction.shape ,(self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images _a : Any = 1 _a : Union[str, Any] = FocalNetForMaskedImageModeling(_a ) model.to(_a ) model.eval() _a : str = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _a : Any = model(_a ) self.parent.assertEqual(result.reconstruction.shape ,(self.batch_size, 1, self.image_size, self.image_size) ) def __lowercase ( self : Any ,_a : int ,_a : Tuple ,_a : List[str] ): '''simple docstring''' _a : Optional[int] = self.type_sequence_label_size _a : Optional[int] = FocalNetForImageClassification(_a ) model.to(_a ) model.eval() _a : Optional[Any] = model(_a ,labels=_a ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) # test greyscale images _a : Any = 1 _a : List[Any] = FocalNetForImageClassification(_a ) model.to(_a ) model.eval() _a : Tuple = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _a : List[Any] = model(_a ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def __lowercase ( self : int ): '''simple docstring''' _a : Union[str, Any] = self.prepare_config_and_inputs() _a, _a, _a : str = config_and_inputs _a : str = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase__ ( lowercase__ , lowercase__ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : int = ( ( FocalNetModel, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetBackbone, ) if is_torch_available() else () ) __UpperCAmelCase : str = ( {'''feature-extraction''': FocalNetModel, '''image-classification''': FocalNetForImageClassification} if is_torch_available() else {} ) __UpperCAmelCase : Dict = False __UpperCAmelCase : Dict = False __UpperCAmelCase : int = False __UpperCAmelCase : List[Any] = False __UpperCAmelCase : Any = False def __lowercase ( self : List[Any] ): '''simple docstring''' _a : Any = FocalNetModelTester(self ) _a : int = ConfigTester(self ,config_class=_a ,embed_dim=37 ,has_text_modality=_a ) def __lowercase ( self : Any ): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __lowercase ( self : List[Any] ): '''simple docstring''' return def __lowercase ( self : Dict ): '''simple docstring''' _a : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def __lowercase ( self : str ): '''simple docstring''' _a : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_a ) def __lowercase ( self : Tuple ): '''simple docstring''' _a : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*_a ) def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_a ) @unittest.skip(reason='FocalNet does not use inputs_embeds' ) def __lowercase ( self : List[str] ): '''simple docstring''' pass @unittest.skip(reason='FocalNet does not use feedforward chunking' ) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' pass def __lowercase ( self : Any ): '''simple docstring''' _a, _a : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes[:-1]: _a : Tuple = model_class(_a ) self.assertIsInstance(model.get_input_embeddings() ,(nn.Module) ) _a : List[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_a ,nn.Linear ) ) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a, _a : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes[:-1]: _a : str = model_class(_a ) _a : str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _a : str = [*signature.parameters.keys()] _a : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] ,_a ) def __lowercase ( self : Union[str, Any] ,_a : Any ,_a : Any ,_a : Dict ,_a : int ): '''simple docstring''' _a : Dict = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): _a : int = model(**self._prepare_for_class(_a ,_a ) ) _a : Optional[int] = outputs.hidden_states _a : int = getattr( self.model_tester ,'expected_num_hidden_layers' ,len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_a ) ,_a ) # FocalNet has a different seq_length _a : Dict = ( config.patch_size if isinstance(config.patch_size ,collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) _a : Optional[Any] = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) ,[num_patches, self.model_tester.embed_dim] ,) _a : Optional[int] = outputs.reshaped_hidden_states self.assertEqual(len(_a ) ,_a ) _a, _a, _a, _a : Tuple = reshaped_hidden_states[0].shape _a : List[Any] = ( reshaped_hidden_states[0].view(_a ,_a ,height * width ).permute(0 ,2 ,1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) ,[num_patches, self.model_tester.embed_dim] ,) def __lowercase ( self : Tuple ): '''simple docstring''' _a, _a : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() _a : List[str] = ( self.model_tester.image_size if isinstance(self.model_tester.image_size ,collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes[:-1]: _a : Union[str, Any] = True self.check_hidden_states_output(_a ,_a ,_a ,_a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _a : int = True self.check_hidden_states_output(_a ,_a ,_a ,_a ) def __lowercase ( self : int ): '''simple docstring''' _a, _a : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() _a : Union[str, Any] = 3 _a : Tuple = ( self.model_tester.image_size if isinstance(self.model_tester.image_size ,collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) _a : Union[str, Any] = ( config.patch_size if isinstance(config.patch_size ,collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) _a : Any = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) _a : Optional[int] = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes[:-1]: _a : Any = True self.check_hidden_states_output(_a ,_a ,_a ,(padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _a : int = True self.check_hidden_states_output(_a ,_a ,_a ,(padded_height, padded_width) ) @slow def __lowercase ( self : Optional[int] ): '''simple docstring''' for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Any = FocalNetModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def __lowercase ( self : List[str] ): '''simple docstring''' _a, _a : List[str] = self.model_tester.prepare_config_and_inputs_for_common() _a : List[str] = _config_zero_init(_a ) for model_class in self.all_model_classes: _a : Union[str, Any] = model_class(config=_a ) for name, param in model.named_parameters(): if "embeddings" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item() ,[0.0, 1.0] ,msg=F"""Parameter {name} of model {model_class} seems not properly initialized""" ,) @require_vision @require_torch class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" @cached_property def __lowercase ( self : Tuple ): '''simple docstring''' return AutoImageProcessor.from_pretrained('microsoft/focalnet-tiny' ) if is_vision_available() else None @slow def __lowercase ( self : Any ): '''simple docstring''' _a : Dict = FocalNetForImageClassification.from_pretrained('microsoft/focalnet-tiny' ).to(_a ) _a : int = self.default_image_processor _a : Optional[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) _a : List[str] = image_processor(images=_a ,return_tensors='pt' ).to(_a ) # forward pass with torch.no_grad(): _a : List[Any] = model(**_a ) # verify the logits _a : Dict = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape ,_a ) _a : List[Any] = torch.tensor([0.2166, -0.4368, 0.2191] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,_a ,atol=1E-4 ) ) self.assertTrue(outputs.logits.argmax(dim=-1 ).item() ,281 ) @require_torch class UpperCAmelCase__ ( lowercase__ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Any = (FocalNetBackbone,) if is_torch_available() else () __UpperCAmelCase : int = FocalNetConfig __UpperCAmelCase : int = False def __lowercase ( self : Any ): '''simple docstring''' _a : Optional[int] = FocalNetModelTester(self )
271
'''simple docstring''' import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" @property def __lowercase ( self : Union[str, Any] ): '''simple docstring''' torch.manual_seed(0 ) _a : Any = UNetaDModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=3 ,out_channels=3 ,down_block_types=('DownBlock2D', 'AttnDownBlock2D') ,up_block_types=('AttnUpBlock2D', 'UpBlock2D') ,) return model @property def __lowercase ( self : Optional[int] ): '''simple docstring''' torch.manual_seed(0 ) _a : Union[str, Any] = VQModel( block_out_channels=[32, 64] ,in_channels=3 ,out_channels=3 ,down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] ,up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] ,latent_channels=3 ,) return model @property def __lowercase ( self : Optional[int] ): '''simple docstring''' torch.manual_seed(0 ) _a : Any = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1E-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1000 ,) return CLIPTextModel(_a ) def __lowercase ( self : Tuple ): '''simple docstring''' _a : Dict = self.dummy_uncond_unet _a : List[Any] = DDIMScheduler() _a : List[Any] = self.dummy_vq_model _a : str = LDMPipeline(unet=_a ,vqvae=_a ,scheduler=_a ) ldm.to(_a ) ldm.set_progress_bar_config(disable=_a ) _a : List[str] = torch.manual_seed(0 ) _a : List[str] = ldm(generator=_a ,num_inference_steps=2 ,output_type='numpy' ).images _a : List[str] = torch.manual_seed(0 ) _a : Union[str, Any] = ldm(generator=_a ,num_inference_steps=2 ,output_type='numpy' ,return_dict=_a )[0] _a : Tuple = image[0, -3:, -3:, -1] _a : Optional[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _a : int = np.array([0.8512, 0.818, 0.6411, 0.6808, 0.4465, 0.5618, 0.46, 0.6231, 0.5172] ) _a : Any = 1E-2 if torch_device != 'mps' else 3E-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < tolerance @slow @require_torch class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a : List[str] = LDMPipeline.from_pretrained('CompVis/ldm-celebahq-256' ) ldm.to(_a ) ldm.set_progress_bar_config(disable=_a ) _a : Optional[int] = torch.manual_seed(0 ) _a : Dict = ldm(generator=_a ,num_inference_steps=5 ,output_type='numpy' ).images _a : str = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) _a : Optional[int] = np.array([0.4399, 0.4_4975, 0.4_6825, 0.474, 0.4359, 0.4581, 0.4_5095, 0.4341, 0.4447] ) _a : int = 1E-2 if torch_device != 'mps' else 3E-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance
271
1
'''simple docstring''' 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 UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : int = '''informer''' __UpperCAmelCase : Dict = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', '''num_hidden_layers''': '''encoder_layers''', } def __init__( self : List[str] ,_a : Optional[int] = None ,_a : Optional[int] = None ,_a : str = "student_t" ,_a : str = "nll" ,_a : int = 1 ,_a : List[int] = None ,_a : Optional[Union[str, bool]] = "mean" ,_a : int = 0 ,_a : int = 0 ,_a : int = 0 ,_a : int = 0 ,_a : Optional[List[int]] = None ,_a : Optional[List[int]] = None ,_a : int = 64 ,_a : int = 32 ,_a : int = 32 ,_a : int = 2 ,_a : int = 2 ,_a : int = 2 ,_a : int = 2 ,_a : bool = True ,_a : str = "gelu" ,_a : float = 0.05 ,_a : float = 0.1 ,_a : float = 0.1 ,_a : float = 0.1 ,_a : float = 0.1 ,_a : int = 100 ,_a : float = 0.02 ,_a : Any=True ,_a : str = "prob" ,_a : int = 5 ,_a : bool = True ,**_a : Optional[Any] ,): '''simple docstring''' _a : str = prediction_length _a : Union[str, Any] = context_length or prediction_length _a : Optional[int] = distribution_output _a : Any = loss _a : Optional[Any] = input_size _a : Union[str, Any] = num_time_features _a : Optional[Any] = lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7] _a : List[str] = scaling _a : Optional[Any] = num_dynamic_real_features _a : Dict = num_static_real_features _a : List[Any] = num_static_categorical_features # set cardinality if cardinality and num_static_categorical_features > 0: if len(_a ) != num_static_categorical_features: raise ValueError( 'The cardinality should be a list of the same length as `num_static_categorical_features`' ) _a : Optional[int] = cardinality else: _a : Tuple = [0] # set embedding_dimension if embedding_dimension and num_static_categorical_features > 0: if len(_a ) != num_static_categorical_features: raise ValueError( 'The embedding dimension should be a list of the same length as `num_static_categorical_features`' ) _a : Optional[int] = embedding_dimension else: _a : List[str] = [min(50 ,(cat + 1) // 2 ) for cat in self.cardinality] _a : str = num_parallel_samples # Transformer architecture configuration _a : Optional[int] = input_size * len(self.lags_sequence ) + self._number_of_features _a : Union[str, Any] = d_model _a : Union[str, Any] = encoder_attention_heads _a : str = decoder_attention_heads _a : List[str] = encoder_ffn_dim _a : Tuple = decoder_ffn_dim _a : Tuple = encoder_layers _a : Tuple = decoder_layers _a : Any = dropout _a : Tuple = attention_dropout _a : Optional[int] = activation_dropout _a : Optional[Any] = encoder_layerdrop _a : List[Any] = decoder_layerdrop _a : Tuple = activation_function _a : Union[str, Any] = init_std _a : int = use_cache # Informer _a : List[str] = attention_type _a : int = sampling_factor _a : List[Any] = distil super().__init__(is_encoder_decoder=_a ,**_a ) @property def __lowercase ( self : Any ): '''simple docstring''' 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 )
271
'''simple docstring''' import warnings from ...utils import logging from .image_processing_beit import BeitImageProcessor __lowerCAmelCase = logging.get_logger(__name__) class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" def __init__( self : int ,*_a : Optional[int] ,**_a : str ): '''simple docstring''' warnings.warn( 'The class BeitFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use BeitImageProcessor instead.' ,_a ,) super().__init__(*_a ,**_a )
271
1
'''simple docstring''' import pprint import requests __lowerCAmelCase = """https://zenquotes.io/api""" def UpperCAmelCase_ (): """simple docstring""" return requests.get(API_ENDPOINT_URL + '/today' ).json() def UpperCAmelCase_ (): """simple docstring""" return requests.get(API_ENDPOINT_URL + '/random' ).json() if __name__ == "__main__": __lowerCAmelCase = random_quotes() pprint.pprint(response)
271
'''simple docstring''' from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.utils.data import DistributedSampler, RandomSampler from transformers import PreTrainedModel, Trainer, logging from transformers.integrations import is_fairscale_available from transformers.models.fsmt.configuration_fsmt import FSMTConfig from transformers.optimization 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_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.trainer_pt_utils import get_tpu_sampler from transformers.training_args import ParallelMode from transformers.utils import is_torch_tpu_available if is_fairscale_available(): from fairscale.optim import OSS __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = { """linear""": get_linear_schedule_with_warmup, """cosine""": get_cosine_schedule_with_warmup, """cosine_w_restarts""": get_cosine_with_hard_restarts_schedule_with_warmup, """polynomial""": get_polynomial_decay_schedule_with_warmup, """constant""": get_constant_schedule, """constant_w_warmup""": get_constant_schedule_with_warmup, } class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" def __init__( self : Optional[int] ,_a : Optional[Any]=None ,_a : Dict=None ,*_a : int ,**_a : str ): '''simple docstring''' super().__init__(*_a ,**_a ) if config is None: assert isinstance(self.model ,_a ), ( "If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is" F""" {self.model.__class__}""" ) _a : List[Any] = self.model.config else: _a : Optional[int] = config _a : List[str] = data_args _a : List[Any] = self.config.tgt_vocab_size if isinstance(self.config ,_a ) else self.config.vocab_size if self.args.label_smoothing != 0 or (self.data_args is not None and self.data_args.ignore_pad_token_for_loss): assert self.config.pad_token_id is not None, ( "Make sure that `config.pad_token_id` is correcly defined when ignoring `pad_token` for loss" " calculation or doing label smoothing." ) if self.config.pad_token_id is None and self.config.eos_token_id is not None: logger.warning( F"""The `config.pad_token_id` is `None`. Using `config.eos_token_id` = {self.config.eos_token_id} for""" ' padding..' ) if self.args.label_smoothing == 0: _a : List[str] = torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id ) else: # dynamically import label_smoothed_nll_loss from utils import label_smoothed_nll_loss _a : Tuple = label_smoothed_nll_loss def __lowercase ( self : List[str] ,_a : int ): '''simple docstring''' if self.optimizer is None: _a : Union[str, Any] = ['bias', 'LayerNorm.weight'] _a : Tuple = [ { 'params': [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay )], 'weight_decay': self.args.weight_decay, }, { 'params': [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay )], 'weight_decay': 0.0, }, ] _a : Optional[int] = Adafactor if self.args.adafactor else AdamW if self.args.adafactor: _a : Any = Adafactor _a : Dict = {'scale_parameter': False, 'relative_step': False} else: _a : Union[str, Any] = AdamW _a : str = { 'betas': (self.args.adam_betaa, self.args.adam_betaa), 'eps': self.args.adam_epsilon, } _a : Union[str, Any] = self.args.learning_rate if self.sharded_ddp: _a : str = OSS( params=_a ,optim=_a ,**_a ,) else: _a : Tuple = optimizer_cls(_a ,**_a ) if self.lr_scheduler is None: _a : List[Any] = self._get_lr_scheduler(_a ) else: # ignoring --lr_scheduler logger.warning('scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored.' ) def __lowercase ( self : List[Any] ,_a : List[Any] ): '''simple docstring''' _a : str = arg_to_scheduler[self.args.lr_scheduler] if self.args.lr_scheduler == "constant": _a : int = schedule_func(self.optimizer ) elif self.args.lr_scheduler == "constant_w_warmup": _a : List[str] = schedule_func(self.optimizer ,num_warmup_steps=self.args.warmup_steps ) else: _a : Optional[int] = schedule_func( self.optimizer ,num_warmup_steps=self.args.warmup_steps ,num_training_steps=_a ) return scheduler def __lowercase ( self : Tuple ): '''simple docstring''' if isinstance(self.train_dataset ,torch.utils.data.IterableDataset ): return None elif is_torch_tpu_available(): return get_tpu_sampler(self.train_dataset ) else: if self.args.sortish_sampler: self.train_dataset.make_sortish_sampler( self.args.per_device_train_batch_size ,distributed=(self.args.parallel_mode == ParallelMode.DISTRIBUTED) ,) return ( RandomSampler(self.train_dataset ) if self.args.local_rank == -1 else DistributedSampler(self.train_dataset ) ) def __lowercase ( self : Dict ,_a : Dict ,_a : Any ,_a : Dict ): '''simple docstring''' if self.args.label_smoothing == 0: if self.data_args is not None and self.data_args.ignore_pad_token_for_loss: # force training to ignore pad token _a : List[Any] = model(**_a ,use_cache=_a )[0] _a : Union[str, Any] = self.loss_fn(logits.view(-1 ,logits.shape[-1] ) ,labels.view(-1 ) ) else: # compute usual loss via models _a, _a : Union[str, Any] = model(**_a ,labels=_a ,use_cache=_a )[:2] else: # compute label smoothed loss _a : List[Any] = model(**_a ,use_cache=_a )[0] _a : Any = torch.nn.functional.log_softmax(_a ,dim=-1 ) _a, _a : List[str] = self.loss_fn(_a ,_a ,self.args.label_smoothing ,ignore_index=self.config.pad_token_id ) return loss, logits def __lowercase ( self : Optional[int] ,_a : Union[str, Any] ,_a : List[Any] ): '''simple docstring''' _a : Optional[int] = inputs.pop('labels' ) _a, _a : int = self._compute_loss(_a ,_a ,_a ) return loss def __lowercase ( self : Optional[Any] ,_a : nn.Module ,_a : Dict[str, Union[torch.Tensor, Any]] ,_a : bool ,_a : Optional[List[str]] = None ,): '''simple docstring''' _a : int = self._prepare_inputs(_a ) _a : Any = { 'max_length': self.data_args.val_max_target_length if self.data_args is not None else self.config.max_length, 'num_beams': self.data_args.eval_beams if self.data_args is not None else self.config.num_beams, } if self.args.predict_with_generate and not self.args.prediction_loss_only: _a : int = self.model.generate( inputs['input_ids'] ,attention_mask=inputs['attention_mask'] ,**_a ,) # in case the batch is shorter than max length, the output should be padded if generated_tokens.shape[-1] < gen_kwargs["max_length"]: _a : int = self._pad_tensors_to_max_len(_a ,gen_kwargs['max_length'] ) _a : Union[str, Any] = inputs.pop('labels' ) with torch.no_grad(): # compute loss on predict data _a, _a : Optional[int] = self._compute_loss(_a ,_a ,_a ) _a : Optional[Any] = loss.mean().detach() if self.args.prediction_loss_only: return (loss, None, None) _a : Optional[Any] = generated_tokens if self.args.predict_with_generate else logits if labels.shape[-1] < gen_kwargs["max_length"]: _a : Dict = self._pad_tensors_to_max_len(_a ,gen_kwargs['max_length'] ) return (loss, logits, labels) def __lowercase ( self : str ,_a : Tuple ,_a : Tuple ): '''simple docstring''' _a : List[Any] = self.config.pad_token_id if self.config.pad_token_id is not None else self.config.eos_token_id if pad_token_id is None: raise ValueError( 'Make sure that either `config.pad_token_id` or `config.eos_token_id` is defined if tensor has to be' F""" padded to `max_length`={max_length}""" ) _a : int = pad_token_id * torch.ones( (tensor.shape[0], max_length) ,dtype=tensor.dtype ,device=tensor.device ) _a : Union[str, Any] = tensor return padded_tensor
271
1
'''simple docstring''' import unittest import numpy as np import torch from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self : str ): '''simple docstring''' _a : int = 10 def __lowercase ( self : Dict ): '''simple docstring''' _a : str = [1, 2, 3, 4] _a : Dict = [1, 2, 3, 4, 0, 0, 0, 0, 0, 0] self.assertEqual(truncate_or_pad(_a ,self.block_size ,0 ) ,_a ) def __lowercase ( self : int ): '''simple docstring''' _a : Tuple = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] _a : Optional[int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] self.assertEqual(truncate_or_pad(_a ,self.block_size ,0 ) ,_a ) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Any = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] _a : str = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] self.assertEqual(truncate_or_pad(_a ,self.block_size ,0 ) ,_a ) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : Any = 'It was the year of Our Lord one thousand seven hundred and\n seventy-five.\n\nSpiritual revelations were conceded to England at that\n favoured period, as at this.' _a, _a : str = process_story(_a ) self.assertEqual(_a ,[] ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a : Optional[int] = '' _a, _a : Union[str, Any] = process_story(_a ) self.assertEqual(_a ,[] ) self.assertEqual(_a ,[] ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a : List[Any] = ( 'It was the year of Our Lord one thousand seven hundred and ' 'seventy-five\n\nSpiritual revelations were conceded to England ' 'at that favoured period, as at this.\n@highlight\n\nIt was the best of times' ) _a, _a : List[str] = process_story(_a ) _a : List[Any] = [ 'It was the year of Our Lord one thousand seven hundred and seventy-five.', 'Spiritual revelations were conceded to England at that favoured period, as at this.', ] self.assertEqual(_a ,_a ) _a : List[Any] = ['It was the best of times.'] self.assertEqual(_a ,_a ) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Optional[Any] = torch.tensor([1, 2, 3, 4] ) _a : int = torch.tensor([1, 1, 1, 1] ) np.testing.assert_array_equal(build_mask(_a ,0 ).numpy() ,expected.numpy() ) def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : List[str] = torch.tensor([1, 2, 3, 4, 23, 23, 23] ) _a : int = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(_a ,23 ).numpy() ,expected.numpy() ) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Union[str, Any] = torch.tensor([8, 2, 3, 4, 1, 1, 1] ) _a : Union[str, Any] = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(_a ,1 ).numpy() ,expected.numpy() ) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Optional[Any] = 101 _a : List[Any] = torch.tensor([[1, 2, 3, 4, 5, 6], [1, 2, 3, 101, 5, 6], [1, 101, 3, 4, 101, 6]] ) _a : Any = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1]] ) _a : Optional[int] = compute_token_type_ids(_a ,_a ) np.testing.assert_array_equal(_a ,_a )
271
'''simple docstring''' import gzip import hashlib import json import multiprocessing import os import re import shutil import time from pathlib import Path import numpy as np from arguments import PreprocessingArguments from datasets import load_dataset from minhash_deduplication import deduplicate_dataset from transformers import AutoTokenizer, HfArgumentParser __lowerCAmelCase = re.compile(r"""\s+""") def UpperCAmelCase_ (__a : Any ): """simple docstring""" return {"hash": hashlib.mda(re.sub(__a , '' , example['content'] ).encode('utf-8' ) ).hexdigest()} def UpperCAmelCase_ (__a : str ): """simple docstring""" _a : List[str] = [len(__a ) for line in example['content'].splitlines()] return {"line_mean": np.mean(__a ), "line_max": max(__a )} def UpperCAmelCase_ (__a : str ): """simple docstring""" _a : Union[str, Any] = np.mean([c.isalnum() for c in example['content']] ) return {"alpha_frac": alpha_frac} def UpperCAmelCase_ (__a : Optional[int] , __a : Any ): """simple docstring""" if example["hash"] in uniques: uniques.remove(example['hash'] ) return True else: return False def UpperCAmelCase_ (__a : int , __a : Union[str, Any]=5 ): """simple docstring""" _a : Optional[int] = ['auto-generated', 'autogenerated', 'automatically generated'] _a : List[str] = example['content'].splitlines() for _, line in zip(range(__a ) , __a ): for keyword in keywords: if keyword in line.lower(): return {"autogenerated": True} else: return {"autogenerated": False} def UpperCAmelCase_ (__a : List[str] , __a : Dict=5 , __a : Tuple=0.05 ): """simple docstring""" _a : Optional[int] = ['unit tests', 'test file', 'configuration file'] _a : int = example['content'].splitlines() _a : int = 0 _a : Dict = 0 # first test for _, line in zip(range(__a ) , __a ): for keyword in keywords: if keyword in line.lower(): return {"config_or_test": True} # second test _a : int = example['content'].count('\n' ) _a : int = int(coeff * nlines ) for line in lines: count_config += line.lower().count('config' ) count_test += line.lower().count('test' ) if count_config > threshold or count_test > threshold: return {"config_or_test": True} return {"config_or_test": False} def UpperCAmelCase_ (__a : Optional[int] ): """simple docstring""" _a : List[str] = ['def ', 'class ', 'for ', 'while '] _a : str = example['content'].splitlines() for line in lines: for keyword in keywords: if keyword in line.lower(): return {"has_no_keywords": False} return {"has_no_keywords": True} def UpperCAmelCase_ (__a : int , __a : Any=4 ): """simple docstring""" _a : List[str] = example['content'].splitlines() _a : Dict = 0 for line in lines: counter += line.lower().count('=' ) if counter > minimum: return {"has_few_assignments": False} return {"has_few_assignments": True} def UpperCAmelCase_ (__a : str ): """simple docstring""" _a : Optional[Any] = tokenizer(example['content'] , truncation=__a )['input_ids'] _a : Optional[int] = len(example['content'] ) / len(__a ) return {"ratio": ratio} def UpperCAmelCase_ (__a : str ): """simple docstring""" _a : Dict = {} results.update(get_hash(__a ) ) results.update(line_stats(__a ) ) results.update(alpha_stats(__a ) ) results.update(char_token_ratio(__a ) ) results.update(is_autogenerated(__a ) ) results.update(is_config_or_test(__a ) ) results.update(has_no_keywords(__a ) ) results.update(has_few_assignments(__a ) ) return results def UpperCAmelCase_ (__a : Any , __a : Any , __a : str ): """simple docstring""" if not check_uniques(__a , __a ): return False elif example["autogenerated"]: return False elif example["line_max"] > args.line_max: return False elif example["line_mean"] > args.line_mean: return False elif example["alpha_frac"] < args.alpha_frac: return False elif example["ratio"] < args.min_token_ratio: return False elif example["config_or_test"] and np.random.rand() <= args.filter_proba: return False elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba: return False elif example["has_few_assignments"]: return False else: return True def UpperCAmelCase_ (__a : Union[str, Any] ): """simple docstring""" with open(__a , 'rb' ) as f_in: with gzip.open(str(__a ) + '.gz' , 'wb' , compresslevel=6 ) as f_out: shutil.copyfileobj(__a , __a ) os.unlink(__a ) # Settings __lowerCAmelCase = HfArgumentParser(PreprocessingArguments) __lowerCAmelCase = parser.parse_args() if args.num_workers is None: __lowerCAmelCase = multiprocessing.cpu_count() __lowerCAmelCase = AutoTokenizer.from_pretrained(args.tokenizer_dir) # Load dataset __lowerCAmelCase = time.time() __lowerCAmelCase = load_dataset(args.dataset_name, split="""train""") print(f'''Time to load dataset: {time.time()-t_start:.2f}''') # Run preprocessing __lowerCAmelCase = time.time() __lowerCAmelCase = ds.map(preprocess, num_proc=args.num_workers) print(f'''Time to preprocess dataset: {time.time()-t_start:.2f}''') # Deduplicate hashes __lowerCAmelCase = set(ds.unique("""hash""")) __lowerCAmelCase = len(uniques) / len(ds) print(f'''Fraction of duplicates: {1-frac:.2%}''') # Deduplicate data and apply heuristics __lowerCAmelCase = time.time() __lowerCAmelCase = ds.filter(filter, fn_kwargs={"""uniques""": uniques, """args""": args}) print(f'''Time to filter dataset: {time.time()-t_start:.2f}''') print(f'''Size of filtered dataset: {len(ds_filter)}''') # Deduplicate with minhash and jaccard similarity if args.near_deduplication: __lowerCAmelCase = time.time() __lowerCAmelCase , __lowerCAmelCase = deduplicate_dataset(ds_filter, args.jaccard_threshold) print(f'''Time to deduplicate dataset: {time.time()-t_start:.2f}''') print(f'''Size of deduplicate dataset: {len(ds_filter)}''') # Save data in batches of samples_per_file __lowerCAmelCase = Path(args.output_dir) output_dir.mkdir(exist_ok=True) # save duplicate_clusters in the output_dir as artifacts # not sure it is the right place the save it if args.near_deduplication: with open(output_dir / """duplicate_clusters.json""", """w""") as f: json.dump(duplicate_clusters, f) __lowerCAmelCase = output_dir / """data""" data_dir.mkdir(exist_ok=True) __lowerCAmelCase = time.time() for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)): __lowerCAmelCase = str(data_dir / f'''file-{file_number+1:012}.json''') __lowerCAmelCase = min(len(ds_filter), index + args.samples_per_file) ds_filter.select(list(range(index, end_index))).to_json(file_path) compress_file(file_path) print(f'''Time to save dataset: {time.time()-t_start:.2f}''')
271
1
'''simple docstring''' import csv from collections import defaultdict from dataclasses import dataclass, field from typing import List, Optional import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import ScalarFormatter from transformers import HfArgumentParser def UpperCAmelCase_ (__a : List[str]=None , __a : Dict=None ): """simple docstring""" return field(default_factory=lambda: default , metadata=__a ) @dataclass class UpperCAmelCase__ : """simple docstring""" __UpperCAmelCase : str = field( metadata={'''help''': '''The csv file to plot.'''} , ) __UpperCAmelCase : bool = field( default=lowercase__ , metadata={'''help''': '''Whether to plot along batch size or sequence length. Defaults to sequence length.'''} , ) __UpperCAmelCase : bool = field( default=lowercase__ , metadata={'''help''': '''Whether the csv file has time results or memory results. Defaults to memory results.'''} , ) __UpperCAmelCase : bool = field( default=lowercase__ , metadata={'''help''': '''Disable logarithmic scale when plotting'''} , ) __UpperCAmelCase : bool = field( default=lowercase__ , metadata={ '''help''': '''Whether the csv file has training results or inference results. Defaults to inference results.''' } , ) __UpperCAmelCase : Optional[str] = field( default=lowercase__ , metadata={'''help''': '''Filename under which the plot will be saved. If unused no plot is saved.'''} , ) __UpperCAmelCase : Optional[List[str]] = list_field( default=lowercase__ , metadata={'''help''': '''List of model names that are used instead of the ones in the csv file.'''} ) def UpperCAmelCase_ (__a : Tuple ): """simple docstring""" try: int(__a ) return True except ValueError: return False def UpperCAmelCase_ (__a : Dict ): """simple docstring""" try: float(__a ) return True except ValueError: return False class UpperCAmelCase__ : """simple docstring""" def __init__( self : str ,_a : Tuple ): '''simple docstring''' _a : Optional[int] = args _a : Tuple = defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}} ) with open(self.args.csv_file ,newline='' ) as csv_file: _a : str = csv.DictReader(_a ) for row in reader: _a : Dict = row['model'] self.result_dict[model_name]["bsz"].append(int(row['batch_size'] ) ) self.result_dict[model_name]["seq_len"].append(int(row['sequence_length'] ) ) if can_convert_to_int(row['result'] ): # value is not None _a : Any = int(row['result'] ) elif can_convert_to_float(row['result'] ): # value is not None _a : Tuple = float(row['result'] ) def __lowercase ( self : Tuple ): '''simple docstring''' _a, _a : Dict = plt.subplots() _a : Optional[Any] = 'Time usage' if self.args.is_time else 'Memory usage' _a : Union[str, Any] = title_str + ' for training' if self.args.is_train else title_str + ' for inference' if not self.args.no_log_scale: # set logarithm scales ax.set_xscale('log' ) ax.set_yscale('log' ) for axis in [ax.xaxis, ax.yaxis]: axis.set_major_formatter(ScalarFormatter() ) for model_name_idx, model_name in enumerate(self.result_dict.keys() ): _a : Optional[int] = sorted(set(self.result_dict[model_name]['bsz'] ) ) _a : Dict = sorted(set(self.result_dict[model_name]['seq_len'] ) ) _a : Any = self.result_dict[model_name]['result'] ((_a), (_a)) : List[Any] = ( (batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes) ) _a : Union[str, Any] = ( model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx] ) for inner_loop_value in inner_loop_array: if self.args.plot_along_batch: _a : int = np.asarray( [results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results] ,dtype=_a ,) else: _a : Any = np.asarray( [results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results] ,dtype=np.floataa ,) ((_a), (_a)) : int = ( ('batch_size', 'len') if self.args.plot_along_batch else ('in #tokens', 'bsz') ) _a : Dict = np.asarray(_a ,_a )[: len(_a )] plt.scatter( _a ,_a ,label=F"""{label_model_name} - {inner_loop_label}: {inner_loop_value}""" ) plt.plot(_a ,_a ,'--' ) title_str += F""" {label_model_name} vs.""" _a : str = title_str[:-4] _a : List[str] = 'Time in s' if self.args.is_time else 'Memory in MB' # plot plt.title(_a ) plt.xlabel(_a ) plt.ylabel(_a ) plt.legend() if self.args.figure_png_file is not None: plt.savefig(self.args.figure_png_file ) else: plt.show() def UpperCAmelCase_ (): """simple docstring""" _a : Optional[int] = HfArgumentParser(__a ) _a : Optional[Any] = parser.parse_args_into_dataclasses()[0] _a : Optional[Any] = Plot(args=__a ) plot.plot() if __name__ == "__main__": main()
271
'''simple docstring''' import argparse from typing import List import evaluate import numpy as np import torch from datasets import DatasetDict, load_dataset # New Code # # We'll be using StratifiedKFold for this example from sklearn.model_selection import StratifiedKFold from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to perform Cross Validation, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## __lowerCAmelCase = 1_6 __lowerCAmelCase = 3_2 def UpperCAmelCase_ (__a : Accelerator , __a : DatasetDict , __a : List[int] , __a : List[int] , __a : int = 1_6 ): """simple docstring""" _a : Union[str, Any] = AutoTokenizer.from_pretrained('bert-base-cased' ) _a : str = DatasetDict( { 'train': dataset['train'].select(__a ), 'validation': dataset['train'].select(__a ), 'test': dataset['validation'], } ) def tokenize_function(__a : List[Any] ): # max_length=None => use the model max length (it's actually the default) _a : Optional[int] = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=__a , max_length=__a ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): _a : List[str] = datasets.map( __a , batched=__a , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _a : List[Any] = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(__a : int ): # On TPU it's best to pad everything to the same length or training will be very slow. _a : Dict = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _a : Tuple = 1_6 elif accelerator.mixed_precision != "no": _a : List[Any] = 8 else: _a : List[Any] = None return tokenizer.pad( __a , padding='longest' , max_length=__a , pad_to_multiple_of=__a , return_tensors='pt' , ) # Instantiate dataloaders. _a : Any = DataLoader( tokenized_datasets['train'] , shuffle=__a , collate_fn=__a , batch_size=__a ) _a : Optional[int] = DataLoader( tokenized_datasets['validation'] , shuffle=__a , collate_fn=__a , batch_size=__a ) _a : Optional[Any] = DataLoader( tokenized_datasets['test'] , shuffle=__a , collate_fn=__a , batch_size=__a ) return train_dataloader, eval_dataloader, test_dataloader def UpperCAmelCase_ (__a : Any , __a : Union[str, Any] ): """simple docstring""" _a : Dict = [] # Download the dataset _a : Tuple = load_dataset('glue' , 'mrpc' ) # Create our splits _a : Union[str, Any] = StratifiedKFold(n_splits=int(args.num_folds ) ) # Initialize accelerator _a : Any = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _a : Optional[Any] = config['lr'] _a : Optional[int] = int(config['num_epochs'] ) _a : Dict = int(config['seed'] ) _a : Dict = int(config['batch_size'] ) _a : Optional[int] = evaluate.load('glue' , 'mrpc' ) # If the batch size is too big we use gradient accumulation _a : List[Any] = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: _a : Any = batch_size // MAX_GPU_BATCH_SIZE _a : List[str] = MAX_GPU_BATCH_SIZE set_seed(__a ) # New Code # # Create our folds: _a : int = kfold.split(np.zeros(datasets['train'].num_rows ) , datasets['train']['label'] ) _a : Any = [] # Iterate over them for i, (train_idxs, valid_idxs) in enumerate(__a ): _a, _a, _a : Optional[Any] = get_fold_dataloaders( __a , __a , __a , __a , ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _a : Dict = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=__a ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _a : List[Any] = model.to(accelerator.device ) # Instantiate optimizer _a : List[str] = AdamW(params=model.parameters() , lr=__a ) # Instantiate scheduler _a : List[Any] = get_linear_schedule_with_warmup( optimizer=__a , num_warmup_steps=1_0_0 , num_training_steps=(len(__a ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _a, _a, _a, _a, _a : Union[str, Any] = accelerator.prepare( __a , __a , __a , __a , __a ) # Now we train the model for epoch in range(__a ): model.train() for step, batch in enumerate(__a ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _a : Dict = model(**__a ) _a : int = outputs.loss _a : Any = loss / gradient_accumulation_steps accelerator.backward(__a ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__a ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _a : Union[str, Any] = model(**__a ) _a : Tuple = outputs.logits.argmax(dim=-1 ) _a, _a : Any = accelerator.gather_for_metrics((predictions, batch['labels']) ) metric.add_batch( predictions=__a , references=__a , ) _a : List[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" , __a ) # New Code # # We also run predictions on the test set at the very end _a : Any = [] for step, batch in enumerate(__a ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _a : Tuple = model(**__a ) _a : Dict = outputs.logits _a, _a : Optional[int] = accelerator.gather_for_metrics((predictions, batch['labels']) ) fold_predictions.append(predictions.cpu() ) if i == 0: # We need all of the test predictions test_references.append(references.cpu() ) # Use accelerator.print to print only on the main process. test_predictions.append(torch.cat(__a , dim=0 ) ) # We now need to release all our memory and get rid of the current model, optimizer, etc accelerator.free_memory() # New Code # # Finally we check the accuracy of our folded results: _a : Dict = torch.cat(__a , dim=0 ) _a : Any = torch.stack(__a , dim=0 ).sum(dim=0 ).div(int(args.num_folds ) ).argmax(dim=-1 ) _a : str = metric.compute(predictions=__a , references=__a ) accelerator.print('Average test metrics from all folds:' , __a ) def UpperCAmelCase_ (): """simple docstring""" _a : Any = argparse.ArgumentParser(description='Simple example of training script.' ) parser.add_argument( '--mixed_precision' , type=__a , default=__a , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.' ) # New Code # parser.add_argument('--num_folds' , type=__a , default=3 , help='The number of splits to perform across the dataset' ) _a : Any = parser.parse_args() _a : int = {'lr': 2e-5, 'num_epochs': 3, 'seed': 4_2, 'batch_size': 1_6} training_function(__a , __a ) if __name__ == "__main__": main()
271
1
'''simple docstring''' from __future__ import annotations from collections.abc import Sequence from typing import Literal def UpperCAmelCase_ (__a : str , __a : str ): """simple docstring""" _a : Dict = list(__a ) _a : int = list(__a ) _a : Dict = 0 for i in range(len(__a ) ): if lista[i] != lista[i]: count += 1 _a : Any = '_' if count > 1: return False else: return "".join(__a ) def UpperCAmelCase_ (__a : list[str] ): """simple docstring""" _a : List[str] = [] while True: _a : Any = ['$'] * len(__a ) _a : Optional[int] = [] for i in range(len(__a ) ): for j in range(i + 1 , len(__a ) ): _a : Union[str, Any] = compare_string(binary[i] , binary[j] ) if k is False: _a : Any = '*' _a : int = '*' temp.append('X' ) for i in range(len(__a ) ): if checka[i] == "$": pi.append(binary[i] ) if len(__a ) == 0: return pi _a : List[Any] = list(set(__a ) ) def UpperCAmelCase_ (__a : int , __a : Sequence[float] ): """simple docstring""" _a : Dict = [] for minterm in minterms: _a : str = '' for _ in range(__a ): _a : Optional[int] = str(minterm % 2 ) + string minterm //= 2 temp.append(__a ) return temp def UpperCAmelCase_ (__a : str , __a : str , __a : int ): """simple docstring""" _a : Union[str, Any] = list(__a ) _a : Optional[Any] = list(__a ) _a : int = 0 for i in range(len(__a ) ): if lista[i] != lista[i]: count_n += 1 return count_n == count def UpperCAmelCase_ (__a : list[list[int]] , __a : list[str] ): """simple docstring""" _a : int = [] _a : List[Any] = [0] * len(__a ) for i in range(len(chart[0] ) ): _a : Any = 0 _a : Union[str, Any] = -1 for j in range(len(__a ) ): if chart[j][i] == 1: count += 1 _a : List[Any] = j if count == 1: _a : Any = 1 for i in range(len(__a ) ): if select[i] == 1: for j in range(len(chart[0] ) ): if chart[i][j] == 1: for k in range(len(__a ) ): _a : Dict = 0 temp.append(prime_implicants[i] ) while True: _a : str = 0 _a : Union[str, Any] = -1 _a : Optional[Any] = 0 for i in range(len(__a ) ): _a : List[str] = chart[i].count(1 ) if count_n > max_n: _a : str = count_n _a : int = i if max_n == 0: return temp temp.append(prime_implicants[rem] ) for i in range(len(chart[0] ) ): if chart[rem][i] == 1: for j in range(len(__a ) ): _a : Optional[int] = 0 def UpperCAmelCase_ (__a : list[str] , __a : list[str] ): """simple docstring""" _a : int = [[0 for x in range(len(__a ) )] for x in range(len(__a ) )] for i in range(len(__a ) ): _a : Dict = prime_implicants[i].count('_' ) for j in range(len(__a ) ): if is_for_table(prime_implicants[i] , binary[j] , __a ): _a : Union[str, Any] = 1 return chart def UpperCAmelCase_ (): """simple docstring""" _a : Dict = int(input('Enter the no. of variables\n' ) ) _a : str = [ float(__a ) for x in input( 'Enter the decimal representation of Minterms \'Spaces Separated\'\n' ).split() ] _a : List[Any] = decimal_to_binary(__a , __a ) _a : Tuple = check(__a ) print('Prime Implicants are:' ) print(__a ) _a : Union[str, Any] = prime_implicant_chart(__a , __a ) _a : List[str] = selection(__a , __a ) print('Essential Prime Implicants are:' ) print(__a ) if __name__ == "__main__": import doctest doctest.testmod() main()
271
'''simple docstring''' from __future__ import annotations __lowerCAmelCase = [-1_0, -5, 0, 5, 5.1, 1_1, 1_3, 2_1, 3, 4, -2_1, -1_0, -5, -1, 0] __lowerCAmelCase = [-5, 0, 5, 5.1, 1_1, 1_3, 2_1, -1, 4, -1, -1_0, -5, -1, 0, -1] def UpperCAmelCase_ (__a : list[float] ): """simple docstring""" _a : Optional[int] = [] _a : int = len(__a ) for i in range(__a ): _a : float = -1 for j in range(i + 1 , __a ): if arr[i] < arr[j]: _a : Any = arr[j] break result.append(__a ) return result def UpperCAmelCase_ (__a : list[float] ): """simple docstring""" _a : Tuple = [] for i, outer in enumerate(__a ): _a : float = -1 for inner in arr[i + 1 :]: if outer < inner: _a : Dict = inner break result.append(__a ) return result def UpperCAmelCase_ (__a : list[float] ): """simple docstring""" _a : int = len(__a ) _a : list[float] = [] _a : list[float] = [-1] * arr_size for index in reversed(range(__a ) ): if stack: while stack[-1] <= arr[index]: stack.pop() if not stack: break if stack: _a : Dict = stack[-1] stack.append(arr[index] ) return result if __name__ == "__main__": from doctest import testmod from timeit import timeit testmod() print(next_greatest_element_slow(arr)) print(next_greatest_element_fast(arr)) print(next_greatest_element(arr)) __lowerCAmelCase = ( """from __main__ import arr, next_greatest_element_slow, """ """next_greatest_element_fast, next_greatest_element""" ) print( """next_greatest_element_slow():""", timeit("""next_greatest_element_slow(arr)""", setup=setup), ) print( """next_greatest_element_fast():""", timeit("""next_greatest_element_fast(arr)""", setup=setup), ) print( """ next_greatest_element():""", timeit("""next_greatest_element(arr)""", setup=setup), )
271
1
'''simple docstring''' def UpperCAmelCase_ (__a : str ): """simple docstring""" _a : Optional[int] = '' for ch in key: if ch == " " or ch not in key_no_dups and ch.isalpha(): key_no_dups += ch return key_no_dups def UpperCAmelCase_ (__a : str ): """simple docstring""" _a : Any = [chr(i + 6_5 ) for i in range(2_6 )] # Remove duplicate characters from key _a : List[str] = remove_duplicates(key.upper() ) _a : int = len(__a ) # First fill cipher with key characters _a : Tuple = {alphabet[i]: char for i, char in enumerate(__a )} # Then map remaining characters in alphabet to # the alphabet from the beginning for i in range(len(__a ) , 2_6 ): _a : List[str] = alphabet[i - offset] # Ensure we are not mapping letters to letters previously mapped while char in key: offset -= 1 _a : Dict = alphabet[i - offset] _a : Optional[int] = char return cipher_alphabet def UpperCAmelCase_ (__a : str , __a : dict[str, str] ): """simple docstring""" return "".join(cipher_map.get(__a , __a ) for ch in message.upper() ) def UpperCAmelCase_ (__a : str , __a : dict[str, str] ): """simple docstring""" _a : List[Any] = {v: k for k, v in cipher_map.items()} return "".join(rev_cipher_map.get(__a , __a ) for ch in message.upper() ) def UpperCAmelCase_ (): """simple docstring""" _a : Any = input('Enter message to encode or decode: ' ).strip() _a : Tuple = input('Enter keyword: ' ).strip() _a : str = input('Encipher or decipher? E/D:' ).strip()[0].lower() try: _a : str = {'e': encipher, 'd': decipher}[option] except KeyError: raise KeyError('invalid input option' ) _a : Dict = create_cipher_map(__a ) print(func(__a , __a ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
271
'''simple docstring''' import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home __lowerCAmelCase = HUGGINGFACE_HUB_CACHE __lowerCAmelCase = """config.json""" __lowerCAmelCase = """diffusion_pytorch_model.bin""" __lowerCAmelCase = """diffusion_flax_model.msgpack""" __lowerCAmelCase = """model.onnx""" __lowerCAmelCase = """diffusion_pytorch_model.safetensors""" __lowerCAmelCase = """weights.pb""" __lowerCAmelCase = """https://huggingface.co""" __lowerCAmelCase = default_cache_path __lowerCAmelCase = """diffusers_modules""" __lowerCAmelCase = os.getenv("""HF_MODULES_CACHE""", os.path.join(hf_cache_home, """modules""")) __lowerCAmelCase = ["""fp16""", """non-ema"""] __lowerCAmelCase = """.self_attn"""
271
1
'''simple docstring''' import tempfile import torch from diffusers import IPNDMScheduler from .test_schedulers import SchedulerCommonTest class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : List[Any] = (IPNDMScheduler,) __UpperCAmelCase : Union[str, Any] = (('''num_inference_steps''', 50),) def __lowercase ( self : Any ,**_a : Union[str, Any] ): '''simple docstring''' _a : int = {'num_train_timesteps': 1000} config.update(**_a ) return config def __lowercase ( self : Dict ,_a : Dict=0 ,**_a : List[str] ): '''simple docstring''' _a : int = dict(self.forward_default_kwargs ) _a : Optional[Any] = kwargs.pop('num_inference_steps' ,_a ) _a : List[str] = self.dummy_sample _a : Any = 0.1 * sample _a : Any = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: _a : Tuple = self.get_scheduler_config(**_a ) _a : Dict = scheduler_class(**_a ) scheduler.set_timesteps(_a ) # copy over dummy past residuals _a : Tuple = dummy_past_residuals[:] if time_step is None: _a : Tuple = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(_a ) _a : int = scheduler_class.from_pretrained(_a ) new_scheduler.set_timesteps(_a ) # copy over dummy past residuals _a : Dict = dummy_past_residuals[:] _a : Optional[int] = scheduler.step(_a ,_a ,_a ,**_a ).prev_sample _a : str = new_scheduler.step(_a ,_a ,_a ,**_a ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" _a : Union[str, Any] = scheduler.step(_a ,_a ,_a ,**_a ).prev_sample _a : List[Any] = new_scheduler.step(_a ,_a ,_a ,**_a ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def __lowercase ( self : Optional[Any] ): '''simple docstring''' pass def __lowercase ( self : List[Any] ,_a : Tuple=0 ,**_a : Dict ): '''simple docstring''' _a : Optional[Any] = dict(self.forward_default_kwargs ) _a : str = kwargs.pop('num_inference_steps' ,_a ) _a : Optional[Any] = self.dummy_sample _a : List[Any] = 0.1 * sample _a : Union[str, Any] = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: _a : Optional[Any] = self.get_scheduler_config() _a : Optional[Any] = scheduler_class(**_a ) scheduler.set_timesteps(_a ) # copy over dummy past residuals (must be after setting timesteps) _a : List[str] = dummy_past_residuals[:] if time_step is None: _a : Dict = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(_a ) _a : Dict = scheduler_class.from_pretrained(_a ) # copy over dummy past residuals new_scheduler.set_timesteps(_a ) # copy over dummy past residual (must be after setting timesteps) _a : int = dummy_past_residuals[:] _a : int = scheduler.step(_a ,_a ,_a ,**_a ).prev_sample _a : Optional[int] = new_scheduler.step(_a ,_a ,_a ,**_a ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" _a : Optional[Any] = scheduler.step(_a ,_a ,_a ,**_a ).prev_sample _a : Optional[Any] = new_scheduler.step(_a ,_a ,_a ,**_a ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def __lowercase ( self : Dict ,**_a : List[Any] ): '''simple docstring''' _a : List[Any] = self.scheduler_classes[0] _a : List[str] = self.get_scheduler_config(**_a ) _a : Union[str, Any] = scheduler_class(**_a ) _a : Optional[Any] = 10 _a : int = self.dummy_model() _a : Optional[int] = self.dummy_sample_deter scheduler.set_timesteps(_a ) for i, t in enumerate(scheduler.timesteps ): _a : Dict = model(_a ,_a ) _a : Optional[int] = scheduler.step(_a ,_a ,_a ).prev_sample for i, t in enumerate(scheduler.timesteps ): _a : Any = model(_a ,_a ) _a : str = scheduler.step(_a ,_a ,_a ).prev_sample return sample def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a : str = dict(self.forward_default_kwargs ) _a : List[Any] = kwargs.pop('num_inference_steps' ,_a ) for scheduler_class in self.scheduler_classes: _a : str = self.get_scheduler_config() _a : int = scheduler_class(**_a ) _a : Any = self.dummy_sample _a : Any = 0.1 * sample if num_inference_steps is not None and hasattr(_a ,'set_timesteps' ): scheduler.set_timesteps(_a ) elif num_inference_steps is not None and not hasattr(_a ,'set_timesteps' ): _a : Union[str, Any] = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) _a : int = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] _a : List[str] = dummy_past_residuals[:] _a : str = scheduler.timesteps[5] _a : Dict = scheduler.timesteps[6] _a : str = scheduler.step(_a ,_a ,_a ,**_a ).prev_sample _a : Optional[int] = scheduler.step(_a ,_a ,_a ,**_a ).prev_sample self.assertEqual(output_a.shape ,sample.shape ) self.assertEqual(output_a.shape ,output_a.shape ) _a : Any = scheduler.step(_a ,_a ,_a ,**_a ).prev_sample _a : int = scheduler.step(_a ,_a ,_a ,**_a ).prev_sample self.assertEqual(output_a.shape ,sample.shape ) self.assertEqual(output_a.shape ,output_a.shape ) def __lowercase ( self : int ): '''simple docstring''' for timesteps in [100, 1000]: self.check_over_configs(num_train_timesteps=_a ,time_step=_a ) def __lowercase ( self : Optional[int] ): '''simple docstring''' for t, num_inference_steps in zip([1, 5, 10] ,[10, 50, 100] ): self.check_over_forward(num_inference_steps=_a ,time_step=_a ) def __lowercase ( self : Dict ): '''simple docstring''' _a : Any = self.full_loop() _a : Any = torch.mean(torch.abs(_a ) ) assert abs(result_mean.item() - 254_0529 ) < 10
271
'''simple docstring''' import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class UpperCAmelCase__ : """simple docstring""" def __init__( self : int ,_a : Any ,_a : Optional[int]=2 ,_a : Optional[Any]=True ,_a : Dict=False ,_a : Dict=10 ,_a : Any=3 ,_a : str=32 * 8 ,_a : Optional[int]=32 * 8 ,_a : int=4 ,_a : str=64 ,): '''simple docstring''' _a : Dict = parent _a : Union[str, Any] = batch_size _a : Tuple = is_training _a : List[str] = use_auxiliary_loss _a : Optional[Any] = num_queries _a : str = num_channels _a : List[str] = min_size _a : int = max_size _a : Optional[int] = num_labels _a : List[str] = hidden_dim _a : int = hidden_dim def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : Tuple = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( _a ) _a : Optional[Any] = torch.ones([self.batch_size, self.min_size, self.max_size] ,device=_a ) _a : Union[str, Any] = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] ,device=_a ) > 0.5 ).float() _a : Tuple = (torch.rand((self.batch_size, self.num_labels) ,device=_a ) > 0.5).long() _a : Dict = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : int = MaskaFormerConfig( hidden_size=self.hidden_dim ,) _a : str = self.num_queries _a : Union[str, Any] = self.num_labels _a : Tuple = [1, 1, 1, 1] _a : Dict = self.num_channels _a : str = 64 _a : Tuple = 128 _a : Optional[Any] = self.hidden_dim _a : Union[str, Any] = self.hidden_dim _a : List[Any] = self.hidden_dim return config def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a, _a, _a, _a, _a : Optional[Any] = self.prepare_config_and_inputs() _a : str = {'pixel_values': pixel_values, 'pixel_mask': pixel_mask} return config, inputs_dict def __lowercase ( self : List[str] ,_a : Optional[Any] ,_a : str ): '''simple docstring''' _a : str = output.encoder_hidden_states _a : Any = output.pixel_decoder_hidden_states _a : Optional[Any] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(_a ) ,len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_a ) ,len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_a ) ,config.decoder_layers ) def __lowercase ( self : List[str] ,_a : str ,_a : List[Any] ,_a : Any ,_a : Union[str, Any]=False ): '''simple docstring''' with torch.no_grad(): _a : str = MaskaFormerModel(config=_a ) model.to(_a ) model.eval() _a : Any = model(pixel_values=_a ,pixel_mask=_a ) _a : Optional[Any] = model(_a ,output_hidden_states=_a ) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape ,(self.batch_size, self.num_queries, self.hidden_dim) ,) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(_a ,_a ) def __lowercase ( self : Tuple ,_a : List[Any] ,_a : Union[str, Any] ,_a : Tuple ,_a : List[str] ,_a : Any ): '''simple docstring''' _a : int = MaskaFormerForUniversalSegmentation(config=_a ) model.to(_a ) model.eval() def comm_check_on_output(_a : Any ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape ,(self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) ,) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape ,(self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): _a : Any = model(pixel_values=_a ,pixel_mask=_a ) _a : Optional[int] = model(_a ) comm_check_on_output(_a ) _a : List[str] = model( pixel_values=_a ,pixel_mask=_a ,mask_labels=_a ,class_labels=_a ) comm_check_on_output(_a ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape ,torch.Size([1] ) ) @require_torch class UpperCAmelCase__ ( lowercase__ , lowercase__ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Optional[int] = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () __UpperCAmelCase : Dict = {'''feature-extraction''': MaskaFormerModel} if is_torch_available() else {} __UpperCAmelCase : Dict = False __UpperCAmelCase : Tuple = False __UpperCAmelCase : Dict = False __UpperCAmelCase : List[Any] = False def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : Union[str, Any] = MaskaFormerModelTester(self ) _a : Dict = ConfigTester(self ,config_class=_a ,has_text_modality=_a ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' self.config_tester.run_common_tests() def __lowercase ( self : Optional[int] ): '''simple docstring''' _a, _a : List[str] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(_a ,**_a ,output_hidden_states=_a ) def __lowercase ( self : str ): '''simple docstring''' _a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*_a ) @unittest.skip(reason='Mask2Former does not use inputs_embeds' ) def __lowercase ( self : Any ): '''simple docstring''' pass @unittest.skip(reason='Mask2Former does not have a get_input_embeddings method' ) def __lowercase ( self : str ): '''simple docstring''' pass @unittest.skip(reason='Mask2Former is not a generative model' ) def __lowercase ( self : List[Any] ): '''simple docstring''' pass @unittest.skip(reason='Mask2Former does not use token embeddings' ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' pass @require_torch_multi_gpu @unittest.skip( reason='Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def __lowercase ( self : Dict ): '''simple docstring''' pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def __lowercase ( self : List[Any] ): '''simple docstring''' pass def __lowercase ( self : int ): '''simple docstring''' _a, _a : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : Union[str, Any] = model_class(_a ) _a : List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _a : Optional[Any] = [*signature.parameters.keys()] _a : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] ,_a ) @slow def __lowercase ( self : List[str] ): '''simple docstring''' for model_name in ["facebook/mask2former-swin-small-coco-instance"]: _a : Dict = MaskaFormerModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def __lowercase ( self : List[Any] ): '''simple docstring''' _a : int = (self.model_tester.min_size,) * 2 _a : Any = { 'pixel_values': torch.randn((2, 3, *size) ,device=_a ), 'mask_labels': torch.randn((2, 10, *size) ,device=_a ), 'class_labels': torch.zeros(2 ,10 ,device=_a ).long(), } _a : List[Any] = self.model_tester.get_config() _a : int = MaskaFormerForUniversalSegmentation(_a ).to(_a ) _a : str = model(**_a ) self.assertTrue(outputs.loss is not None ) def __lowercase ( self : List[str] ): '''simple docstring''' _a, _a : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(_a ,**_a ,output_hidden_states=_a ) def __lowercase ( self : int ): '''simple docstring''' _a, _a : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : Any = model_class(_a ).to(_a ) _a : Optional[int] = model(**_a ,output_attentions=_a ) self.assertTrue(outputs.attentions is not None ) def __lowercase ( self : Tuple ): '''simple docstring''' if not self.model_tester.is_training: return _a : List[str] = self.all_model_classes[1] _a, _a, _a, _a, _a : List[str] = self.model_tester.prepare_config_and_inputs() _a : Any = model_class(_a ) model.to(_a ) model.train() _a : Union[str, Any] = model(_a ,mask_labels=_a ,class_labels=_a ).loss loss.backward() def __lowercase ( self : int ): '''simple docstring''' _a : int = self.all_model_classes[1] _a, _a, _a, _a, _a : List[Any] = self.model_tester.prepare_config_and_inputs() _a : str = True _a : str = True _a : List[str] = model_class(_a ).to(_a ) model.train() _a : Optional[int] = model(_a ,mask_labels=_a ,class_labels=_a ) _a : Tuple = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() _a : str = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() _a : Dict = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() _a : List[str] = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=_a ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) __lowerCAmelCase = 1e-4 def UpperCAmelCase_ (): """simple docstring""" _a : int = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_vision @slow class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" @cached_property def __lowercase ( self : Union[str, Any] ): '''simple docstring''' return "facebook/mask2former-swin-small-coco-instance" @cached_property def __lowercase ( self : Any ): '''simple docstring''' return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None def __lowercase ( self : Any ): '''simple docstring''' _a : List[str] = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(_a ) _a : int = self.default_image_processor _a : Tuple = prepare_img() _a : Any = image_processor(_a ,return_tensors='pt' ).to(_a ) _a : Union[str, Any] = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(_a ,(1, 3, 384, 384) ) with torch.no_grad(): _a : Optional[Any] = model(**_a ) _a : List[Any] = torch.tensor( [[-0.2790, -1.0717, -1.1668], [-0.5128, -0.3128, -0.4987], [-0.5832, 0.1971, -0.0197]] ).to(_a ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] ,_a ,atol=_a ) ) _a : str = torch.tensor( [[0.8973, 1.1847, 1.1776], [1.1934, 1.5040, 1.5128], [1.1153, 1.4486, 1.4951]] ).to(_a ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] ,_a ,atol=_a ) ) _a : Any = torch.tensor( [[2.1152, 1.7000, -0.8603], [1.5808, 1.8004, -0.9353], [1.6043, 1.7495, -0.5999]] ).to(_a ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] ,_a ,atol=_a ) ) def __lowercase ( self : Tuple ): '''simple docstring''' _a : List[Any] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(_a ).eval() _a : Optional[Any] = self.default_image_processor _a : List[Any] = prepare_img() _a : str = image_processor(_a ,return_tensors='pt' ).to(_a ) _a : Any = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(_a ,(1, 3, 384, 384) ) with torch.no_grad(): _a : Optional[int] = model(**_a ) # masks_queries_logits _a : Dict = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape ,(1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ) _a : Dict = [ [-8.7839, -9.0056, -8.8121], [-7.4104, -7.0313, -6.5401], [-6.6105, -6.3427, -6.4675], ] _a : Optional[Any] = torch.tensor(_a ).to(_a ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] ,_a ,atol=_a ) ) # class_queries_logits _a : str = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape ,(1, model.config.num_queries, model.config.num_labels + 1) ) _a : str = torch.tensor( [ [1.8324, -8.0835, -4.1922], [0.8450, -9.0050, -3.6053], [0.3045, -7.7293, -3.0275], ] ).to(_a ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] ,_a ,atol=_a ) ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a : Any = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(_a ).eval() _a : Tuple = self.default_image_processor _a : Tuple = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] ,segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] ,return_tensors='pt' ,) _a : str = inputs['pixel_values'].to(_a ) _a : str = [el.to(_a ) for el in inputs['mask_labels']] _a : Dict = [el.to(_a ) for el in inputs['class_labels']] with torch.no_grad(): _a : List[str] = model(**_a ) self.assertTrue(outputs.loss is not None )
271
1
'''simple docstring''' import random import unittest import torch from diffusers import IFInpaintingSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class UpperCAmelCase__ ( lowercase__ , lowercase__ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Tuple = IFInpaintingSuperResolutionPipeline __UpperCAmelCase : List[str] = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''width''', '''height'''} __UpperCAmelCase : str = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS.union({'''original_image'''} ) __UpperCAmelCase : Tuple = PipelineTesterMixin.required_optional_params - {'''latents'''} def __lowercase ( self : str ): '''simple docstring''' return self._get_superresolution_dummy_components() def __lowercase ( self : int ,_a : Any ,_a : int=0 ): '''simple docstring''' if str(_a ).startswith('mps' ): _a : List[Any] = torch.manual_seed(_a ) else: _a : Dict = torch.Generator(device=_a ).manual_seed(_a ) _a : List[str] = floats_tensor((1, 3, 16, 16) ,rng=random.Random(_a ) ).to(_a ) _a : Any = floats_tensor((1, 3, 32, 32) ,rng=random.Random(_a ) ).to(_a ) _a : Optional[Any] = floats_tensor((1, 3, 32, 32) ,rng=random.Random(_a ) ).to(_a ) _a : Any = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'original_image': original_image, 'mask_image': mask_image, 'generator': generator, 'num_inference_steps': 2, 'output_type': 'numpy', } return inputs @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() ,reason='XFormers attention is only available with CUDA and `xformers` installed' ,) def __lowercase ( self : List[Any] ): '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) def __lowercase ( self : Dict ): '''simple docstring''' self._test_save_load_optional_components() @unittest.skipIf(torch_device != 'cuda' ,reason='float16 requires CUDA' ) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' super().test_save_load_floataa(expected_max_diff=1E-1 ) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def __lowercase ( self : str ): '''simple docstring''' self._test_save_load_local() def __lowercase ( self : str ): '''simple docstring''' self._test_inference_batch_single_identical( expected_max_diff=1E-2 ,)
271
'''simple docstring''' import argparse import json from typing import List from ltp import LTP from transformers import BertTokenizer def UpperCAmelCase_ (__a : List[Any] ): """simple docstring""" if ( (cp >= 0x4E_00 and cp <= 0x9F_FF) or (cp >= 0x34_00 and cp <= 0x4D_BF) # or (cp >= 0x2_00_00 and cp <= 0x2_A6_DF) # or (cp >= 0x2_A7_00 and cp <= 0x2_B7_3F) # or (cp >= 0x2_B7_40 and cp <= 0x2_B8_1F) # or (cp >= 0x2_B8_20 and cp <= 0x2_CE_AF) # or (cp >= 0xF9_00 and cp <= 0xFA_FF) or (cp >= 0x2_F8_00 and cp <= 0x2_FA_1F) # ): # return True return False def UpperCAmelCase_ (__a : str ): """simple docstring""" for char in word: _a : Union[str, Any] = ord(__a ) if not _is_chinese_char(__a ): return 0 return 1 def UpperCAmelCase_ (__a : List[str] ): """simple docstring""" _a : Dict = set() for token in tokens: _a : str = len(__a ) > 1 and is_chinese(__a ) if chinese_word: word_set.add(__a ) _a : Optional[Any] = list(__a ) return word_list def UpperCAmelCase_ (__a : List[str] , __a : set() ): """simple docstring""" if not chinese_word_set: return bert_tokens _a : Optional[Any] = max([len(__a ) for w in chinese_word_set] ) _a : Optional[int] = bert_tokens _a, _a : Any = 0, len(__a ) while start < end: _a : Tuple = True if is_chinese(bert_word[start] ): _a : Union[str, Any] = min(end - start , __a ) for i in range(__a , 1 , -1 ): _a : Optional[Any] = ''.join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1 , start + i ): _a : Any = '##' + bert_word[j] _a : Union[str, Any] = start + i _a : int = False break if single_word: start += 1 return bert_word def UpperCAmelCase_ (__a : List[str] , __a : LTP , __a : BertTokenizer ): """simple docstring""" _a : int = [] for i in range(0 , len(__a ) , 1_0_0 ): _a : Union[str, Any] = ltp_tokenizer.seg(lines[i : i + 1_0_0] )[0] _a : Optional[Any] = [get_chinese_word(__a ) for r in res] ltp_res.extend(__a ) assert len(__a ) == len(__a ) _a : str = [] for i in range(0 , len(__a ) , 1_0_0 ): _a : List[str] = bert_tokenizer(lines[i : i + 1_0_0] , add_special_tokens=__a , truncation=__a , max_length=5_1_2 ) bert_res.extend(res['input_ids'] ) assert len(__a ) == len(__a ) _a : List[str] = [] for input_ids, chinese_word in zip(__a , __a ): _a : int = [] for id in input_ids: _a : Optional[int] = bert_tokenizer._convert_id_to_token(__a ) input_tokens.append(__a ) _a : List[str] = add_sub_symbol(__a , __a ) _a : Tuple = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(__a ): if token[:2] == "##": _a : str = token[2:] # save chinese tokens' pos if len(__a ) == 1 and _is_chinese_char(ord(__a ) ): ref_id.append(__a ) ref_ids.append(__a ) assert len(__a ) == len(__a ) return ref_ids def UpperCAmelCase_ (__a : Optional[Any] ): """simple docstring""" with open(args.file_name , 'r' , encoding='utf-8' ) as f: _a : Dict = f.readlines() _a : int = [line.strip() for line in data if len(__a ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' _a : int = LTP(args.ltp ) # faster in GPU device _a : Tuple = BertTokenizer.from_pretrained(args.bert ) _a : int = prepare_ref(__a , __a , __a ) with open(args.save_path , 'w' , encoding='utf-8' ) as f: _a : Optional[Any] = [json.dumps(__a ) + '\n' for ref in ref_ids] f.writelines(__a ) if __name__ == "__main__": __lowerCAmelCase = argparse.ArgumentParser(description="""prepare_chinese_ref""") parser.add_argument( """--file_name""", type=str, default="""./resources/chinese-demo.txt""", help="""file need process, same as training data in lm""", ) parser.add_argument( """--ltp""", type=str, default="""./resources/ltp""", help="""resources for LTP tokenizer, usually a path""" ) parser.add_argument("""--bert""", type=str, default="""./resources/robert""", help="""resources for Bert tokenizer""") parser.add_argument("""--save_path""", type=str, default="""./resources/ref.txt""", help="""path to save res""") __lowerCAmelCase = parser.parse_args() main(args)
271
1
'''simple docstring''' import json import os from pathlib import Path import pytest from datasets.download.download_config import DownloadConfig from datasets.download.download_manager import DownloadManager from datasets.utils.file_utils import hash_url_to_filename __lowerCAmelCase = """http://www.mocksite.com/file1.txt""" __lowerCAmelCase = """\"text\": [\"foo\", \"foo\"]""" __lowerCAmelCase = """6d8ce9aa78a471c7477201efbeabd3bb01ac2e7d100a6dc024ba1608361f90a8""" class UpperCAmelCase__ : """simple docstring""" __UpperCAmelCase : Optional[Any] = 200 __UpperCAmelCase : Optional[int] = {'''Content-Length''': '''100'''} __UpperCAmelCase : Tuple = {} def __lowercase ( self : List[str] ,**_a : Tuple ): '''simple docstring''' return [bytes(_a ,'utf-8' )] def UpperCAmelCase_ (*__a : Optional[Any] , **__a : Any ): """simple docstring""" return MockResponse() @pytest.mark.parametrize('urls_type' , [str, list, dict] ) def UpperCAmelCase_ (__a : Optional[Any] , __a : Tuple , __a : Any ): """simple docstring""" import requests monkeypatch.setattr(__a , 'request' , __a ) _a : List[str] = URL if issubclass(__a , __a ): _a : Optional[Any] = url elif issubclass(__a , __a ): _a : Optional[int] = [url] elif issubclass(__a , __a ): _a : List[str] = {'train': url} _a : Optional[int] = 'dummy' _a : Optional[int] = 'downloads' _a : Dict = tmp_path _a : Tuple = DownloadConfig( cache_dir=os.path.join(__a , __a ) , use_etag=__a , ) _a : List[Any] = DownloadManager(dataset_name=__a , download_config=__a ) _a : Tuple = dl_manager.download(__a ) _a : int = urls for downloaded_paths in [downloaded_paths]: if isinstance(__a , __a ): _a : Dict = [downloaded_paths] _a : Tuple = [urls] elif isinstance(__a , __a ): assert "train" in downloaded_paths.keys() _a : Optional[int] = downloaded_paths.values() _a : Any = urls.values() assert downloaded_paths for downloaded_path, input_url in zip(__a , __a ): assert downloaded_path == dl_manager.downloaded_paths[input_url] _a : List[str] = Path(__a ) _a : Dict = downloaded_path.parts assert parts[-1] == HASH assert parts[-2] == cache_subdir assert downloaded_path.exists() _a : Tuple = downloaded_path.read_text() assert content == CONTENT _a : List[str] = downloaded_path.with_suffix('.json' ) assert metadata_downloaded_path.exists() _a : str = json.loads(metadata_downloaded_path.read_text() ) assert metadata_content == {"url": URL, "etag": None} @pytest.mark.parametrize('paths_type' , [str, list, dict] ) def UpperCAmelCase_ (__a : Optional[Any] , __a : List[Any] , __a : Any ): """simple docstring""" _a : Optional[int] = str(__a ) if issubclass(__a , __a ): _a : Union[str, Any] = filename elif issubclass(__a , __a ): _a : Optional[Any] = [filename] elif issubclass(__a , __a ): _a : Tuple = {'train': filename} _a : Optional[Any] = 'dummy' _a : List[str] = xz_file.parent _a : Union[str, Any] = 'extracted' _a : Tuple = DownloadConfig( cache_dir=__a , use_etag=__a , ) _a : Union[str, Any] = DownloadManager(dataset_name=__a , download_config=__a ) _a : Any = dl_manager.extract(__a ) _a : Any = paths for extracted_paths in [extracted_paths]: if isinstance(__a , __a ): _a : int = [extracted_paths] _a : str = [paths] elif isinstance(__a , __a ): assert "train" in extracted_paths.keys() _a : Any = extracted_paths.values() _a : Union[str, Any] = paths.values() assert extracted_paths for extracted_path, input_path in zip(__a , __a ): assert extracted_path == dl_manager.extracted_paths[input_path] _a : Optional[Any] = Path(__a ) _a : Union[str, Any] = extracted_path.parts assert parts[-1] == hash_url_to_filename(__a , etag=__a ) assert parts[-2] == extracted_subdir assert extracted_path.exists() _a : int = extracted_path.read_text() _a : Tuple = text_file.read_text() assert extracted_file_content == expected_file_content def UpperCAmelCase_ (__a : List[str] , __a : Dict ): """simple docstring""" assert path.endswith('.jsonl' ) for num_items, line in enumerate(__a , start=1 ): _a : str = json.loads(line.decode('utf-8' ) ) assert item.keys() == {"col_1", "col_2", "col_3"} assert num_items == 4 @pytest.mark.parametrize('archive_jsonl' , ['tar_jsonl_path', 'zip_jsonl_path'] ) def UpperCAmelCase_ (__a : Optional[Any] , __a : List[str] ): """simple docstring""" _a : Dict = request.getfixturevalue(__a ) _a : Optional[int] = DownloadManager() for num_jsonl, (path, file) in enumerate(dl_manager.iter_archive(__a ) , start=1 ): _test_jsonl(__a , __a ) assert num_jsonl == 2 @pytest.mark.parametrize('archive_nested_jsonl' , ['tar_nested_jsonl_path', 'zip_nested_jsonl_path'] ) def UpperCAmelCase_ (__a : Optional[Any] , __a : int ): """simple docstring""" _a : Any = request.getfixturevalue(__a ) _a : Any = DownloadManager() for num_tar, (path, file) in enumerate(dl_manager.iter_archive(__a ) , start=1 ): for num_jsonl, (subpath, subfile) in enumerate(dl_manager.iter_archive(__a ) , start=1 ): _test_jsonl(__a , __a ) assert num_tar == 1 assert num_jsonl == 2 def UpperCAmelCase_ (__a : Union[str, Any] ): """simple docstring""" _a : Dict = DownloadManager() for num_file, file in enumerate(dl_manager.iter_files(__a ) , start=1 ): assert os.path.basename(__a ) == ("test.txt" if num_file == 1 else "train.txt") assert num_file == 2
271
'''simple docstring''' import warnings from ...utils import logging from .image_processing_videomae import VideoMAEImageProcessor __lowerCAmelCase = logging.get_logger(__name__) class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" def __init__( self : Tuple ,*_a : List[str] ,**_a : Any ): '''simple docstring''' warnings.warn( 'The class VideoMAEFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use VideoMAEImageProcessor instead.' ,_a ,) super().__init__(*_a ,**_a )
271
1
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCAmelCase = { """configuration_autoformer""": [ """AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """AutoformerConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ """AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """AutoformerForPrediction""", """AutoformerModel""", """AutoformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_autoformer import ( AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_autoformer import ( AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, AutoformerForPrediction, AutoformerModel, AutoformerPreTrainedModel, ) else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
271
'''simple docstring''' from __future__ import annotations from random import choice def UpperCAmelCase_ (__a : str ): """simple docstring""" return choice(__a ) def UpperCAmelCase_ (__a : list[int] , __a : int ): """simple docstring""" _a : Dict = random_pivot(__a ) # partition based on pivot # linear time _a : Optional[int] = [e for e in lst if e < pivot] _a : List[str] = [e for e in lst if e > pivot] # if we get lucky, pivot might be the element we want. # we can easily see this: # small (elements smaller than k) # + pivot (kth element) # + big (elements larger than k) if len(__a ) == k - 1: return pivot # pivot is in elements bigger than k elif len(__a ) < k - 1: return kth_number(__a , k - len(__a ) - 1 ) # pivot is in elements smaller than k else: return kth_number(__a , __a ) if __name__ == "__main__": import doctest doctest.testmod()
271
1
'''simple docstring''' import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": __lowerCAmelCase = argparse.ArgumentParser() parser.add_argument( """--checkpoint_path""", default=None, type=str, required=True, help="""Path to the checkpoint to convert.""" ) parser.add_argument( """--original_config_file""", type=str, required=True, help="""The YAML config file corresponding to the original architecture.""", ) parser.add_argument( """--num_in_channels""", default=None, type=int, help="""The number of input channels. If `None` number of input channels will be automatically inferred.""", ) parser.add_argument( """--image_size""", default=5_1_2, type=int, help=( """The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2""" """ Base. Use 768 for Stable Diffusion v2.""" ), ) parser.add_argument( """--extract_ema""", action="""store_true""", help=( """Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights""" """ or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield""" """ higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.""" ), ) parser.add_argument( """--upcast_attention""", action="""store_true""", help=( """Whether the attention computation should always be upcasted. This is necessary when running stable""" """ diffusion 2.1.""" ), ) parser.add_argument( """--from_safetensors""", action="""store_true""", help="""If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.""", ) parser.add_argument( """--to_safetensors""", action="""store_true""", help="""Whether to store pipeline in safetensors format or not.""", ) parser.add_argument("""--dump_path""", default=None, type=str, required=True, help="""Path to the output model.""") parser.add_argument("""--device""", type=str, help="""Device to use (e.g. cpu, cuda:0, cuda:1, etc.)""") def UpperCAmelCase_ (__a : int ): """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) __lowerCAmelCase = parser.parse_args() __lowerCAmelCase = 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)
271
'''simple docstring''' class UpperCAmelCase__ : """simple docstring""" def __init__( self : Dict ): '''simple docstring''' _a : Dict = {} def __lowercase ( self : Union[str, Any] ): '''simple docstring''' print(self.vertex ) for i in self.vertex: print(_a ,' -> ' ,' -> '.join([str(_a ) for j in self.vertex[i]] ) ) def __lowercase ( self : Dict ,_a : int ,_a : int ): '''simple docstring''' if from_vertex in self.vertex: self.vertex[from_vertex].append(_a ) else: # else make a new vertex _a : int = [to_vertex] def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : Tuple = [False] * len(self.vertex ) # call the recursive helper function for i in range(len(self.vertex ) ): if not visited[i]: self.dfs_recursive(_a ,_a ) def __lowercase ( self : Union[str, Any] ,_a : int ,_a : list ): '''simple docstring''' _a : List[Any] = True print(_a ,end=' ' ) # Recur for all the vertices that are adjacent to this node for i in self.vertex: if not visited[i]: self.dfs_recursive(_a ,_a ) if __name__ == "__main__": __lowerCAmelCase = Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) g.print_graph() print("""DFS:""") g.dfs() # OUTPUT: # 0 -> 1 -> 2 # 1 -> 2 # 2 -> 0 -> 3 # 3 -> 3 # DFS: # 0 1 2 3
271
1
'''simple docstring''' import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class UpperCAmelCase__ : """simple docstring""" def __init__( self : int ,_a : Any ,_a : Optional[int]=2 ,_a : Optional[Any]=True ,_a : Dict=False ,_a : Dict=10 ,_a : Any=3 ,_a : str=32 * 8 ,_a : Optional[int]=32 * 8 ,_a : int=4 ,_a : str=64 ,): '''simple docstring''' _a : Dict = parent _a : Union[str, Any] = batch_size _a : Tuple = is_training _a : List[str] = use_auxiliary_loss _a : Optional[Any] = num_queries _a : str = num_channels _a : List[str] = min_size _a : int = max_size _a : Optional[int] = num_labels _a : List[str] = hidden_dim _a : int = hidden_dim def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : Tuple = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( _a ) _a : Optional[Any] = torch.ones([self.batch_size, self.min_size, self.max_size] ,device=_a ) _a : Union[str, Any] = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] ,device=_a ) > 0.5 ).float() _a : Tuple = (torch.rand((self.batch_size, self.num_labels) ,device=_a ) > 0.5).long() _a : Dict = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : int = MaskaFormerConfig( hidden_size=self.hidden_dim ,) _a : str = self.num_queries _a : Union[str, Any] = self.num_labels _a : Tuple = [1, 1, 1, 1] _a : Dict = self.num_channels _a : str = 64 _a : Tuple = 128 _a : Optional[Any] = self.hidden_dim _a : Union[str, Any] = self.hidden_dim _a : List[Any] = self.hidden_dim return config def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a, _a, _a, _a, _a : Optional[Any] = self.prepare_config_and_inputs() _a : str = {'pixel_values': pixel_values, 'pixel_mask': pixel_mask} return config, inputs_dict def __lowercase ( self : List[str] ,_a : Optional[Any] ,_a : str ): '''simple docstring''' _a : str = output.encoder_hidden_states _a : Any = output.pixel_decoder_hidden_states _a : Optional[Any] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(_a ) ,len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_a ) ,len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_a ) ,config.decoder_layers ) def __lowercase ( self : List[str] ,_a : str ,_a : List[Any] ,_a : Any ,_a : Union[str, Any]=False ): '''simple docstring''' with torch.no_grad(): _a : str = MaskaFormerModel(config=_a ) model.to(_a ) model.eval() _a : Any = model(pixel_values=_a ,pixel_mask=_a ) _a : Optional[Any] = model(_a ,output_hidden_states=_a ) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape ,(self.batch_size, self.num_queries, self.hidden_dim) ,) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(_a ,_a ) def __lowercase ( self : Tuple ,_a : List[Any] ,_a : Union[str, Any] ,_a : Tuple ,_a : List[str] ,_a : Any ): '''simple docstring''' _a : int = MaskaFormerForUniversalSegmentation(config=_a ) model.to(_a ) model.eval() def comm_check_on_output(_a : Any ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape ,(self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) ,) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape ,(self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): _a : Any = model(pixel_values=_a ,pixel_mask=_a ) _a : Optional[int] = model(_a ) comm_check_on_output(_a ) _a : List[str] = model( pixel_values=_a ,pixel_mask=_a ,mask_labels=_a ,class_labels=_a ) comm_check_on_output(_a ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape ,torch.Size([1] ) ) @require_torch class UpperCAmelCase__ ( lowercase__ , lowercase__ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Optional[int] = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () __UpperCAmelCase : Dict = {'''feature-extraction''': MaskaFormerModel} if is_torch_available() else {} __UpperCAmelCase : Dict = False __UpperCAmelCase : Tuple = False __UpperCAmelCase : Dict = False __UpperCAmelCase : List[Any] = False def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : Union[str, Any] = MaskaFormerModelTester(self ) _a : Dict = ConfigTester(self ,config_class=_a ,has_text_modality=_a ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' self.config_tester.run_common_tests() def __lowercase ( self : Optional[int] ): '''simple docstring''' _a, _a : List[str] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(_a ,**_a ,output_hidden_states=_a ) def __lowercase ( self : str ): '''simple docstring''' _a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*_a ) @unittest.skip(reason='Mask2Former does not use inputs_embeds' ) def __lowercase ( self : Any ): '''simple docstring''' pass @unittest.skip(reason='Mask2Former does not have a get_input_embeddings method' ) def __lowercase ( self : str ): '''simple docstring''' pass @unittest.skip(reason='Mask2Former is not a generative model' ) def __lowercase ( self : List[Any] ): '''simple docstring''' pass @unittest.skip(reason='Mask2Former does not use token embeddings' ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' pass @require_torch_multi_gpu @unittest.skip( reason='Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def __lowercase ( self : Dict ): '''simple docstring''' pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def __lowercase ( self : List[Any] ): '''simple docstring''' pass def __lowercase ( self : int ): '''simple docstring''' _a, _a : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : Union[str, Any] = model_class(_a ) _a : List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _a : Optional[Any] = [*signature.parameters.keys()] _a : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] ,_a ) @slow def __lowercase ( self : List[str] ): '''simple docstring''' for model_name in ["facebook/mask2former-swin-small-coco-instance"]: _a : Dict = MaskaFormerModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def __lowercase ( self : List[Any] ): '''simple docstring''' _a : int = (self.model_tester.min_size,) * 2 _a : Any = { 'pixel_values': torch.randn((2, 3, *size) ,device=_a ), 'mask_labels': torch.randn((2, 10, *size) ,device=_a ), 'class_labels': torch.zeros(2 ,10 ,device=_a ).long(), } _a : List[Any] = self.model_tester.get_config() _a : int = MaskaFormerForUniversalSegmentation(_a ).to(_a ) _a : str = model(**_a ) self.assertTrue(outputs.loss is not None ) def __lowercase ( self : List[str] ): '''simple docstring''' _a, _a : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(_a ,**_a ,output_hidden_states=_a ) def __lowercase ( self : int ): '''simple docstring''' _a, _a : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : Any = model_class(_a ).to(_a ) _a : Optional[int] = model(**_a ,output_attentions=_a ) self.assertTrue(outputs.attentions is not None ) def __lowercase ( self : Tuple ): '''simple docstring''' if not self.model_tester.is_training: return _a : List[str] = self.all_model_classes[1] _a, _a, _a, _a, _a : List[str] = self.model_tester.prepare_config_and_inputs() _a : Any = model_class(_a ) model.to(_a ) model.train() _a : Union[str, Any] = model(_a ,mask_labels=_a ,class_labels=_a ).loss loss.backward() def __lowercase ( self : int ): '''simple docstring''' _a : int = self.all_model_classes[1] _a, _a, _a, _a, _a : List[Any] = self.model_tester.prepare_config_and_inputs() _a : str = True _a : str = True _a : List[str] = model_class(_a ).to(_a ) model.train() _a : Optional[int] = model(_a ,mask_labels=_a ,class_labels=_a ) _a : Tuple = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() _a : str = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() _a : Dict = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() _a : List[str] = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=_a ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) __lowerCAmelCase = 1e-4 def UpperCAmelCase_ (): """simple docstring""" _a : int = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_vision @slow class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" @cached_property def __lowercase ( self : Union[str, Any] ): '''simple docstring''' return "facebook/mask2former-swin-small-coco-instance" @cached_property def __lowercase ( self : Any ): '''simple docstring''' return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None def __lowercase ( self : Any ): '''simple docstring''' _a : List[str] = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(_a ) _a : int = self.default_image_processor _a : Tuple = prepare_img() _a : Any = image_processor(_a ,return_tensors='pt' ).to(_a ) _a : Union[str, Any] = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(_a ,(1, 3, 384, 384) ) with torch.no_grad(): _a : Optional[Any] = model(**_a ) _a : List[Any] = torch.tensor( [[-0.2790, -1.0717, -1.1668], [-0.5128, -0.3128, -0.4987], [-0.5832, 0.1971, -0.0197]] ).to(_a ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] ,_a ,atol=_a ) ) _a : str = torch.tensor( [[0.8973, 1.1847, 1.1776], [1.1934, 1.5040, 1.5128], [1.1153, 1.4486, 1.4951]] ).to(_a ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] ,_a ,atol=_a ) ) _a : Any = torch.tensor( [[2.1152, 1.7000, -0.8603], [1.5808, 1.8004, -0.9353], [1.6043, 1.7495, -0.5999]] ).to(_a ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] ,_a ,atol=_a ) ) def __lowercase ( self : Tuple ): '''simple docstring''' _a : List[Any] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(_a ).eval() _a : Optional[Any] = self.default_image_processor _a : List[Any] = prepare_img() _a : str = image_processor(_a ,return_tensors='pt' ).to(_a ) _a : Any = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(_a ,(1, 3, 384, 384) ) with torch.no_grad(): _a : Optional[int] = model(**_a ) # masks_queries_logits _a : Dict = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape ,(1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ) _a : Dict = [ [-8.7839, -9.0056, -8.8121], [-7.4104, -7.0313, -6.5401], [-6.6105, -6.3427, -6.4675], ] _a : Optional[Any] = torch.tensor(_a ).to(_a ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] ,_a ,atol=_a ) ) # class_queries_logits _a : str = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape ,(1, model.config.num_queries, model.config.num_labels + 1) ) _a : str = torch.tensor( [ [1.8324, -8.0835, -4.1922], [0.8450, -9.0050, -3.6053], [0.3045, -7.7293, -3.0275], ] ).to(_a ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] ,_a ,atol=_a ) ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a : Any = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(_a ).eval() _a : Tuple = self.default_image_processor _a : Tuple = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] ,segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] ,return_tensors='pt' ,) _a : str = inputs['pixel_values'].to(_a ) _a : str = [el.to(_a ) for el in inputs['mask_labels']] _a : Dict = [el.to(_a ) for el in inputs['class_labels']] with torch.no_grad(): _a : List[str] = model(**_a ) self.assertTrue(outputs.loss is not None )
271
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = """▁""" __lowerCAmelCase = {"""vocab_file""": """sentencepiece.bpe.model""", """monolingual_vocab_file""": """dict.txt"""} __lowerCAmelCase = { """vocab_file""": { """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model""", }, """monolingual_vocab_file""": { """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt""", }, } __lowerCAmelCase = {"""vinai/bartpho-syllable""": 1_0_2_4} class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : Optional[Any] = VOCAB_FILES_NAMES __UpperCAmelCase : Dict = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Dict = ['''input_ids''', '''attention_mask'''] def __init__( self : str ,_a : str ,_a : Any ,_a : Any="<s>" ,_a : Dict="</s>" ,_a : int="</s>" ,_a : Union[str, Any]="<s>" ,_a : List[Any]="<unk>" ,_a : Optional[Any]="<pad>" ,_a : List[str]="<mask>" ,_a : Optional[Dict[str, Any]] = None ,**_a : int ,): '''simple docstring''' _a : Any = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else mask_token _a : Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_a ,eos_token=_a ,unk_token=_a ,sep_token=_a ,cls_token=_a ,pad_token=_a ,mask_token=_a ,sp_model_kwargs=self.sp_model_kwargs ,**_a ,) _a : Optional[int] = vocab_file _a : Union[str, Any] = monolingual_vocab_file _a : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_a ) ) # Load the reduced vocab # Keep order of special tokens for backward compatibility _a : Union[str, Any] = {} _a : int = 0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(_a ) not in self.fairseq_tokens_to_ids: _a : int = cnt cnt += 1 with open(_a ,'r' ,encoding='utf-8' ) as f: for line in f.readlines(): _a : str = line.strip().split()[0] _a : Tuple = len(self.fairseq_tokens_to_ids ) if str(_a ) not in self.fairseq_tokens_to_ids: _a : List[str] = len(self.fairseq_tokens_to_ids ) _a : Tuple = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : Union[str, Any] ): '''simple docstring''' _a : int = self.__dict__.copy() _a : str = None _a : Optional[Any] = self.sp_model.serialized_model_proto() return state def __setstate__( self : Tuple ,_a : Tuple ): '''simple docstring''' _a : Tuple = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs' ): _a : List[str] = {} _a : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def __lowercase ( self : Dict ,_a : List[int] ,_a : Optional[List[int]] = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _a : Dict = [self.cls_token_id] _a : int = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def __lowercase ( self : int ,_a : List[int] ,_a : Optional[List[int]] = None ,_a : bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a ,token_ids_a=_a ,already_has_special_tokens=_a ) if token_ids_a is None: return [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1, 1] + ([0] * len(_a )) + [1] def __lowercase ( self : Tuple ,_a : List[int] ,_a : Optional[List[int]] = None ): '''simple docstring''' _a : List[str] = [self.sep_token_id] _a : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def __lowercase ( self : Dict ): '''simple docstring''' return len(self.fairseq_ids_to_tokens ) def __lowercase ( self : Dict ): '''simple docstring''' _a : List[str] = {self.convert_ids_to_tokens(_a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __lowercase ( self : Tuple ,_a : str ): '''simple docstring''' return self.sp_model.encode(_a ,out_type=_a ) def __lowercase ( self : Union[str, Any] ,_a : Union[str, Any] ): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def __lowercase ( self : Any ,_a : int ): '''simple docstring''' return self.fairseq_ids_to_tokens[index] def __lowercase ( self : Tuple ,_a : Union[str, Any] ): '''simple docstring''' _a : str = ''.join(_a ).replace(_a ,' ' ).strip() return out_string def __lowercase ( self : Union[str, Any] ,_a : str ,_a : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(_a ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _a : int = os.path.join( _a ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) _a : int = os.path.join( _a ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['monolingual_vocab_file'] ,) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,_a ) elif not os.path.isfile(self.vocab_file ): with open(_a ,'wb' ) as fi: _a : List[Any] = self.sp_model.serialized_model_proto() fi.write(_a ) if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath( _a ) and os.path.isfile(self.monolingual_vocab_file ): copyfile(self.monolingual_vocab_file ,_a ) elif not os.path.isfile(self.monolingual_vocab_file ): with open(_a ,'w' ,encoding='utf-8' ) as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(F"""{str(_a )} \n""" ) return out_vocab_file, out_monolingual_vocab_file
271
1
'''simple docstring''' from ... import PretrainedConfig __lowerCAmelCase = { """sijunhe/nezha-cn-base""": """https://huggingface.co/sijunhe/nezha-cn-base/resolve/main/config.json""", } class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : str = NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP __UpperCAmelCase : str = '''nezha''' def __init__( self : Any ,_a : List[str]=2_1128 ,_a : Union[str, Any]=768 ,_a : Any=12 ,_a : List[str]=12 ,_a : int=3072 ,_a : Tuple="gelu" ,_a : Tuple=0.1 ,_a : str=0.1 ,_a : Tuple=512 ,_a : List[str]=64 ,_a : List[str]=2 ,_a : str=0.02 ,_a : Tuple=1E-12 ,_a : int=0.1 ,_a : Optional[int]=0 ,_a : List[str]=2 ,_a : Any=3 ,_a : List[Any]=True ,**_a : Dict ,): '''simple docstring''' super().__init__(pad_token_id=_a ,bos_token_id=_a ,eos_token_id=_a ,**_a ) _a : Union[str, Any] = vocab_size _a : Tuple = hidden_size _a : Optional[Any] = num_hidden_layers _a : Any = num_attention_heads _a : Union[str, Any] = hidden_act _a : List[Any] = intermediate_size _a : int = hidden_dropout_prob _a : List[str] = attention_probs_dropout_prob _a : str = max_position_embeddings _a : Tuple = max_relative_position _a : int = type_vocab_size _a : Dict = initializer_range _a : Tuple = layer_norm_eps _a : Any = classifier_dropout _a : Dict = use_cache
271
'''simple docstring''' import numpy as np from transformers import BatchFeature from transformers.testing_utils import require_tf, require_torch from .test_feature_extraction_common import FeatureExtractionSavingTestMixin class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = None __UpperCAmelCase : List[Any] = None @property def __lowercase ( self : Dict ): '''simple docstring''' return self.feat_extract_tester.prepare_feat_extract_dict() def __lowercase ( self : str ): '''simple docstring''' _a : Dict = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(_a ,'feature_size' ) ) self.assertTrue(hasattr(_a ,'sampling_rate' ) ) self.assertTrue(hasattr(_a ,'padding_value' ) ) def __lowercase ( self : int ): '''simple docstring''' _a : Any = self.feat_extract_tester.prepare_inputs_for_common() _a : str = self.feature_extraction_class(**self.feat_extract_dict ) _a : int = feat_extract.model_input_names[0] _a : List[Any] = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(_a ) == len(_a ) for x, y in zip(_a ,processed_features[input_name] ) ) ) _a : Any = self.feat_extract_tester.prepare_inputs_for_common(equal_length=_a ) _a : Union[str, Any] = BatchFeature({input_name: speech_inputs} ,tensor_type='np' ) _a : Union[str, Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: _a : Optional[int] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_torch def __lowercase ( self : Any ): '''simple docstring''' _a : List[Any] = self.feat_extract_tester.prepare_inputs_for_common(equal_length=_a ) _a : Dict = self.feature_extraction_class(**self.feat_extract_dict ) _a : int = feat_extract.model_input_names[0] _a : str = BatchFeature({input_name: speech_inputs} ,tensor_type='pt' ) _a : str = processed_features[input_name] if len(batch_features_input.shape ) < 3: _a : str = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_tf def __lowercase ( self : int ): '''simple docstring''' _a : int = self.feat_extract_tester.prepare_inputs_for_common(equal_length=_a ) _a : Dict = self.feature_extraction_class(**self.feat_extract_dict ) _a : Tuple = feat_extract.model_input_names[0] _a : int = BatchFeature({input_name: speech_inputs} ,tensor_type='tf' ) _a : Optional[int] = processed_features[input_name] if len(batch_features_input.shape ) < 3: _a : Optional[Any] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) def __lowercase ( self : Dict ,_a : Any=False ): '''simple docstring''' def _inputs_have_equal_length(_a : Tuple ): _a : Tuple = len(input[0] ) for input_slice in input[1:]: if len(_a ) != length: return False return True def _inputs_are_equal(_a : Optional[Any] ,_a : Union[str, Any] ): if len(_a ) != len(_a ): return False for input_slice_a, input_slice_a in zip(_a ,_a ): if not np.allclose(np.asarray(_a ) ,np.asarray(_a ) ,atol=1E-3 ): return False return True _a : int = self.feature_extraction_class(**self.feat_extract_dict ) _a : Tuple = self.feat_extract_tester.prepare_inputs_for_common(numpify=_a ) _a : Union[str, Any] = feat_extract.model_input_names[0] _a : Tuple = BatchFeature({input_name: speech_inputs} ) _a : str = self.feat_extract_tester.seq_length_diff _a : Dict = self.feat_extract_tester.max_seq_length + pad_diff _a : Dict = self.feat_extract_tester.min_seq_length _a : Optional[Any] = self.feat_extract_tester.batch_size _a : Tuple = self.feat_extract_tester.feature_size # test padding for List[int] + numpy _a : int = feat_extract.pad(_a ,padding=_a ) _a : List[Any] = input_a[input_name] _a : Tuple = feat_extract.pad(_a ,padding='longest' ) _a : Any = input_a[input_name] _a : Optional[Any] = feat_extract.pad(_a ,padding='max_length' ,max_length=len(speech_inputs[-1] ) ) _a : List[str] = input_a[input_name] _a : List[str] = feat_extract.pad(_a ,padding='longest' ,return_tensors='np' ) _a : str = input_a[input_name] # max_length parameter has to be provided when setting `padding="max_length"` with self.assertRaises(_a ): feat_extract.pad(_a ,padding='max_length' )[input_name] _a : int = feat_extract.pad( _a ,padding='max_length' ,max_length=_a ,return_tensors='np' ) _a : Optional[int] = input_a[input_name] self.assertFalse(_inputs_have_equal_length(_a ) ) self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertTrue(_inputs_are_equal(_a ,_a ) ) self.assertTrue(len(input_a[0] ) == pad_min_length ) self.assertTrue(len(input_a[1] ) == pad_min_length + pad_diff ) self.assertTrue(input_a.shape[:2] == (batch_size, len(input_a[0] )) ) self.assertTrue(input_a.shape[:2] == (batch_size, pad_max_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == input_a.shape[2] == feature_size ) # test padding for `pad_to_multiple_of` for List[int] + numpy _a : Tuple = feat_extract.pad(_a ,pad_to_multiple_of=10 ) _a : List[str] = input_a[input_name] _a : str = feat_extract.pad(_a ,padding='longest' ,pad_to_multiple_of=10 ) _a : Tuple = input_a[input_name] _a : Optional[int] = feat_extract.pad( _a ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=_a ) _a : Any = input_a[input_name] _a : Optional[int] = feat_extract.pad( _a ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=_a ,return_tensors='np' ,) _a : Dict = input_a[input_name] self.assertTrue(all(len(_a ) % 10 == 0 for x in input_a ) ) self.assertTrue(_inputs_are_equal(_a ,_a ) ) _a : List[str] = pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10 self.assertTrue(all(len(_a ) == expected_mult_pad_length for x in input_a ) ) self.assertEqual(input_a.shape[:2] ,(batch_size, expected_mult_pad_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == feature_size ) # Check padding value is correct _a : Any = (np.ones(self.feat_extract_tester.feature_size ) * feat_extract.padding_value).sum() self.assertTrue( abs(np.asarray(input_a[0] )[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1E-3 ) self.assertTrue( abs( np.asarray(input_a[1] )[pad_min_length + pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff) ) < 1E-3 ) self.assertTrue( abs( np.asarray(input_a[2] )[pad_min_length + 2 * pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff) ) < 1E-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1E-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length) ) < 1E-3 ) def __lowercase ( self : List[Any] ,_a : Optional[int]=False ): '''simple docstring''' def _inputs_have_equal_length(_a : List[str] ): _a : Union[str, Any] = len(input[0] ) for input_slice in input[1:]: if len(_a ) != length: return False return True def _inputs_are_equal(_a : List[str] ,_a : List[str] ): if len(_a ) != len(_a ): return False for input_slice_a, input_slice_a in zip(_a ,_a ): if not np.allclose(np.asarray(_a ) ,np.asarray(_a ) ,atol=1E-3 ): return False return True _a : Dict = self.feature_extraction_class(**self.feat_extract_dict ) _a : str = self.feat_extract_tester.prepare_inputs_for_common(numpify=_a ) _a : Any = feat_extract.model_input_names[0] _a : List[Any] = BatchFeature({input_name: speech_inputs} ) # truncate to smallest _a : Union[str, Any] = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,truncation=_a ) _a : str = input_a[input_name] _a : List[str] = feat_extract.pad(_a ,padding='max_length' ,max_length=len(speech_inputs[0] ) ) _a : Tuple = input_a[input_name] self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertFalse(_inputs_have_equal_length(_a ) ) # truncate to smallest with np _a : Dict = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ,truncation=_a ,) _a : Any = input_a[input_name] _a : List[Any] = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ) _a : int = input_a[input_name] self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertTrue(input_a.shape[1] == len(speech_inputs[0] ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(_a ) ) # truncate to middle _a : Dict = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=_a ,return_tensors='np' ,) _a : List[Any] = input_a[input_name] _a : Tuple = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=_a ) _a : Tuple = input_a[input_name] _a : Tuple = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,return_tensors='np' ) _a : Dict = input_a[input_name] self.assertTrue(input_a.shape[1] == len(speech_inputs[1] ) ) self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertTrue(_inputs_are_equal(_a ,_a ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(_a ) ) self.assertTrue(len(input_a[-1] ) == len(speech_inputs[-1] ) ) # padding has to be max_length when setting `truncation=True` with self.assertRaises(_a ): feat_extract.pad(_a ,truncation=_a )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(_a ): feat_extract.pad(_a ,padding='longest' ,truncation=_a )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(_a ): feat_extract.pad(_a ,padding='longest' ,truncation=_a )[input_name] # max_length parameter has to be provided when setting `truncation=True` and padding="max_length" with self.assertRaises(_a ): feat_extract.pad(_a ,padding='max_length' ,truncation=_a )[input_name] # test truncation for `pad_to_multiple_of` for List[int] + numpy _a : Optional[Any] = 12 _a : List[Any] = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=_a ,truncation=_a ,) _a : Tuple = input_a[input_name] _a : str = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=_a ,) _a : List[Any] = input_a[input_name] # retrieve expected_length as multiple of pad_to_multiple_of _a : List[Any] = len(speech_inputs[0] ) if expected_length % pad_to_multiple_of != 0: _a : Union[str, Any] = ((len(speech_inputs[0] ) // pad_to_multiple_of) + 1) * pad_to_multiple_of self.assertTrue(len(input_a[0] ) == expected_length ) self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertFalse(_inputs_have_equal_length(_a ) ) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' self._check_padding(numpify=_a ) def __lowercase ( self : Tuple ): '''simple docstring''' self._check_padding(numpify=_a ) def __lowercase ( self : Dict ): '''simple docstring''' self._check_truncation(numpify=_a ) def __lowercase ( self : str ): '''simple docstring''' self._check_truncation(numpify=_a ) @require_torch def __lowercase ( self : Dict ): '''simple docstring''' _a : Any = self.feature_extraction_class(**self.feat_extract_dict ) _a : List[Any] = self.feat_extract_tester.prepare_inputs_for_common() _a : Union[str, Any] = feat_extract.model_input_names[0] _a : Optional[int] = BatchFeature({input_name: speech_inputs} ) _a : List[Any] = feat_extract.pad(_a ,padding='longest' ,return_tensors='np' )[input_name] _a : List[str] = feat_extract.pad(_a ,padding='longest' ,return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1E-2 ) @require_tf def __lowercase ( self : int ): '''simple docstring''' _a : List[str] = self.feature_extraction_class(**self.feat_extract_dict ) _a : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_common() _a : Dict = feat_extract.model_input_names[0] _a : Optional[Any] = BatchFeature({input_name: speech_inputs} ) _a : Dict = feat_extract.pad(_a ,padding='longest' ,return_tensors='np' )[input_name] _a : Any = feat_extract.pad(_a ,padding='longest' ,return_tensors='tf' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_tf.numpy().astype(np.floataa ).sum() ) < 1E-2 ) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : str = self.feat_extract_dict _a : List[Any] = True _a : Optional[int] = self.feature_extraction_class(**_a ) _a : List[Any] = self.feat_extract_tester.prepare_inputs_for_common() _a : Tuple = [len(_a ) for x in speech_inputs] _a : int = feat_extract.model_input_names[0] _a : Optional[Any] = BatchFeature({input_name: speech_inputs} ) _a : str = feat_extract.pad(_a ,padding='longest' ,return_tensors='np' ) self.assertIn('attention_mask' ,_a ) self.assertListEqual(list(processed.attention_mask.shape ) ,list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() ,_a ) def __lowercase ( self : int ): '''simple docstring''' _a : Any = self.feat_extract_dict _a : Tuple = True _a : Optional[int] = self.feature_extraction_class(**_a ) _a : Dict = self.feat_extract_tester.prepare_inputs_for_common() _a : Dict = [len(_a ) for x in speech_inputs] _a : Union[str, Any] = feat_extract.model_input_names[0] _a : Any = BatchFeature({input_name: speech_inputs} ) _a : List[Any] = min(_a ) _a : Dict = feat_extract.pad( _a ,padding='max_length' ,max_length=_a ,truncation=_a ,return_tensors='np' ) self.assertIn('attention_mask' ,_a ) self.assertListEqual( list(processed_pad.attention_mask.shape ) ,[processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() ,[max_length for x in speech_inputs] )
271
1
'''simple docstring''' import gc import unittest from diffusers import FlaxStableDiffusionInpaintPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self : List[str] ): '''simple docstring''' super().tearDown() gc.collect() def __lowercase ( self : List[Any] ): '''simple docstring''' _a : List[str] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/sd2-inpaint/init_image.png' ) _a : Tuple = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png' ) _a : int = 'xvjiarui/stable-diffusion-2-inpainting' _a, _a : Optional[Any] = FlaxStableDiffusionInpaintPipeline.from_pretrained(_a ,safety_checker=_a ) _a : Tuple = 'Face of a yellow cat, high resolution, sitting on a park bench' _a : Optional[int] = jax.random.PRNGKey(0 ) _a : str = 50 _a : Tuple = jax.device_count() _a : List[str] = num_samples * [prompt] _a : Tuple = num_samples * [init_image] _a : Any = num_samples * [mask_image] _a, _a, _a : Any = pipeline.prepare_inputs(_a ,_a ,_a ) # shard inputs and rng _a : List[str] = replicate(_a ) _a : Optional[Any] = jax.random.split(_a ,jax.device_count() ) _a : Optional[int] = shard(_a ) _a : Optional[int] = shard(_a ) _a : Dict = shard(_a ) _a : Dict = pipeline( _a ,_a ,_a ,_a ,_a ,_a ,jit=_a ) _a : Tuple = output.images.reshape(_a ,512 ,512 ,3 ) _a : str = images[0, 253:256, 253:256, -1] _a : Union[str, Any] = jnp.asarray(jax.device_get(image_slice.flatten() ) ) _a : Any = jnp.array( [0.361_1307, 0.3764_9736, 0.375_7408, 0.3821_3953, 0.3929_5167, 0.384_1631, 0.4155_4978, 0.413_7475, 0.421_7084] ) print(F"""output_slice: {output_slice}""" ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2
271
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import KarrasVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : UNetaDModel __UpperCAmelCase : KarrasVeScheduler def __init__( self : Union[str, Any] ,_a : UNetaDModel ,_a : KarrasVeScheduler ): '''simple docstring''' super().__init__() self.register_modules(unet=_a ,scheduler=_a ) @torch.no_grad() def __call__( self : List[Any] ,_a : int = 1 ,_a : int = 50 ,_a : Optional[Union[torch.Generator, List[torch.Generator]]] = None ,_a : Optional[str] = "pil" ,_a : bool = True ,**_a : List[Any] ,): '''simple docstring''' _a : Any = self.unet.config.sample_size _a : Optional[int] = (batch_size, 3, img_size, img_size) _a : Dict = self.unet # sample x_0 ~ N(0, sigma_0^2 * I) _a : Dict = randn_tensor(_a ,generator=_a ,device=self.device ) * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(_a ) for t in self.progress_bar(self.scheduler.timesteps ): # here sigma_t == t_i from the paper _a : Optional[int] = self.scheduler.schedule[t] _a : List[str] = self.scheduler.schedule[t - 1] if t > 0 else 0 # 1. Select temporarily increased noise level sigma_hat # 2. Add new noise to move from sample_i to sample_hat _a, _a : List[Any] = self.scheduler.add_noise_to_input(_a ,_a ,generator=_a ) # 3. Predict the noise residual given the noise magnitude `sigma_hat` # The model inputs and output are adjusted by following eq. (213) in [1]. _a : Optional[int] = (sigma_hat / 2) * model((sample_hat + 1) / 2 ,sigma_hat / 2 ).sample # 4. Evaluate dx/dt at sigma_hat # 5. Take Euler step from sigma to sigma_prev _a : Tuple = self.scheduler.step(_a ,_a ,_a ,_a ) if sigma_prev != 0: # 6. Apply 2nd order correction # The model inputs and output are adjusted by following eq. (213) in [1]. _a : Optional[int] = (sigma_prev / 2) * model((step_output.prev_sample + 1) / 2 ,sigma_prev / 2 ).sample _a : Optional[Any] = self.scheduler.step_correct( _a ,_a ,_a ,_a ,step_output.prev_sample ,step_output['derivative'] ,) _a : Dict = step_output.prev_sample _a : Tuple = (sample / 2 + 0.5).clamp(0 ,1 ) _a : Optional[Any] = sample.cpu().permute(0 ,2 ,3 ,1 ).numpy() if output_type == "pil": _a : List[str] = self.numpy_to_pil(_a ) if not return_dict: return (image,) return ImagePipelineOutput(images=_a )
271
1
'''simple docstring''' __lowerCAmelCase = """ # Transformers installation ! pip install transformers datasets # To install from source instead of the last release, comment the command above and uncomment the following one. # ! pip install git+https://github.com/huggingface/transformers.git """ __lowerCAmelCase = [{"""type""": """code""", """content""": INSTALL_CONTENT}] __lowerCAmelCase = { """{processor_class}""": """FakeProcessorClass""", """{model_class}""": """FakeModelClass""", """{object_class}""": """FakeObjectClass""", }
271
'''simple docstring''' import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version from .. import __version__ from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging __lowerCAmelCase = ( """https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py""" ) __lowerCAmelCase = logging.get_logger(__name__) # pylint: disable=invalid-name def UpperCAmelCase_ (): """simple docstring""" _a : Optional[int] = 'https://pypi.org/pypi/diffusers/json' _a : int = json.loads(request.urlopen(__a ).read() )['releases'].keys() return sorted(__a , key=lambda __a : version.Version(__a ) ) def UpperCAmelCase_ (): """simple docstring""" if HF_MODULES_CACHE in sys.path: return sys.path.append(__a ) os.makedirs(__a , exist_ok=__a ) _a : str = Path(__a ) / '__init__.py' if not init_path.exists(): init_path.touch() def UpperCAmelCase_ (__a : Union[str, os.PathLike] ): """simple docstring""" init_hf_modules() _a : Dict = Path(__a ) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent ) os.makedirs(__a , exist_ok=__a ) _a : Optional[int] = dynamic_module_path / '__init__.py' if not init_path.exists(): init_path.touch() def UpperCAmelCase_ (__a : str ): """simple docstring""" with open(__a , 'r' , encoding='utf-8' ) as f: _a : int = f.read() # Imports of the form `import .xxx` _a : Tuple = re.findall('^\s*import\s+\.(\S+)\s*$' , __a , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall('^\s*from\s+\.(\S+)\s+import' , __a , flags=re.MULTILINE ) # Unique-ify return list(set(__a ) ) def UpperCAmelCase_ (__a : Any ): """simple docstring""" _a : Optional[int] = False _a : Optional[int] = [module_file] _a : List[str] = [] # Let's recurse through all relative imports while not no_change: _a : str = [] for f in files_to_check: new_imports.extend(get_relative_imports(__a ) ) _a : Union[str, Any] = Path(__a ).parent _a : str = [str(module_path / m ) for m in new_imports] _a : Tuple = [f for f in new_import_files if f not in all_relative_imports] _a : Dict = [f"""{f}.py""" for f in new_import_files] _a : List[str] = len(__a ) == 0 all_relative_imports.extend(__a ) return all_relative_imports def UpperCAmelCase_ (__a : Tuple ): """simple docstring""" with open(__a , 'r' , encoding='utf-8' ) as f: _a : Dict = f.read() # Imports of the form `import xxx` _a : Optional[int] = re.findall('^\s*import\s+(\S+)\s*$' , __a , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall('^\s*from\s+(\S+)\s+import' , __a , flags=re.MULTILINE ) # Only keep the top-level module _a : List[str] = [imp.split('.' )[0] for imp in imports if not imp.startswith('.' )] # Unique-ify and test we got them all _a : Optional[int] = list(set(__a ) ) _a : List[str] = [] for imp in imports: try: importlib.import_module(__a ) except ImportError: missing_packages.append(__a ) if len(__a ) > 0: raise ImportError( 'This modeling file requires the following packages that were not found in your environment: ' f"""{', '.join(__a )}. Run `pip install {' '.join(__a )}`""" ) return get_relative_imports(__a ) def UpperCAmelCase_ (__a : Any , __a : str ): """simple docstring""" _a : Any = module_path.replace(os.path.sep , '.' ) _a : Union[str, Any] = importlib.import_module(__a ) if class_name is None: return find_pipeline_class(__a ) return getattr(__a , __a ) def UpperCAmelCase_ (__a : Optional[int] ): """simple docstring""" from ..pipelines import DiffusionPipeline _a : List[str] = dict(inspect.getmembers(__a , inspect.isclass ) ) _a : str = None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , __a ) and cls.__module__.split('.' )[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( f"""Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:""" f""" {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in""" f""" {loaded_module}.""" ) _a : Any = cls return pipeline_class def UpperCAmelCase_ (__a : Union[str, os.PathLike] , __a : str , __a : Optional[Union[str, os.PathLike]] = None , __a : bool = False , __a : bool = False , __a : Optional[Dict[str, str]] = None , __a : Optional[Union[bool, str]] = None , __a : Optional[str] = None , __a : bool = False , ): """simple docstring""" _a : str = str(__a ) _a : Optional[Any] = os.path.join(__a , __a ) if os.path.isfile(__a ): _a : Tuple = module_file_or_url _a : Optional[Any] = 'local' elif pretrained_model_name_or_path.count('/' ) == 0: _a : int = get_diffusers_versions() # cut ".dev0" _a : Any = 'v' + '.'.join(__version__.split('.' )[:3] ) # retrieve github version that matches if revision is None: _a : Any = latest_version if latest_version[1:] in available_versions else 'main' logger.info(f"""Defaulting to latest_version: {revision}.""" ) elif revision in available_versions: _a : Any = f"""v{revision}""" elif revision == "main": _a : Optional[int] = revision else: raise ValueError( f"""`custom_revision`: {revision} does not exist. Please make sure to choose one of""" f""" {', '.join(available_versions + ['main'] )}.""" ) # community pipeline on GitHub _a : Tuple = COMMUNITY_PIPELINES_URL.format(revision=__a , pipeline=__a ) try: _a : Any = cached_download( __a , cache_dir=__a , force_download=__a , proxies=__a , resume_download=__a , local_files_only=__a , use_auth_token=__a , ) _a : List[Any] = 'git' _a : Any = pretrained_model_name_or_path + '.py' except EnvironmentError: logger.error(f"""Could not locate the {module_file} inside {pretrained_model_name_or_path}.""" ) raise else: try: # Load from URL or cache if already cached _a : Optional[Any] = hf_hub_download( __a , __a , cache_dir=__a , force_download=__a , proxies=__a , resume_download=__a , local_files_only=__a , use_auth_token=__a , ) _a : List[Any] = os.path.join('local' , '--'.join(pretrained_model_name_or_path.split('/' ) ) ) except EnvironmentError: logger.error(f"""Could not locate the {module_file} inside {pretrained_model_name_or_path}.""" ) raise # Check we have all the requirements in our environment _a : Optional[int] = check_imports(__a ) # Now we move the module inside our cached dynamic modules. _a : Optional[Any] = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(__a ) _a : Any = Path(__a ) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copy(__a , submodule_path / module_file ) for module_needed in modules_needed: _a : Dict = f"""{module_needed}.py""" shutil.copy(os.path.join(__a , __a ) , submodule_path / module_needed ) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. if isinstance(__a , __a ): _a : Optional[Any] = use_auth_token elif use_auth_token is True: _a : List[Any] = HfFolder.get_token() else: _a : Dict = None _a : int = model_info(__a , revision=__a , token=__a ).sha # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. _a : Optional[int] = submodule_path / commit_hash _a : str = full_submodule + os.path.sep + commit_hash create_dynamic_module(__a ) if not (submodule_path / module_file).exists(): shutil.copy(__a , submodule_path / module_file ) # Make sure we also have every file with relative for module_needed in modules_needed: if not (submodule_path / module_needed).exists(): get_cached_module_file( __a , f"""{module_needed}.py""" , cache_dir=__a , force_download=__a , resume_download=__a , proxies=__a , use_auth_token=__a , revision=__a , local_files_only=__a , ) return os.path.join(__a , __a ) def UpperCAmelCase_ (__a : Union[str, os.PathLike] , __a : str , __a : Optional[str] = None , __a : Optional[Union[str, os.PathLike]] = None , __a : bool = False , __a : bool = False , __a : Optional[Dict[str, str]] = None , __a : Optional[Union[bool, str]] = None , __a : Optional[str] = None , __a : bool = False , **__a : str , ): """simple docstring""" _a : Dict = get_cached_module_file( __a , __a , cache_dir=__a , force_download=__a , resume_download=__a , proxies=__a , use_auth_token=__a , revision=__a , local_files_only=__a , ) return get_class_in_module(__a , final_module.replace('.py' , '' ) )
271
1
'''simple docstring''' def UpperCAmelCase_ (__a : list , __a : list , __a : int ): """simple docstring""" _a : Optional[Any] = len(__a ) _a : int = [[0] * n for i in range(__a )] for i in range(__a ): _a : Tuple = y_points[i] for i in range(2 , __a ): for j in range(__a , __a ): _a : Tuple = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
271
'''simple docstring''' def UpperCAmelCase_ (__a : list , __a : list , __a : int ): """simple docstring""" _a : Optional[Any] = len(__a ) _a : int = [[0] * n for i in range(__a )] for i in range(__a ): _a : Tuple = y_points[i] for i in range(2 , __a ): for j in range(__a , __a ): _a : Tuple = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
271
1
'''simple docstring''' from __future__ import annotations from collections.abc import Callable def UpperCAmelCase_ (__a : Callable[[int | float], int | float] , __a : int | float , __a : int | float , __a : int = 1_0_0 , ): """simple docstring""" _a : Dict = x_start _a : Dict = fnc(__a ) _a : Union[str, Any] = 0.0 for _ in range(__a ): # Approximates small segments of curve as linear and solve # for trapezoidal area _a : List[Any] = (x_end - x_start) / steps + xa _a : Dict = fnc(__a ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step _a : Any = xa _a : Union[str, Any] = fxa return area if __name__ == "__main__": def UpperCAmelCase_ (__a : int ): """simple docstring""" return x**3 + x**2 print("""f(x) = x^3 + x^2""") print("""The area between the curve, x = -5, x = 5 and the x axis is:""") __lowerCAmelCase = 1_0 while i <= 1_0_0_0_0_0: print(f'''with {i} steps: {trapezoidal_area(f, -5, 5, i)}''') i *= 1_0
271
'''simple docstring''' import inspect import os import unittest from pathlib import Path import torch import accelerate from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils.testing import run_command class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Optional[Any] = inspect.getfile(accelerate.test_utils ) __UpperCAmelCase : List[str] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_cli.py'''] ) __UpperCAmelCase : Dict = ['''accelerate''', '''launch'''] __UpperCAmelCase : Dict = Path.home() / '''.cache/huggingface/accelerate''' __UpperCAmelCase : Dict = '''default_config.yaml''' __UpperCAmelCase : Optional[Any] = config_folder / config_file __UpperCAmelCase : Dict = config_folder / '''_default_config.yaml''' __UpperCAmelCase : Any = Path('''tests/test_configs''' ) @classmethod def __lowercase ( cls : int ): '''simple docstring''' if cls.config_path.is_file(): cls.config_path.rename(cls.changed_path ) @classmethod def __lowercase ( cls : List[Any] ): '''simple docstring''' if cls.changed_path.is_file(): cls.changed_path.rename(cls.config_path ) def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : Dict = self.base_cmd if torch.cuda.is_available() and (torch.cuda.device_count() > 1): cmd += ["--multi_gpu"] execute_subprocess_async(cmd + [self.test_file_path] ,env=os.environ.copy() ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' for config in sorted(self.test_config_path.glob('**/*.yaml' ) ): with self.subTest(config_file=_a ): execute_subprocess_async( self.base_cmd + ['--config_file', str(_a ), self.test_file_path] ,env=os.environ.copy() ) def __lowercase ( self : Optional[int] ): '''simple docstring''' execute_subprocess_async(['accelerate', 'test'] ,env=os.environ.copy() ) class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Optional[Any] = '''test-tpu''' __UpperCAmelCase : Any = '''us-central1-a''' __UpperCAmelCase : List[Any] = '''ls''' __UpperCAmelCase : Any = ['''accelerate''', '''tpu-config'''] __UpperCAmelCase : Dict = '''cd /usr/share''' __UpperCAmelCase : Any = '''tests/test_samples/test_command_file.sh''' __UpperCAmelCase : List[Any] = '''Running gcloud compute tpus tpu-vm ssh''' def __lowercase ( self : Dict ): '''simple docstring''' _a : Optional[Any] = run_command( self.cmd + ['--command', self.command, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug'] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" ,_a ,) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Any = run_command( self.cmd + [ '--config_file', 'tests/test_configs/0_12_0.yaml', '--command', self.command, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug', ] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" ,_a ,) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Optional[int] = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--debug'] ,return_stdout=_a ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_a ,) def __lowercase ( self : int ): '''simple docstring''' _a : Optional[Any] = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--command', self.command, '--debug'] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" ,_a ,) def __lowercase ( self : str ): '''simple docstring''' _a : List[str] = run_command( self.cmd + [ '--config_file', 'tests/test_configs/latest.yaml', '--command', self.command, '--command', 'echo "Hello World"', '--debug', ] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo \"Hello World\" --worker all""" ,_a ,) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : Any = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--command_file', self.command_file, '--debug'] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_a ,) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : Union[str, Any] = run_command( self.cmd + [ '--config_file', 'tests/test_configs/0_12_0.yaml', '--command_file', self.command_file, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug', ] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_a ,) def __lowercase ( self : Any ): '''simple docstring''' _a : Optional[int] = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--install_accelerate', '--debug'] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_a ,) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Optional[int] = run_command( self.cmd + [ '--config_file', 'tests/test_configs/latest.yaml', '--install_accelerate', '--accelerate_version', '12.0.0', '--debug', ] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_a ,)
271
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __lowerCAmelCase = { """configuration_bloom""": ["""BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BloomConfig""", """BloomOnnxConfig"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = ["""BloomTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ """BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST""", """BloomForCausalLM""", """BloomModel""", """BloomPreTrainedModel""", """BloomForSequenceClassification""", """BloomForTokenClassification""", """BloomForQuestionAnswering""", ] if TYPE_CHECKING: from .configuration_bloom import BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP, BloomConfig, BloomOnnxConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bloom_fast import BloomTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bloom import ( BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST, BloomForCausalLM, BloomForQuestionAnswering, BloomForSequenceClassification, BloomForTokenClassification, BloomModel, BloomPreTrainedModel, ) else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
271
'''simple docstring''' from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar __lowerCAmelCase = TypeVar("""T""") class UpperCAmelCase__ ( Generic[T] ): """simple docstring""" def __init__( self : Tuple ,_a : T ): '''simple docstring''' _a : List[str] = data _a : Node[T] | None = None def __str__( self : Dict ): '''simple docstring''' return F"""{self.data}""" class UpperCAmelCase__ ( Generic[T] ): """simple docstring""" def __init__( self : Optional[int] ): '''simple docstring''' _a : Node[T] | None = None def __iter__( self : str ): '''simple docstring''' _a : Tuple = self.top while node: yield node.data _a : int = node.next def __str__( self : str ): '''simple docstring''' return "->".join([str(_a ) for item in self] ) def __len__( self : Optional[Any] ): '''simple docstring''' return len(tuple(iter(self ) ) ) def __lowercase ( self : str ): '''simple docstring''' return self.top is None def __lowercase ( self : List[Any] ,_a : T ): '''simple docstring''' _a : int = Node(_a ) if not self.is_empty(): _a : Optional[Any] = self.top _a : List[str] = node def __lowercase ( self : Tuple ): '''simple docstring''' if self.is_empty(): raise IndexError('pop from empty stack' ) assert isinstance(self.top ,_a ) _a : List[Any] = self.top _a : int = self.top.next return pop_node.data def __lowercase ( self : List[str] ): '''simple docstring''' if self.is_empty(): raise IndexError('peek from empty stack' ) assert self.top is not None return self.top.data def __lowercase ( self : List[str] ): '''simple docstring''' _a : Optional[int] = None if __name__ == "__main__": from doctest import testmod testmod()
271
1
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = { """Salesforce/blip-vqa-base""": """https://huggingface.co/Salesforce/blip-vqa-base/resolve/main/config.json""", """Salesforce/blip-vqa-capfit-large""": ( """https://huggingface.co/Salesforce/blip-vqa-base-capfit/resolve/main/config.json""" ), """Salesforce/blip-image-captioning-base""": ( """https://huggingface.co/Salesforce/blip-image-captioning-base/resolve/main/config.json""" ), """Salesforce/blip-image-captioning-large""": ( """https://huggingface.co/Salesforce/blip-image-captioning-large/resolve/main/config.json""" ), """Salesforce/blip-itm-base-coco""": """https://huggingface.co/Salesforce/blip-itm-base-coco/resolve/main/config.json""", """Salesforce/blip-itm-large-coco""": """https://huggingface.co/Salesforce/blip-itm-large-coco/resolve/main/config.json""", """Salesforce/blip-itm-base-flikr""": """https://huggingface.co/Salesforce/blip-itm-base-flikr/resolve/main/config.json""", """Salesforce/blip-itm-large-flikr""": ( """https://huggingface.co/Salesforce/blip-itm-large-flikr/resolve/main/config.json""" ), } class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : Any = '''blip_text_model''' def __init__( self : Any ,_a : List[Any]=3_0524 ,_a : Optional[Any]=768 ,_a : Dict=768 ,_a : Optional[int]=3072 ,_a : str=768 ,_a : Union[str, Any]=12 ,_a : List[str]=8 ,_a : str=512 ,_a : List[Any]="gelu" ,_a : Any=1E-12 ,_a : Tuple=0.0 ,_a : Union[str, Any]=0.0 ,_a : Tuple=0.02 ,_a : Union[str, Any]=3_0522 ,_a : str=2 ,_a : List[str]=0 ,_a : Tuple=102 ,_a : List[Any]=True ,_a : Any=True ,**_a : List[Any] ,): '''simple docstring''' super().__init__( pad_token_id=_a ,bos_token_id=_a ,eos_token_id=_a ,sep_token_id=_a ,**_a ,) _a : Any = vocab_size _a : str = hidden_size _a : Any = encoder_hidden_size _a : Optional[int] = intermediate_size _a : Any = projection_dim _a : Any = hidden_dropout_prob _a : Union[str, Any] = num_hidden_layers _a : List[str] = num_attention_heads _a : int = max_position_embeddings _a : Dict = layer_norm_eps _a : Tuple = hidden_act _a : Tuple = initializer_range _a : List[str] = attention_probs_dropout_prob _a : str = is_decoder _a : Tuple = use_cache @classmethod def __lowercase ( cls : int ,_a : Union[str, os.PathLike] ,**_a : Tuple ): '''simple docstring''' cls._set_token_in_kwargs(_a ) _a, _a : Any = cls.get_config_dict(_a ,**_a ) # get the text config dict if we are loading from BlipConfig if config_dict.get('model_type' ) == "blip": _a : Tuple = config_dict['text_config'] if "model_type" in config_dict and hasattr(cls ,'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(_a ,**_a ) class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : List[Any] = '''blip_vision_model''' def __init__( self : Tuple ,_a : List[Any]=768 ,_a : List[str]=3072 ,_a : Union[str, Any]=512 ,_a : Any=12 ,_a : Tuple=12 ,_a : Any=384 ,_a : Tuple=16 ,_a : Any="gelu" ,_a : Dict=1E-5 ,_a : int=0.0 ,_a : Union[str, Any]=1E-10 ,**_a : List[Any] ,): '''simple docstring''' super().__init__(**_a ) _a : Tuple = hidden_size _a : str = intermediate_size _a : Tuple = projection_dim _a : Union[str, Any] = num_hidden_layers _a : Optional[Any] = num_attention_heads _a : int = patch_size _a : List[Any] = image_size _a : int = initializer_range _a : str = attention_dropout _a : Union[str, Any] = layer_norm_eps _a : List[str] = hidden_act @classmethod def __lowercase ( cls : Tuple ,_a : Union[str, os.PathLike] ,**_a : int ): '''simple docstring''' cls._set_token_in_kwargs(_a ) _a, _a : List[str] = cls.get_config_dict(_a ,**_a ) # get the vision config dict if we are loading from BlipConfig if config_dict.get('model_type' ) == "blip": _a : List[Any] = config_dict['vision_config'] if "model_type" in config_dict and hasattr(cls ,'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(_a ,**_a ) class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : List[Any] = '''blip''' __UpperCAmelCase : Dict = True def __init__( self : Dict ,_a : Optional[Any]=None ,_a : List[str]=None ,_a : Any=512 ,_a : Optional[Any]=2.6592 ,_a : Optional[int]=256 ,**_a : Optional[int] ,): '''simple docstring''' super().__init__(**_a ) if text_config is None: _a : Dict = {} logger.info('`text_config` is `None`. Initializing the `BlipTextConfig` with default values.' ) if vision_config is None: _a : Any = {} logger.info('`vision_config` is `None`. Initializing the `BlipVisionConfig` with default values.' ) _a : Union[str, Any] = BlipTextConfig(**_a ) _a : Union[str, Any] = BlipVisionConfig(**_a ) _a : int = self.vision_config.hidden_size _a : Tuple = projection_dim _a : int = logit_scale_init_value _a : List[Any] = 1.0 _a : Any = 0.02 _a : Optional[int] = image_text_hidden_size @classmethod def __lowercase ( cls : str ,_a : BlipTextConfig ,_a : BlipVisionConfig ,**_a : Optional[int] ): '''simple docstring''' return cls(text_config=text_config.to_dict() ,vision_config=vision_config.to_dict() ,**_a ) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : Dict = copy.deepcopy(self.__dict__ ) _a : int = self.text_config.to_dict() _a : Tuple = self.vision_config.to_dict() _a : int = self.__class__.model_type return output
271
'''simple docstring''' import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" @property def __lowercase ( self : List[str] ): '''simple docstring''' torch.manual_seed(0 ) _a : int = UNetaDModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=3 ,out_channels=3 ,down_block_types=('DownBlock2D', 'AttnDownBlock2D') ,up_block_types=('AttnUpBlock2D', 'UpBlock2D') ,) return model def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a : str = self.dummy_uncond_unet _a : int = PNDMScheduler() _a : str = PNDMPipeline(unet=_a ,scheduler=_a ) pndm.to(_a ) pndm.set_progress_bar_config(disable=_a ) _a : Optional[int] = torch.manual_seed(0 ) _a : Optional[Any] = pndm(generator=_a ,num_inference_steps=20 ,output_type='numpy' ).images _a : List[str] = torch.manual_seed(0 ) _a : Any = pndm(generator=_a ,num_inference_steps=20 ,output_type='numpy' ,return_dict=_a )[0] _a : List[Any] = image[0, -3:, -3:, -1] _a : Any = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _a : List[Any] = np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self : Tuple ): '''simple docstring''' _a : List[str] = 'google/ddpm-cifar10-32' _a : str = UNetaDModel.from_pretrained(_a ) _a : Union[str, Any] = PNDMScheduler() _a : Tuple = PNDMPipeline(unet=_a ,scheduler=_a ) pndm.to(_a ) pndm.set_progress_bar_config(disable=_a ) _a : str = torch.manual_seed(0 ) _a : Optional[Any] = pndm(generator=_a ,output_type='numpy' ).images _a : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _a : Tuple = np.array([0.1564, 0.1_4645, 0.1406, 0.1_4715, 0.1_2425, 0.1_4045, 0.1_3115, 0.1_2175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
271
1
'''simple docstring''' from collections import deque class UpperCAmelCase__ : """simple docstring""" def __init__( self : Tuple ,_a : str ,_a : int ,_a : int ): '''simple docstring''' _a : Any = process_name # process name _a : Union[str, Any] = arrival_time # arrival time of the process # completion time of finished process or last interrupted time _a : Union[str, Any] = arrival_time _a : Union[str, Any] = burst_time # remaining burst time _a : Optional[Any] = 0 # total time of the process wait in ready queue _a : Tuple = 0 # time from arrival time to completion time class UpperCAmelCase__ : """simple docstring""" def __init__( self : Dict ,_a : int ,_a : list[int] ,_a : deque[Process] ,_a : int ,): '''simple docstring''' _a : Dict = number_of_queues # time slice of queues that round robin algorithm applied _a : List[Any] = time_slices # unfinished process is in this ready_queue _a : Dict = queue # current time _a : Any = current_time # finished process is in this sequence queue _a : deque[Process] = deque() def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a : Optional[Any] = [] for i in range(len(self.finish_queue ) ): sequence.append(self.finish_queue[i].process_name ) return sequence def __lowercase ( self : Union[str, Any] ,_a : list[Process] ): '''simple docstring''' _a : Union[str, Any] = [] for i in range(len(_a ) ): waiting_times.append(queue[i].waiting_time ) return waiting_times def __lowercase ( self : List[Any] ,_a : list[Process] ): '''simple docstring''' _a : Optional[Any] = [] for i in range(len(_a ) ): turnaround_times.append(queue[i].turnaround_time ) return turnaround_times def __lowercase ( self : Tuple ,_a : list[Process] ): '''simple docstring''' _a : Optional[Any] = [] for i in range(len(_a ) ): completion_times.append(queue[i].stop_time ) return completion_times def __lowercase ( self : Dict ,_a : deque[Process] ): '''simple docstring''' return [q.burst_time for q in queue] def __lowercase ( self : Optional[Any] ,_a : Process ): '''simple docstring''' process.waiting_time += self.current_time - process.stop_time return process.waiting_time def __lowercase ( self : List[str] ,_a : deque[Process] ): '''simple docstring''' _a : deque[Process] = deque() # sequence deque of finished process while len(_a ) != 0: _a : List[str] = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of current process self.update_waiting_time(_a ) # update current time self.current_time += cp.burst_time # finish the process and set the process's burst-time 0 _a : Dict = 0 # set the process's turnaround time because it is finished _a : List[Any] = self.current_time - cp.arrival_time # set the completion time _a : int = self.current_time # add the process to queue that has finished queue finished.append(_a ) self.finish_queue.extend(_a ) # add finished process to finish queue # FCFS will finish all remaining processes return finished def __lowercase ( self : int ,_a : deque[Process] ,_a : int ): '''simple docstring''' _a : deque[Process] = deque() # sequence deque of terminated process # just for 1 cycle and unfinished processes will go back to queue for _ in range(len(_a ) ): _a : Optional[int] = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of unfinished processes self.update_waiting_time(_a ) # if the burst time of process is bigger than time-slice if cp.burst_time > time_slice: # use CPU for only time-slice self.current_time += time_slice # update remaining burst time cp.burst_time -= time_slice # update end point time _a : str = self.current_time # locate the process behind the queue because it is not finished ready_queue.append(_a ) else: # use CPU for remaining burst time self.current_time += cp.burst_time # set burst time 0 because the process is finished _a : Tuple = 0 # set the finish time _a : Optional[int] = self.current_time # update the process' turnaround time because it is finished _a : int = self.current_time - cp.arrival_time # add the process to queue that has finished queue finished.append(_a ) self.finish_queue.extend(_a ) # add finished process to finish queue # return finished processes queue and remaining processes queue return finished, ready_queue def __lowercase ( self : Union[str, Any] ): '''simple docstring''' for i in range(self.number_of_queues - 1 ): _a, _a : Dict = self.round_robin( self.ready_queue ,self.time_slices[i] ) # the last queue has first_come_first_served algorithm self.first_come_first_served(self.ready_queue ) return self.finish_queue if __name__ == "__main__": import doctest __lowerCAmelCase = Process("""P1""", 0, 5_3) __lowerCAmelCase = Process("""P2""", 0, 1_7) __lowerCAmelCase = Process("""P3""", 0, 6_8) __lowerCAmelCase = Process("""P4""", 0, 2_4) __lowerCAmelCase = 3 __lowerCAmelCase = [1_7, 2_5] __lowerCAmelCase = deque([Pa, Pa, Pa, Pa]) if len(time_slices) != number_of_queues - 1: raise SystemExit(0) doctest.testmod(extraglobs={"""queue""": deque([Pa, Pa, Pa, Pa])}) __lowerCAmelCase = Process("""P1""", 0, 5_3) __lowerCAmelCase = Process("""P2""", 0, 1_7) __lowerCAmelCase = Process("""P3""", 0, 6_8) __lowerCAmelCase = Process("""P4""", 0, 2_4) __lowerCAmelCase = 3 __lowerCAmelCase = [1_7, 2_5] __lowerCAmelCase = deque([Pa, Pa, Pa, Pa]) __lowerCAmelCase = MLFQ(number_of_queues, time_slices, queue, 0) __lowerCAmelCase = mlfq.multi_level_feedback_queue() # print total waiting times of processes(P1, P2, P3, P4) print( f'''waiting time:\ \t\t\t{MLFQ.calculate_waiting_time(mlfq, [Pa, Pa, Pa, Pa])}''' ) # print completion times of processes(P1, P2, P3, P4) print( f'''completion time:\ \t\t{MLFQ.calculate_completion_time(mlfq, [Pa, Pa, Pa, Pa])}''' ) # print total turnaround times of processes(P1, P2, P3, P4) print( f'''turnaround time:\ \t\t{MLFQ.calculate_turnaround_time(mlfq, [Pa, Pa, Pa, Pa])}''' ) # print sequence of finished processes print( f'''sequence of finished processes:\ {mlfq.calculate_sequence_of_finish_queue()}''' )
271
'''simple docstring''' import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow __lowerCAmelCase = logging.getLogger() @unittest.skip('''Temporarily disable the doc tests.''' ) @require_torch @require_tf @slow class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self : str ,_a : Path ,_a : Union[str, None] = None ,_a : Union[List[str], None] = None ,_a : Union[str, List[str], None] = None ,_a : bool = True ,): '''simple docstring''' _a : Optional[int] = [file for file in os.listdir(_a ) if os.path.isfile(os.path.join(_a ,_a ) )] if identifier is not None: _a : List[str] = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(_a ,_a ): for n_ in n_identifier: _a : Tuple = [file for file in files if n_ not in file] else: _a : Optional[Any] = [file for file in files if n_identifier not in file] _a : List[str] = ignore_files or [] ignore_files.append('__init__.py' ) _a : Tuple = [file for file in files if file not in ignore_files] for file in files: # Open all files print('Testing' ,_a ) if only_modules: _a : Any = file.split('.' )[0] try: _a : List[str] = getattr(_a ,_a ) _a : int = doctest.DocTestSuite(_a ) _a : Any = unittest.TextTestRunner().run(_a ) self.assertIs(len(result.failures ) ,0 ) except AttributeError: logger.info(F"""{module_identifier} is not a module.""" ) else: _a : Union[str, Any] = doctest.testfile(str('..' / directory / file ) ,optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed ,0 ) def __lowercase ( self : Any ): '''simple docstring''' _a : int = Path('src/transformers' ) _a : List[Any] = 'modeling' _a : Optional[Any] = [ 'modeling_ctrl.py', 'modeling_tf_ctrl.py', ] self.analyze_directory(_a ,identifier=_a ,ignore_files=_a ) def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : Optional[Any] = Path('src/transformers' ) _a : Optional[Any] = 'tokenization' self.analyze_directory(_a ,identifier=_a ) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Dict = Path('src/transformers' ) _a : str = 'configuration' self.analyze_directory(_a ,identifier=_a ) def __lowercase ( self : Any ): '''simple docstring''' _a : Tuple = Path('src/transformers' ) _a : List[Any] = ['configuration', 'modeling', 'tokenization'] self.analyze_directory(_a ,n_identifier=_a ) def __lowercase ( self : Tuple ): '''simple docstring''' _a : List[Any] = Path('docs/source' ) _a : List[str] = ['favicon.ico'] self.analyze_directory(_a ,ignore_files=_a ,only_modules=_a )
271
1
'''simple docstring''' import random import timeit from functools import wraps from typing import Callable, Optional from ..configuration_utils import PretrainedConfig from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING from ..utils import is_pyanvml_available, is_tf_available, logging from .benchmark_utils import ( Benchmark, Memory, MemorySummary, measure_peak_memory_cpu, start_memory_tracing, stop_memory_tracing, ) if is_tf_available(): import tensorflow as tf from tensorflow.python.framework.errors_impl import ResourceExhaustedError from .benchmark_args_tf import TensorFlowBenchmarkArguments if is_pyanvml_available(): import pyanvml.pyanvml as nvml __lowerCAmelCase = logging.get_logger(__name__) def UpperCAmelCase_ (__a : bool , __a : bool ): """simple docstring""" def run_func(__a : int ): @wraps(__a ) def run_in_eager_mode(*__a : Optional[Any] , **__a : Optional[int] ): return func(*__a , **__a ) @wraps(__a ) @tf.function(experimental_compile=__a ) def run_in_graph_mode(*__a : Any , **__a : Optional[int] ): return func(*__a , **__a ) if do_eager_mode is True: if use_xla is not False: raise ValueError( 'Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`.' ) return run_in_eager_mode else: return run_in_graph_mode return run_func def UpperCAmelCase_ (__a : int , __a : int , __a : int ): """simple docstring""" _a : List[str] = random.Random() _a : Any = [rng.randint(0 , vocab_size - 1 ) for i in range(batch_size * sequence_length )] return tf.constant(__a , shape=(batch_size, sequence_length) , dtype=tf.intaa ) class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : TensorFlowBenchmarkArguments __UpperCAmelCase : PretrainedConfig __UpperCAmelCase : str = "TensorFlow" @property def __lowercase ( self : Any ): '''simple docstring''' return tf.__version__ def __lowercase ( self : int ,_a : str ,_a : int ,_a : int ): '''simple docstring''' _a : Dict = self.args.strategy if strategy is None: raise ValueError('A device strategy has to be initialized before using TensorFlow.' ) _a : int = self._prepare_inference_func(_a ,_a ,_a ) return self._measure_speed(_inference ) def __lowercase ( self : Optional[Any] ,_a : str ,_a : int ,_a : int ): '''simple docstring''' _a : int = self.args.strategy if strategy is None: raise ValueError('A device strategy has to be initialized before using TensorFlow.' ) _a : Any = self._prepare_train_func(_a ,_a ,_a ) return self._measure_speed(_train ) def __lowercase ( self : int ,_a : str ,_a : int ,_a : int ): '''simple docstring''' if self.args.is_gpu: tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] ,_a ) _a : Optional[Any] = self.args.strategy if strategy is None: raise ValueError('A device strategy has to be initialized before using TensorFlow.' ) _a : Optional[int] = self._prepare_inference_func(_a ,_a ,_a ) return self._measure_memory(_inference ) def __lowercase ( self : Union[str, Any] ,_a : str ,_a : int ,_a : int ): '''simple docstring''' if self.args.is_gpu: tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] ,_a ) _a : Optional[Any] = self.args.strategy if strategy is None: raise ValueError('A device strategy has to be initialized before using TensorFlow.' ) _a : Optional[int] = self._prepare_train_func(_a ,_a ,_a ) return self._measure_memory(_train ) def __lowercase ( self : Any ,_a : str ,_a : int ,_a : int ): '''simple docstring''' _a : Tuple = self.config_dict[model_name] if self.args.fpaa: raise NotImplementedError('Mixed precision is currently not supported.' ) _a : Optional[Any] = ( hasattr(_a ,'architectures' ) and isinstance(config.architectures ,_a ) and len(config.architectures ) > 0 ) if not self.args.only_pretrain_model and has_model_class_in_config: try: _a : str = 'TF' + config.architectures[0] # prepend 'TF' for tensorflow model _a : Dict = __import__('transformers' ,fromlist=[model_class] ) _a : str = getattr(_a ,_a ) _a : Optional[Any] = model_cls(_a ) except ImportError: raise ImportError( F"""{model_class} does not exist. If you just want to test the pretrained model, you might want to""" ' set `--only_pretrain_model` or `args.only_pretrain_model=True`.' ) else: _a : Any = TF_MODEL_MAPPING[config.__class__](_a ) # encoder-decoder has vocab size saved differently _a : Optional[Any] = config.vocab_size if hasattr(_a ,'vocab_size' ) else config.encoder.vocab_size _a : Union[str, Any] = random_input_ids(_a ,_a ,_a ) @run_with_tf_optimizations(self.args.eager_mode ,self.args.use_xla ) def encoder_decoder_forward(): return model(_a ,decoder_input_ids=_a ,training=_a ) @run_with_tf_optimizations(self.args.eager_mode ,self.args.use_xla ) def encoder_forward(): return model(_a ,training=_a ) _a : Optional[Any] = encoder_decoder_forward if config.is_encoder_decoder else encoder_forward return _inference def __lowercase ( self : Optional[Any] ,_a : str ,_a : int ,_a : int ): '''simple docstring''' _a : str = self.config_dict[model_name] if self.args.eager_mode is not False: raise ValueError('Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`.' ) if self.args.fpaa: raise NotImplementedError('Mixed precision is currently not supported.' ) _a : Optional[Any] = ( hasattr(_a ,'architectures' ) and isinstance(config.architectures ,_a ) and len(config.architectures ) > 0 ) if not self.args.only_pretrain_model and has_model_class_in_config: try: _a : str = 'TF' + config.architectures[0] # prepend 'TF' for tensorflow model _a : Union[str, Any] = __import__('transformers' ,fromlist=[model_class] ) _a : Union[str, Any] = getattr(_a ,_a ) _a : List[str] = model_cls(_a ) except ImportError: raise ImportError( F"""{model_class} does not exist. If you just want to test the pretrained model, you might want to""" ' set `--only_pretrain_model` or `args.only_pretrain_model=True`.' ) else: _a : Any = TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](_a ) # encoder-decoder has vocab size saved differently _a : Optional[Any] = config.vocab_size if hasattr(_a ,'vocab_size' ) else config.encoder.vocab_size _a : List[str] = random_input_ids(_a ,_a ,_a ) @run_with_tf_optimizations(self.args.eager_mode ,self.args.use_xla ) def encoder_decoder_train(): _a : List[Any] = model(_a ,decoder_input_ids=_a ,labels=_a ,training=_a )[0] _a : int = tf.gradients(_a ,model.trainable_variables ) return gradients @run_with_tf_optimizations(self.args.eager_mode ,self.args.use_xla ) def encoder_train(): _a : List[str] = model(_a ,labels=_a ,training=_a )[0] _a : Union[str, Any] = tf.gradients(_a ,model.trainable_variables ) return gradients _a : str = encoder_decoder_train if config.is_encoder_decoder else encoder_train return _train def __lowercase ( self : List[Any] ,_a : int ): '''simple docstring''' with self.args.strategy.scope(): try: if self.args.is_tpu or self.args.use_xla: # run additional 10 times to stabilize compilation for tpu logger.info('Do inference on TPU. Running model 5 times to stabilize compilation' ) timeit.repeat(_a ,repeat=1 ,number=5 ) # as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average _a : Optional[int] = timeit.repeat( _a ,repeat=self.args.repeat ,number=10 ,) return min(_a ) / 10.0 except ResourceExhaustedError as e: self.print_fn(F"""Doesn't fit on GPU. {e}""" ) def __lowercase ( self : Tuple ,_a : Callable[[], None] ): '''simple docstring''' logger.info( 'Note that TensorFlow allocates more memory than ' 'it might need to speed up computation. ' 'The memory reported here corresponds to the memory ' 'reported by `nvidia-smi`, which can vary depending ' 'on total available memory on the GPU that is used.' ) with self.args.strategy.scope(): try: if self.args.trace_memory_line_by_line: if not self.args.eager_mode: raise ValueError( '`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory' ' consumption line by line.' ) _a : Any = start_memory_tracing('transformers' ) if self.args.is_tpu: # tpu raise NotImplementedError( 'Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking' ' with `args.memory=False`' ) elif self.args.is_gpu: # gpu if not is_pyanvml_available(): logger.warning( 'py3nvml not installed, we won\'t log GPU memory usage. ' 'Install py3nvml (pip install py3nvml) to log information about GPU.' ) _a : str = 'N/A' else: logger.info( 'Measuring total GPU usage on GPU device. Make sure to not have additional processes' ' running on the same GPU.' ) # init nvml nvml.nvmlInit() func() _a : Tuple = nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx ) _a : Tuple = nvml.nvmlDeviceGetMemoryInfo(_a ) _a : Any = meminfo.used _a : Dict = Memory(_a ) # shutdown nvml nvml.nvmlShutdown() else: # cpu if self.args.trace_memory_line_by_line: logger.info( 'When enabling line by line tracing, the max peak memory for CPU is inaccurate in' ' TensorFlow.' ) _a : Optional[Any] = None else: _a : Any = measure_peak_memory_cpu(_a ) _a : int = Memory(_a ) if isinstance(_a ,_a ) else memory_bytes if self.args.trace_memory_line_by_line: _a : Any = stop_memory_tracing(_a ) if memory is None: _a : Optional[Any] = summary.total else: _a : Tuple = None return memory, summary except ResourceExhaustedError as e: self.print_fn(F"""Doesn't fit on GPU. {e}""" ) return "N/A", None
271
'''simple docstring''' import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def UpperCAmelCase_ (__a : Optional[Any] , __a : str , __a : Optional[Any]=None ): """simple docstring""" assert torch_layer.weight.shape == weight.shape, f"""{torch_layer} layer.weight does not match""" _a : str = nn.Parameter(__a ) if bias is not None: assert torch_layer.bias.shape == bias.shape, f"""{torch_layer} layer.bias does not match""" _a : Any = nn.Parameter(__a ) def UpperCAmelCase_ (__a : int , __a : Optional[Any] , __a : int ): """simple docstring""" _a : Tuple = np.asarray(weights[0] ) _a : Union[str, Any] = np.asarray(weights[1] ) _a : Dict = np.asarray(weights[2] ) set_param( torch_layer.self_attention.query_key , torch.tensor(__a ).transpose(1 , 2 ).contiguous().view(-1 , __a ) , ) set_param( torch_layer.self_attention.value , torch.tensor(__a ).transpose(1 , 2 ).contiguous().view(-1 , __a ) , ) set_param( torch_layer.output.dense , torch.tensor(__a ).view(-1 , __a ).contiguous().transpose(0 , 1 ) , ) def UpperCAmelCase_ (__a : Optional[Any] , __a : Optional[int] , __a : List[str] ): """simple docstring""" _a : Dict = np.asarray(weights[0] ) _a : Union[str, Any] = np.asarray(weights[1] ) _a : str = np.asarray(weights[2] ) _a : int = np.asarray(weights[3] ) set_param( torch_layer.self_attention.query , torch.tensor(__a ).transpose(1 , 2 ).contiguous().view(-1 , __a ) , ) set_param( torch_layer.self_attention.key , torch.tensor(__a ).transpose(1 , 2 ).contiguous().view(-1 , __a ) , ) set_param( torch_layer.self_attention.value , torch.tensor(__a ).transpose(1 , 2 ).contiguous().view(-1 , __a ) , ) set_param( torch_layer.output.dense , torch.tensor(__a ).view(-1 , __a ).contiguous().transpose(0 , 1 ) , ) def UpperCAmelCase_ (__a : Any , __a : Any , __a : Optional[Any] ): """simple docstring""" _a : List[str] = weights[0][0][0] _a : List[Any] = np.asarray(layer_norm_a[0] ) _a : List[str] = np.asarray(layer_norm_a[1] ) set_param( torch_block.attention.layer_norm , torch.tensor(__a ) , torch.tensor(__a ) , ) # lsh weights + output _a : List[str] = weights[0][1] if len(__a ) < 4: set_layer_weights_in_torch_lsh(__a , torch_block.attention , __a ) else: set_layer_weights_in_torch_local(__a , torch_block.attention , __a ) # intermediate weighs _a : Optional[Any] = weights[2][0][1][2] # Chunked Feed Forward if len(__a ) == 4: _a : Union[str, Any] = intermediate_weights[2] # layernorm 2 _a : Any = np.asarray(intermediate_weights[0][0] ) _a : List[Any] = np.asarray(intermediate_weights[0][1] ) set_param( torch_block.feed_forward.layer_norm , torch.tensor(__a ) , torch.tensor(__a ) , ) # intermediate dense _a : Any = np.asarray(intermediate_weights[1][0] ) _a : Any = np.asarray(intermediate_weights[1][1] ) set_param( torch_block.feed_forward.dense.dense , torch.tensor(__a ).transpose(0 , 1 ).contiguous() , torch.tensor(__a ) , ) # intermediate out _a : Optional[int] = np.asarray(intermediate_weights[4][0] ) _a : int = np.asarray(intermediate_weights[4][1] ) set_param( torch_block.feed_forward.output.dense , torch.tensor(__a ).transpose(0 , 1 ).contiguous() , torch.tensor(__a ) , ) def UpperCAmelCase_ (__a : Dict , __a : Dict , __a : List[Any] ): """simple docstring""" _a : Optional[int] = torch_model.reformer # word embeds _a : Tuple = np.asarray(weights[1] ) set_param( torch_model_reformer.embeddings.word_embeddings , torch.tensor(__a ) , ) if isinstance(weights[3] , __a ): _a : Any = torch_model_reformer.embeddings.position_embeddings for emb_idx in range(len(position_embeddings.weights ) ): _a : List[Any] = np.asarray(weights[3][emb_idx][0] ) assert ( position_embeddings.weights[emb_idx].shape == emb_weights.shape ), f"""{position_embeddings[emb_idx]} emb does not match""" _a : Any = nn.Parameter(torch.tensor(__a ) ) _a : List[str] = weights[5] assert len(torch_model_reformer.encoder.layers ) * 4 == len( __a ), "HF and trax model do not have the same number of layers" for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ): _a : Tuple = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)] set_block_weights_in_torch(__a , __a , __a ) # output layer norm _a : Optional[Any] = np.asarray(weights[7][0] ) _a : int = np.asarray(weights[7][1] ) set_param( torch_model_reformer.encoder.layer_norm , torch.tensor(__a ) , torch.tensor(__a ) , ) # output embeddings _a : List[str] = np.asarray(weights[9][0] ) _a : int = np.asarray(weights[9][1] ) set_param( torch_model.lm_head.decoder , torch.tensor(__a ).transpose(0 , 1 ).contiguous() , torch.tensor(__a ) , ) def UpperCAmelCase_ (__a : Tuple , __a : Optional[Any] , __a : Dict ): """simple docstring""" _a : List[Any] = ReformerConfig.from_json_file(__a ) print(f"""Building PyTorch model from configuration: {config}""" ) _a : int = ReformerModelWithLMHead(__a ) with open(__a , 'rb' ) as f: _a : Optional[Any] = pickle.load(__a )['weights'] set_model_weights_in_torch(__a , __a , config.hidden_size ) # Save pytorch-model print(f"""Save PyTorch model to {pytorch_dump_path}""" ) torch.save(model.state_dict() , __a ) if __name__ == "__main__": __lowerCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--trax_model_pkl_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained Reformer model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) __lowerCAmelCase = parser.parse_args() convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
271
1
'''simple docstring''' import gzip import hashlib import json import multiprocessing import os import re import shutil import time from pathlib import Path import numpy as np from arguments import PreprocessingArguments from datasets import load_dataset from minhash_deduplication import deduplicate_dataset from transformers import AutoTokenizer, HfArgumentParser __lowerCAmelCase = re.compile(r"""\s+""") def UpperCAmelCase_ (__a : Any ): """simple docstring""" return {"hash": hashlib.mda(re.sub(__a , '' , example['content'] ).encode('utf-8' ) ).hexdigest()} def UpperCAmelCase_ (__a : str ): """simple docstring""" _a : List[str] = [len(__a ) for line in example['content'].splitlines()] return {"line_mean": np.mean(__a ), "line_max": max(__a )} def UpperCAmelCase_ (__a : str ): """simple docstring""" _a : Union[str, Any] = np.mean([c.isalnum() for c in example['content']] ) return {"alpha_frac": alpha_frac} def UpperCAmelCase_ (__a : Optional[int] , __a : Any ): """simple docstring""" if example["hash"] in uniques: uniques.remove(example['hash'] ) return True else: return False def UpperCAmelCase_ (__a : int , __a : Union[str, Any]=5 ): """simple docstring""" _a : Optional[int] = ['auto-generated', 'autogenerated', 'automatically generated'] _a : List[str] = example['content'].splitlines() for _, line in zip(range(__a ) , __a ): for keyword in keywords: if keyword in line.lower(): return {"autogenerated": True} else: return {"autogenerated": False} def UpperCAmelCase_ (__a : List[str] , __a : Dict=5 , __a : Tuple=0.05 ): """simple docstring""" _a : Optional[int] = ['unit tests', 'test file', 'configuration file'] _a : int = example['content'].splitlines() _a : int = 0 _a : Dict = 0 # first test for _, line in zip(range(__a ) , __a ): for keyword in keywords: if keyword in line.lower(): return {"config_or_test": True} # second test _a : int = example['content'].count('\n' ) _a : int = int(coeff * nlines ) for line in lines: count_config += line.lower().count('config' ) count_test += line.lower().count('test' ) if count_config > threshold or count_test > threshold: return {"config_or_test": True} return {"config_or_test": False} def UpperCAmelCase_ (__a : Optional[int] ): """simple docstring""" _a : List[str] = ['def ', 'class ', 'for ', 'while '] _a : str = example['content'].splitlines() for line in lines: for keyword in keywords: if keyword in line.lower(): return {"has_no_keywords": False} return {"has_no_keywords": True} def UpperCAmelCase_ (__a : int , __a : Any=4 ): """simple docstring""" _a : List[str] = example['content'].splitlines() _a : Dict = 0 for line in lines: counter += line.lower().count('=' ) if counter > minimum: return {"has_few_assignments": False} return {"has_few_assignments": True} def UpperCAmelCase_ (__a : str ): """simple docstring""" _a : Optional[Any] = tokenizer(example['content'] , truncation=__a )['input_ids'] _a : Optional[int] = len(example['content'] ) / len(__a ) return {"ratio": ratio} def UpperCAmelCase_ (__a : str ): """simple docstring""" _a : Dict = {} results.update(get_hash(__a ) ) results.update(line_stats(__a ) ) results.update(alpha_stats(__a ) ) results.update(char_token_ratio(__a ) ) results.update(is_autogenerated(__a ) ) results.update(is_config_or_test(__a ) ) results.update(has_no_keywords(__a ) ) results.update(has_few_assignments(__a ) ) return results def UpperCAmelCase_ (__a : Any , __a : Any , __a : str ): """simple docstring""" if not check_uniques(__a , __a ): return False elif example["autogenerated"]: return False elif example["line_max"] > args.line_max: return False elif example["line_mean"] > args.line_mean: return False elif example["alpha_frac"] < args.alpha_frac: return False elif example["ratio"] < args.min_token_ratio: return False elif example["config_or_test"] and np.random.rand() <= args.filter_proba: return False elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba: return False elif example["has_few_assignments"]: return False else: return True def UpperCAmelCase_ (__a : Union[str, Any] ): """simple docstring""" with open(__a , 'rb' ) as f_in: with gzip.open(str(__a ) + '.gz' , 'wb' , compresslevel=6 ) as f_out: shutil.copyfileobj(__a , __a ) os.unlink(__a ) # Settings __lowerCAmelCase = HfArgumentParser(PreprocessingArguments) __lowerCAmelCase = parser.parse_args() if args.num_workers is None: __lowerCAmelCase = multiprocessing.cpu_count() __lowerCAmelCase = AutoTokenizer.from_pretrained(args.tokenizer_dir) # Load dataset __lowerCAmelCase = time.time() __lowerCAmelCase = load_dataset(args.dataset_name, split="""train""") print(f'''Time to load dataset: {time.time()-t_start:.2f}''') # Run preprocessing __lowerCAmelCase = time.time() __lowerCAmelCase = ds.map(preprocess, num_proc=args.num_workers) print(f'''Time to preprocess dataset: {time.time()-t_start:.2f}''') # Deduplicate hashes __lowerCAmelCase = set(ds.unique("""hash""")) __lowerCAmelCase = len(uniques) / len(ds) print(f'''Fraction of duplicates: {1-frac:.2%}''') # Deduplicate data and apply heuristics __lowerCAmelCase = time.time() __lowerCAmelCase = ds.filter(filter, fn_kwargs={"""uniques""": uniques, """args""": args}) print(f'''Time to filter dataset: {time.time()-t_start:.2f}''') print(f'''Size of filtered dataset: {len(ds_filter)}''') # Deduplicate with minhash and jaccard similarity if args.near_deduplication: __lowerCAmelCase = time.time() __lowerCAmelCase , __lowerCAmelCase = deduplicate_dataset(ds_filter, args.jaccard_threshold) print(f'''Time to deduplicate dataset: {time.time()-t_start:.2f}''') print(f'''Size of deduplicate dataset: {len(ds_filter)}''') # Save data in batches of samples_per_file __lowerCAmelCase = Path(args.output_dir) output_dir.mkdir(exist_ok=True) # save duplicate_clusters in the output_dir as artifacts # not sure it is the right place the save it if args.near_deduplication: with open(output_dir / """duplicate_clusters.json""", """w""") as f: json.dump(duplicate_clusters, f) __lowerCAmelCase = output_dir / """data""" data_dir.mkdir(exist_ok=True) __lowerCAmelCase = time.time() for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)): __lowerCAmelCase = str(data_dir / f'''file-{file_number+1:012}.json''') __lowerCAmelCase = min(len(ds_filter), index + args.samples_per_file) ds_filter.select(list(range(index, end_index))).to_json(file_path) compress_file(file_path) print(f'''Time to save dataset: {time.time()-t_start:.2f}''')
271
'''simple docstring''' import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" @property def __lowercase ( self : Union[str, Any] ): '''simple docstring''' torch.manual_seed(0 ) _a : Any = UNetaDModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=3 ,out_channels=3 ,down_block_types=('DownBlock2D', 'AttnDownBlock2D') ,up_block_types=('AttnUpBlock2D', 'UpBlock2D') ,) return model @property def __lowercase ( self : Optional[int] ): '''simple docstring''' torch.manual_seed(0 ) _a : Union[str, Any] = VQModel( block_out_channels=[32, 64] ,in_channels=3 ,out_channels=3 ,down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] ,up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] ,latent_channels=3 ,) return model @property def __lowercase ( self : Optional[int] ): '''simple docstring''' torch.manual_seed(0 ) _a : Any = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1E-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1000 ,) return CLIPTextModel(_a ) def __lowercase ( self : Tuple ): '''simple docstring''' _a : Dict = self.dummy_uncond_unet _a : List[Any] = DDIMScheduler() _a : List[Any] = self.dummy_vq_model _a : str = LDMPipeline(unet=_a ,vqvae=_a ,scheduler=_a ) ldm.to(_a ) ldm.set_progress_bar_config(disable=_a ) _a : List[str] = torch.manual_seed(0 ) _a : List[str] = ldm(generator=_a ,num_inference_steps=2 ,output_type='numpy' ).images _a : List[str] = torch.manual_seed(0 ) _a : Union[str, Any] = ldm(generator=_a ,num_inference_steps=2 ,output_type='numpy' ,return_dict=_a )[0] _a : Tuple = image[0, -3:, -3:, -1] _a : Optional[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _a : int = np.array([0.8512, 0.818, 0.6411, 0.6808, 0.4465, 0.5618, 0.46, 0.6231, 0.5172] ) _a : Any = 1E-2 if torch_device != 'mps' else 3E-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < tolerance @slow @require_torch class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a : List[str] = LDMPipeline.from_pretrained('CompVis/ldm-celebahq-256' ) ldm.to(_a ) ldm.set_progress_bar_config(disable=_a ) _a : Optional[int] = torch.manual_seed(0 ) _a : Dict = ldm(generator=_a ,num_inference_steps=5 ,output_type='numpy' ).images _a : str = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) _a : Optional[int] = np.array([0.4399, 0.4_4975, 0.4_6825, 0.474, 0.4359, 0.4581, 0.4_5095, 0.4341, 0.4447] ) _a : int = 1E-2 if torch_device != 'mps' else 3E-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance
271
1
'''simple docstring''' from jiwer import compute_measures import datasets __lowerCAmelCase = """\ @inproceedings{inproceedings, author = {Morris, Andrew and Maier, Viktoria and Green, Phil}, year = {2004}, month = {01}, pages = {}, title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.} } """ __lowerCAmelCase = """\ Word error rate (WER) is a common metric of the performance of an automatic speech recognition system. The general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort. This problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate. Word error rate can then be computed as: WER = (S + D + I) / N = (S + D + I) / (S + D + C) where S is the number of substitutions, D is the number of deletions, I is the number of insertions, C is the number of correct words, N is the number of words in the reference (N=S+D+C). This value indicates the average number of errors per reference word. The lower the value, the better the performance of the ASR system with a WER of 0 being a perfect score. """ __lowerCAmelCase = """ Compute WER score of transcribed segments against references. Args: references: List of references for each speech input. predictions: List of transcriptions to score. concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively. Returns: (float): the word error rate Examples: >>> predictions = [\"this is the prediction\", \"there is an other sample\"] >>> references = [\"this is the reference\", \"there is another one\"] >>> wer = datasets.load_metric(\"wer\") >>> wer_score = wer.compute(predictions=predictions, references=references) >>> print(wer_score) 0.5 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase__ ( datasets.Metric ): """simple docstring""" def __lowercase ( self : List[Any] ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('string' ,id='sequence' ), 'references': datasets.Value('string' ,id='sequence' ), } ) ,codebase_urls=['https://github.com/jitsi/jiwer/'] ,reference_urls=[ 'https://en.wikipedia.org/wiki/Word_error_rate', ] ,) def __lowercase ( self : Tuple ,_a : Any=None ,_a : List[Any]=None ,_a : List[str]=False ): '''simple docstring''' if concatenate_texts: return compute_measures(_a ,_a )["wer"] else: _a : List[str] = 0 _a : Optional[Any] = 0 for prediction, reference in zip(_a ,_a ): _a : Dict = compute_measures(_a ,_a ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
271
'''simple docstring''' import warnings from ...utils import logging from .image_processing_beit import BeitImageProcessor __lowerCAmelCase = logging.get_logger(__name__) class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" def __init__( self : int ,*_a : Optional[int] ,**_a : str ): '''simple docstring''' warnings.warn( 'The class BeitFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use BeitImageProcessor instead.' ,_a ,) super().__init__(*_a ,**_a )
271
1
'''simple docstring''' import tempfile import torch from diffusers import PNDMScheduler from .test_schedulers import SchedulerCommonTest class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = (PNDMScheduler,) __UpperCAmelCase : List[str] = (('''num_inference_steps''', 50),) def __lowercase ( self : Optional[Any] ,**_a : str ): '''simple docstring''' _a : Union[str, Any] = { 'num_train_timesteps': 1000, 'beta_start': 0.0001, 'beta_end': 0.02, 'beta_schedule': 'linear', } config.update(**_a ) return config def __lowercase ( self : int ,_a : Any=0 ,**_a : Dict ): '''simple docstring''' _a : Union[str, Any] = dict(self.forward_default_kwargs ) _a : Any = kwargs.pop('num_inference_steps' ,_a ) _a : Optional[Any] = self.dummy_sample _a : Any = 0.1 * sample _a : Any = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: _a : Optional[int] = self.get_scheduler_config(**_a ) _a : Any = scheduler_class(**_a ) scheduler.set_timesteps(_a ) # copy over dummy past residuals _a : List[Any] = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(_a ) _a : Dict = scheduler_class.from_pretrained(_a ) new_scheduler.set_timesteps(_a ) # copy over dummy past residuals _a : Tuple = dummy_past_residuals[:] _a : Optional[Any] = scheduler.step_prk(_a ,_a ,_a ,**_a ).prev_sample _a : List[Any] = new_scheduler.step_prk(_a ,_a ,_a ,**_a ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" _a : Dict = scheduler.step_plms(_a ,_a ,_a ,**_a ).prev_sample _a : List[Any] = new_scheduler.step_plms(_a ,_a ,_a ,**_a ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def __lowercase ( self : List[Any] ): '''simple docstring''' pass def __lowercase ( self : Union[str, Any] ,_a : List[Any]=0 ,**_a : Optional[Any] ): '''simple docstring''' _a : str = dict(self.forward_default_kwargs ) _a : List[Any] = kwargs.pop('num_inference_steps' ,_a ) _a : List[str] = self.dummy_sample _a : str = 0.1 * sample _a : Any = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: _a : int = self.get_scheduler_config() _a : Optional[int] = scheduler_class(**_a ) scheduler.set_timesteps(_a ) # copy over dummy past residuals (must be after setting timesteps) _a : Any = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(_a ) _a : Optional[Any] = scheduler_class.from_pretrained(_a ) # copy over dummy past residuals new_scheduler.set_timesteps(_a ) # copy over dummy past residual (must be after setting timesteps) _a : List[Any] = dummy_past_residuals[:] _a : int = scheduler.step_prk(_a ,_a ,_a ,**_a ).prev_sample _a : str = new_scheduler.step_prk(_a ,_a ,_a ,**_a ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" _a : Optional[Any] = scheduler.step_plms(_a ,_a ,_a ,**_a ).prev_sample _a : int = new_scheduler.step_plms(_a ,_a ,_a ,**_a ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def __lowercase ( self : List[Any] ,**_a : Optional[int] ): '''simple docstring''' _a : Optional[int] = self.scheduler_classes[0] _a : Optional[Any] = self.get_scheduler_config(**_a ) _a : Optional[int] = scheduler_class(**_a ) _a : Dict = 10 _a : Dict = self.dummy_model() _a : List[str] = self.dummy_sample_deter scheduler.set_timesteps(_a ) for i, t in enumerate(scheduler.prk_timesteps ): _a : int = model(_a ,_a ) _a : Any = scheduler.step_prk(_a ,_a ,_a ).prev_sample for i, t in enumerate(scheduler.plms_timesteps ): _a : Optional[Any] = model(_a ,_a ) _a : List[str] = scheduler.step_plms(_a ,_a ,_a ).prev_sample return sample def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a : Optional[int] = dict(self.forward_default_kwargs ) _a : Any = kwargs.pop('num_inference_steps' ,_a ) for scheduler_class in self.scheduler_classes: _a : Union[str, Any] = self.get_scheduler_config() _a : int = scheduler_class(**_a ) _a : Any = self.dummy_sample _a : List[Any] = 0.1 * sample if num_inference_steps is not None and hasattr(_a ,'set_timesteps' ): scheduler.set_timesteps(_a ) elif num_inference_steps is not None and not hasattr(_a ,'set_timesteps' ): _a : List[str] = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) _a : Any = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] _a : str = dummy_past_residuals[:] _a : str = scheduler.step_prk(_a ,0 ,_a ,**_a ).prev_sample _a : Optional[Any] = scheduler.step_prk(_a ,1 ,_a ,**_a ).prev_sample self.assertEqual(output_a.shape ,sample.shape ) self.assertEqual(output_a.shape ,output_a.shape ) _a : str = scheduler.step_plms(_a ,0 ,_a ,**_a ).prev_sample _a : Union[str, Any] = scheduler.step_plms(_a ,1 ,_a ,**_a ).prev_sample self.assertEqual(output_a.shape ,sample.shape ) self.assertEqual(output_a.shape ,output_a.shape ) def __lowercase ( self : Any ): '''simple docstring''' for timesteps in [100, 1000]: self.check_over_configs(num_train_timesteps=_a ) def __lowercase ( self : List[str] ): '''simple docstring''' for steps_offset in [0, 1]: self.check_over_configs(steps_offset=_a ) _a : Tuple = self.scheduler_classes[0] _a : Tuple = self.get_scheduler_config(steps_offset=1 ) _a : Optional[Any] = scheduler_class(**_a ) scheduler.set_timesteps(10 ) assert torch.equal( scheduler.timesteps ,torch.LongTensor( [901, 851, 851, 801, 801, 751, 751, 701, 701, 651, 651, 601, 601, 501, 401, 301, 201, 101, 1] ) ,) def __lowercase ( self : Tuple ): '''simple docstring''' for beta_start, beta_end in zip([0.0001, 0.001] ,[0.002, 0.02] ): self.check_over_configs(beta_start=_a ,beta_end=_a ) def __lowercase ( self : List[str] ): '''simple docstring''' for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=_a ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=_a ) def __lowercase ( self : Dict ): '''simple docstring''' for t in [1, 5, 10]: self.check_over_forward(time_step=_a ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' for t, num_inference_steps in zip([1, 5, 10] ,[10, 50, 100] ): self.check_over_forward(num_inference_steps=_a ) def __lowercase ( self : List[Any] ): '''simple docstring''' _a : List[str] = 27 for scheduler_class in self.scheduler_classes: _a : List[str] = self.dummy_sample _a : Optional[Any] = 0.1 * sample _a : Any = self.get_scheduler_config() _a : Optional[int] = scheduler_class(**_a ) scheduler.set_timesteps(_a ) # before power of 3 fix, would error on first step, so we only need to do two for i, t in enumerate(scheduler.prk_timesteps[:2] ): _a : int = scheduler.step_prk(_a ,_a ,_a ).prev_sample def __lowercase ( self : Any ): '''simple docstring''' with self.assertRaises(_a ): _a : Optional[Any] = self.scheduler_classes[0] _a : int = self.get_scheduler_config() _a : Tuple = scheduler_class(**_a ) scheduler.step_plms(self.dummy_sample ,1 ,self.dummy_sample ).prev_sample def __lowercase ( self : Any ): '''simple docstring''' _a : Dict = self.full_loop() _a : List[Any] = torch.sum(torch.abs(_a ) ) _a : List[str] = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 198.1318 ) < 1E-2 assert abs(result_mean.item() - 0.2580 ) < 1E-3 def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : Optional[Any] = self.full_loop(prediction_type='v_prediction' ) _a : Any = torch.sum(torch.abs(_a ) ) _a : List[str] = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 67.3986 ) < 1E-2 assert abs(result_mean.item() - 0.0878 ) < 1E-3 def __lowercase ( self : List[Any] ): '''simple docstring''' _a : Dict = self.full_loop(set_alpha_to_one=_a ,beta_start=0.01 ) _a : Optional[int] = torch.sum(torch.abs(_a ) ) _a : Optional[int] = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 230.0399 ) < 1E-2 assert abs(result_mean.item() - 0.2995 ) < 1E-3 def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : Any = self.full_loop(set_alpha_to_one=_a ,beta_start=0.01 ) _a : List[str] = torch.sum(torch.abs(_a ) ) _a : Tuple = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 186.9482 ) < 1E-2 assert abs(result_mean.item() - 0.2434 ) < 1E-3
271
'''simple docstring''' from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.utils.data import DistributedSampler, RandomSampler from transformers import PreTrainedModel, Trainer, logging from transformers.integrations import is_fairscale_available from transformers.models.fsmt.configuration_fsmt import FSMTConfig from transformers.optimization 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_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.trainer_pt_utils import get_tpu_sampler from transformers.training_args import ParallelMode from transformers.utils import is_torch_tpu_available if is_fairscale_available(): from fairscale.optim import OSS __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = { """linear""": get_linear_schedule_with_warmup, """cosine""": get_cosine_schedule_with_warmup, """cosine_w_restarts""": get_cosine_with_hard_restarts_schedule_with_warmup, """polynomial""": get_polynomial_decay_schedule_with_warmup, """constant""": get_constant_schedule, """constant_w_warmup""": get_constant_schedule_with_warmup, } class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" def __init__( self : Optional[int] ,_a : Optional[Any]=None ,_a : Dict=None ,*_a : int ,**_a : str ): '''simple docstring''' super().__init__(*_a ,**_a ) if config is None: assert isinstance(self.model ,_a ), ( "If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is" F""" {self.model.__class__}""" ) _a : List[Any] = self.model.config else: _a : Optional[int] = config _a : List[str] = data_args _a : List[Any] = self.config.tgt_vocab_size if isinstance(self.config ,_a ) else self.config.vocab_size if self.args.label_smoothing != 0 or (self.data_args is not None and self.data_args.ignore_pad_token_for_loss): assert self.config.pad_token_id is not None, ( "Make sure that `config.pad_token_id` is correcly defined when ignoring `pad_token` for loss" " calculation or doing label smoothing." ) if self.config.pad_token_id is None and self.config.eos_token_id is not None: logger.warning( F"""The `config.pad_token_id` is `None`. Using `config.eos_token_id` = {self.config.eos_token_id} for""" ' padding..' ) if self.args.label_smoothing == 0: _a : List[str] = torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id ) else: # dynamically import label_smoothed_nll_loss from utils import label_smoothed_nll_loss _a : Tuple = label_smoothed_nll_loss def __lowercase ( self : List[str] ,_a : int ): '''simple docstring''' if self.optimizer is None: _a : Union[str, Any] = ['bias', 'LayerNorm.weight'] _a : Tuple = [ { 'params': [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay )], 'weight_decay': self.args.weight_decay, }, { 'params': [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay )], 'weight_decay': 0.0, }, ] _a : Optional[int] = Adafactor if self.args.adafactor else AdamW if self.args.adafactor: _a : Any = Adafactor _a : Dict = {'scale_parameter': False, 'relative_step': False} else: _a : Union[str, Any] = AdamW _a : str = { 'betas': (self.args.adam_betaa, self.args.adam_betaa), 'eps': self.args.adam_epsilon, } _a : Union[str, Any] = self.args.learning_rate if self.sharded_ddp: _a : str = OSS( params=_a ,optim=_a ,**_a ,) else: _a : Tuple = optimizer_cls(_a ,**_a ) if self.lr_scheduler is None: _a : List[Any] = self._get_lr_scheduler(_a ) else: # ignoring --lr_scheduler logger.warning('scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored.' ) def __lowercase ( self : List[Any] ,_a : List[Any] ): '''simple docstring''' _a : str = arg_to_scheduler[self.args.lr_scheduler] if self.args.lr_scheduler == "constant": _a : int = schedule_func(self.optimizer ) elif self.args.lr_scheduler == "constant_w_warmup": _a : List[str] = schedule_func(self.optimizer ,num_warmup_steps=self.args.warmup_steps ) else: _a : Optional[int] = schedule_func( self.optimizer ,num_warmup_steps=self.args.warmup_steps ,num_training_steps=_a ) return scheduler def __lowercase ( self : Tuple ): '''simple docstring''' if isinstance(self.train_dataset ,torch.utils.data.IterableDataset ): return None elif is_torch_tpu_available(): return get_tpu_sampler(self.train_dataset ) else: if self.args.sortish_sampler: self.train_dataset.make_sortish_sampler( self.args.per_device_train_batch_size ,distributed=(self.args.parallel_mode == ParallelMode.DISTRIBUTED) ,) return ( RandomSampler(self.train_dataset ) if self.args.local_rank == -1 else DistributedSampler(self.train_dataset ) ) def __lowercase ( self : Dict ,_a : Dict ,_a : Any ,_a : Dict ): '''simple docstring''' if self.args.label_smoothing == 0: if self.data_args is not None and self.data_args.ignore_pad_token_for_loss: # force training to ignore pad token _a : List[Any] = model(**_a ,use_cache=_a )[0] _a : Union[str, Any] = self.loss_fn(logits.view(-1 ,logits.shape[-1] ) ,labels.view(-1 ) ) else: # compute usual loss via models _a, _a : Union[str, Any] = model(**_a ,labels=_a ,use_cache=_a )[:2] else: # compute label smoothed loss _a : List[Any] = model(**_a ,use_cache=_a )[0] _a : Any = torch.nn.functional.log_softmax(_a ,dim=-1 ) _a, _a : List[str] = self.loss_fn(_a ,_a ,self.args.label_smoothing ,ignore_index=self.config.pad_token_id ) return loss, logits def __lowercase ( self : Optional[int] ,_a : Union[str, Any] ,_a : List[Any] ): '''simple docstring''' _a : Optional[int] = inputs.pop('labels' ) _a, _a : int = self._compute_loss(_a ,_a ,_a ) return loss def __lowercase ( self : Optional[Any] ,_a : nn.Module ,_a : Dict[str, Union[torch.Tensor, Any]] ,_a : bool ,_a : Optional[List[str]] = None ,): '''simple docstring''' _a : int = self._prepare_inputs(_a ) _a : Any = { 'max_length': self.data_args.val_max_target_length if self.data_args is not None else self.config.max_length, 'num_beams': self.data_args.eval_beams if self.data_args is not None else self.config.num_beams, } if self.args.predict_with_generate and not self.args.prediction_loss_only: _a : int = self.model.generate( inputs['input_ids'] ,attention_mask=inputs['attention_mask'] ,**_a ,) # in case the batch is shorter than max length, the output should be padded if generated_tokens.shape[-1] < gen_kwargs["max_length"]: _a : int = self._pad_tensors_to_max_len(_a ,gen_kwargs['max_length'] ) _a : Union[str, Any] = inputs.pop('labels' ) with torch.no_grad(): # compute loss on predict data _a, _a : Optional[int] = self._compute_loss(_a ,_a ,_a ) _a : Optional[Any] = loss.mean().detach() if self.args.prediction_loss_only: return (loss, None, None) _a : Optional[Any] = generated_tokens if self.args.predict_with_generate else logits if labels.shape[-1] < gen_kwargs["max_length"]: _a : Dict = self._pad_tensors_to_max_len(_a ,gen_kwargs['max_length'] ) return (loss, logits, labels) def __lowercase ( self : str ,_a : Tuple ,_a : Tuple ): '''simple docstring''' _a : List[Any] = self.config.pad_token_id if self.config.pad_token_id is not None else self.config.eos_token_id if pad_token_id is None: raise ValueError( 'Make sure that either `config.pad_token_id` or `config.eos_token_id` is defined if tensor has to be' F""" padded to `max_length`={max_length}""" ) _a : int = pad_token_id * torch.ones( (tensor.shape[0], max_length) ,dtype=tensor.dtype ,device=tensor.device ) _a : Union[str, Any] = tensor return padded_tensor
271
1
'''simple docstring''' from typing import List, Optional, Union import numpy as np import tensorflow as tf from .utils import logging __lowerCAmelCase = logging.get_logger(__name__) def UpperCAmelCase_ (__a : Union[tf.Tensor, np.ndarray] ): """simple docstring""" if isinstance(__a , np.ndarray ): return list(tensor.shape ) _a : Optional[int] = tf.shape(__a ) if tensor.shape == tf.TensorShape(__a ): return dynamic _a : Any = tensor.shape.as_list() return [dynamic[i] if s is None else s for i, s in enumerate(__a )] def UpperCAmelCase_ (__a : tf.Tensor , __a : Optional[int] = None , __a : Optional[str] = None ): """simple docstring""" return tf.nn.softmax(logits=logits + 1e-9 , axis=__a , name=__a ) def UpperCAmelCase_ (__a : Optional[int] , __a : Tuple , __a : Optional[Any] , __a : Optional[Any]=1e-5 , __a : Any=-1 ): """simple docstring""" if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(__a , __a ): raise NotImplementedError('Only 1D weight and bias tensors are supported for now, with only a single axis.' ) # Get mean and variance on the axis to be normalized _a, _a : Tuple = tf.nn.moments(__a , axes=[axis] , keepdims=__a ) if axis != -1: # Reshape scale and weight to have the same rank as inputs, but with 1 dimensions # on every dimension except axis _a : int = [1] * inputs.shape.rank _a : List[Any] = shape_list(__a )[axis] _a : Dict = tf.reshape(__a , __a ) _a : str = tf.reshape(__a , __a ) # Compute layer normalization using the batch_normalization # function. _a : List[str] = tf.nn.batch_normalization( __a , __a , __a , offset=__a , scale=__a , variance_epsilon=__a , ) return outputs def UpperCAmelCase_ (__a : Optional[Any] , __a : List[str]=0 , __a : Tuple=-1 ): """simple docstring""" if end_dim < 0: end_dim += input.shape.rank if start_dim < 0: start_dim += input.shape.rank if start_dim == end_dim: return input _a : Dict = tf.shape(__a ) _a : List[str] = tf.math.reduce_prod(in_shape[start_dim : end_dim + 1] ) _a : int = tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]] , axis=0 ) return tf.reshape(__a , __a ) def UpperCAmelCase_ (__a : tf.Tensor ): """simple docstring""" if not isinstance(__a , tf.Tensor ): _a : str = tf.convert_to_tensor(__a ) # Catches stray NumPy inputs if encoder_attention_mask.shape.rank == 3: _a : List[str] = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.shape.rank == 2: _a : List[Any] = encoder_attention_mask[:, None, None, :] # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow # /transformer/transformer_layers.py#L270 # encoder_extended_attention_mask = (encoder_extended_attention_mask == # encoder_extended_attention_mask.transpose(-1, -2)) _a : List[Any] = ( tf.cast(1 , encoder_attention_mask.dtype ) - encoder_extended_attention_mask ) * encoder_extended_attention_mask.dtype.min return encoder_extended_attention_mask def UpperCAmelCase_ (__a : tf.Tensor , __a : int , __a : str = "input_ids" ): """simple docstring""" tf.debugging.assert_less( __a , tf.cast(__a , dtype=tensor.dtype ) , message=( f"""The maximum value of {tensor_name} ({tf.math.reduce_max(__a )}) must be smaller than the embedding """ f"""layer's input dimension ({embed_dim}). The likely cause is some problem at tokenization time.""" ) , ) def UpperCAmelCase_ (__a : Tuple , __a : Union[str, Any] , __a : List[Any] ): """simple docstring""" _a : Tuple = 6_4_5_1_2 # Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT` # because in that case even chunking the array would not make the saving # possible. _a : Union[str, Any] = [x for x in data if len(__a ) > HDF5_OBJECT_HEADER_LIMIT] # Expecting this to never be true. if bad_attributes: raise RuntimeError( 'The following attributes cannot be saved to HDF5 file because ' f"""they are larger than {HDF5_OBJECT_HEADER_LIMIT} """ f"""bytes: {bad_attributes}""" ) _a : List[str] = np.asarray(__a ) _a : List[Any] = 1 _a : Union[str, Any] = np.array_split(__a , __a ) # This will never loop forever thanks to the test above. while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data ): num_chunks += 1 _a : Optional[int] = np.array_split(__a , __a ) if num_chunks > 1: for chunk_id, chunk_data in enumerate(__a ): _a : str = chunk_data else: _a : Optional[int] = data def UpperCAmelCase_ (__a : str , __a : int ): """simple docstring""" if name in group.attrs: _a : str = [n.decode('utf8' ) if hasattr(__a , 'decode' ) else n for n in group.attrs[name]] else: _a : Any = [] _a : str = 0 while "%s%d" % (name, chunk_id) in group.attrs: data.extend( [n.decode('utf8' ) if hasattr(__a , 'decode' ) else n for n in group.attrs['%s%d' % (name, chunk_id)]] ) chunk_id += 1 return data def UpperCAmelCase_ (__a : List[Any] ): """simple docstring""" def _expand_single_ad_tensor(__a : Tuple ): if isinstance(__a , tf.Tensor ) and t.shape.rank == 1: return tf.expand_dims(__a , axis=-1 ) return t return tf.nest.map_structure(_expand_single_ad_tensor , __a )
271
'''simple docstring''' import gzip import hashlib import json import multiprocessing import os import re import shutil import time from pathlib import Path import numpy as np from arguments import PreprocessingArguments from datasets import load_dataset from minhash_deduplication import deduplicate_dataset from transformers import AutoTokenizer, HfArgumentParser __lowerCAmelCase = re.compile(r"""\s+""") def UpperCAmelCase_ (__a : Any ): """simple docstring""" return {"hash": hashlib.mda(re.sub(__a , '' , example['content'] ).encode('utf-8' ) ).hexdigest()} def UpperCAmelCase_ (__a : str ): """simple docstring""" _a : List[str] = [len(__a ) for line in example['content'].splitlines()] return {"line_mean": np.mean(__a ), "line_max": max(__a )} def UpperCAmelCase_ (__a : str ): """simple docstring""" _a : Union[str, Any] = np.mean([c.isalnum() for c in example['content']] ) return {"alpha_frac": alpha_frac} def UpperCAmelCase_ (__a : Optional[int] , __a : Any ): """simple docstring""" if example["hash"] in uniques: uniques.remove(example['hash'] ) return True else: return False def UpperCAmelCase_ (__a : int , __a : Union[str, Any]=5 ): """simple docstring""" _a : Optional[int] = ['auto-generated', 'autogenerated', 'automatically generated'] _a : List[str] = example['content'].splitlines() for _, line in zip(range(__a ) , __a ): for keyword in keywords: if keyword in line.lower(): return {"autogenerated": True} else: return {"autogenerated": False} def UpperCAmelCase_ (__a : List[str] , __a : Dict=5 , __a : Tuple=0.05 ): """simple docstring""" _a : Optional[int] = ['unit tests', 'test file', 'configuration file'] _a : int = example['content'].splitlines() _a : int = 0 _a : Dict = 0 # first test for _, line in zip(range(__a ) , __a ): for keyword in keywords: if keyword in line.lower(): return {"config_or_test": True} # second test _a : int = example['content'].count('\n' ) _a : int = int(coeff * nlines ) for line in lines: count_config += line.lower().count('config' ) count_test += line.lower().count('test' ) if count_config > threshold or count_test > threshold: return {"config_or_test": True} return {"config_or_test": False} def UpperCAmelCase_ (__a : Optional[int] ): """simple docstring""" _a : List[str] = ['def ', 'class ', 'for ', 'while '] _a : str = example['content'].splitlines() for line in lines: for keyword in keywords: if keyword in line.lower(): return {"has_no_keywords": False} return {"has_no_keywords": True} def UpperCAmelCase_ (__a : int , __a : Any=4 ): """simple docstring""" _a : List[str] = example['content'].splitlines() _a : Dict = 0 for line in lines: counter += line.lower().count('=' ) if counter > minimum: return {"has_few_assignments": False} return {"has_few_assignments": True} def UpperCAmelCase_ (__a : str ): """simple docstring""" _a : Optional[Any] = tokenizer(example['content'] , truncation=__a )['input_ids'] _a : Optional[int] = len(example['content'] ) / len(__a ) return {"ratio": ratio} def UpperCAmelCase_ (__a : str ): """simple docstring""" _a : Dict = {} results.update(get_hash(__a ) ) results.update(line_stats(__a ) ) results.update(alpha_stats(__a ) ) results.update(char_token_ratio(__a ) ) results.update(is_autogenerated(__a ) ) results.update(is_config_or_test(__a ) ) results.update(has_no_keywords(__a ) ) results.update(has_few_assignments(__a ) ) return results def UpperCAmelCase_ (__a : Any , __a : Any , __a : str ): """simple docstring""" if not check_uniques(__a , __a ): return False elif example["autogenerated"]: return False elif example["line_max"] > args.line_max: return False elif example["line_mean"] > args.line_mean: return False elif example["alpha_frac"] < args.alpha_frac: return False elif example["ratio"] < args.min_token_ratio: return False elif example["config_or_test"] and np.random.rand() <= args.filter_proba: return False elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba: return False elif example["has_few_assignments"]: return False else: return True def UpperCAmelCase_ (__a : Union[str, Any] ): """simple docstring""" with open(__a , 'rb' ) as f_in: with gzip.open(str(__a ) + '.gz' , 'wb' , compresslevel=6 ) as f_out: shutil.copyfileobj(__a , __a ) os.unlink(__a ) # Settings __lowerCAmelCase = HfArgumentParser(PreprocessingArguments) __lowerCAmelCase = parser.parse_args() if args.num_workers is None: __lowerCAmelCase = multiprocessing.cpu_count() __lowerCAmelCase = AutoTokenizer.from_pretrained(args.tokenizer_dir) # Load dataset __lowerCAmelCase = time.time() __lowerCAmelCase = load_dataset(args.dataset_name, split="""train""") print(f'''Time to load dataset: {time.time()-t_start:.2f}''') # Run preprocessing __lowerCAmelCase = time.time() __lowerCAmelCase = ds.map(preprocess, num_proc=args.num_workers) print(f'''Time to preprocess dataset: {time.time()-t_start:.2f}''') # Deduplicate hashes __lowerCAmelCase = set(ds.unique("""hash""")) __lowerCAmelCase = len(uniques) / len(ds) print(f'''Fraction of duplicates: {1-frac:.2%}''') # Deduplicate data and apply heuristics __lowerCAmelCase = time.time() __lowerCAmelCase = ds.filter(filter, fn_kwargs={"""uniques""": uniques, """args""": args}) print(f'''Time to filter dataset: {time.time()-t_start:.2f}''') print(f'''Size of filtered dataset: {len(ds_filter)}''') # Deduplicate with minhash and jaccard similarity if args.near_deduplication: __lowerCAmelCase = time.time() __lowerCAmelCase , __lowerCAmelCase = deduplicate_dataset(ds_filter, args.jaccard_threshold) print(f'''Time to deduplicate dataset: {time.time()-t_start:.2f}''') print(f'''Size of deduplicate dataset: {len(ds_filter)}''') # Save data in batches of samples_per_file __lowerCAmelCase = Path(args.output_dir) output_dir.mkdir(exist_ok=True) # save duplicate_clusters in the output_dir as artifacts # not sure it is the right place the save it if args.near_deduplication: with open(output_dir / """duplicate_clusters.json""", """w""") as f: json.dump(duplicate_clusters, f) __lowerCAmelCase = output_dir / """data""" data_dir.mkdir(exist_ok=True) __lowerCAmelCase = time.time() for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)): __lowerCAmelCase = str(data_dir / f'''file-{file_number+1:012}.json''') __lowerCAmelCase = min(len(ds_filter), index + args.samples_per_file) ds_filter.select(list(range(index, end_index))).to_json(file_path) compress_file(file_path) print(f'''Time to save dataset: {time.time()-t_start:.2f}''')
271
1
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import KandinskyPipeline, KandinskyPriorPipeline else: from .pipeline_kandinsky import KandinskyPipeline from .pipeline_kandinsky_imgaimg import KandinskyImgaImgPipeline from .pipeline_kandinsky_inpaint import KandinskyInpaintPipeline from .pipeline_kandinsky_prior import KandinskyPriorPipeline, KandinskyPriorPipelineOutput from .text_encoder import MultilingualCLIP
271
'''simple docstring''' import argparse from typing import List import evaluate import numpy as np import torch from datasets import DatasetDict, load_dataset # New Code # # We'll be using StratifiedKFold for this example from sklearn.model_selection import StratifiedKFold from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to perform Cross Validation, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## __lowerCAmelCase = 1_6 __lowerCAmelCase = 3_2 def UpperCAmelCase_ (__a : Accelerator , __a : DatasetDict , __a : List[int] , __a : List[int] , __a : int = 1_6 ): """simple docstring""" _a : Union[str, Any] = AutoTokenizer.from_pretrained('bert-base-cased' ) _a : str = DatasetDict( { 'train': dataset['train'].select(__a ), 'validation': dataset['train'].select(__a ), 'test': dataset['validation'], } ) def tokenize_function(__a : List[Any] ): # max_length=None => use the model max length (it's actually the default) _a : Optional[int] = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=__a , max_length=__a ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): _a : List[str] = datasets.map( __a , batched=__a , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _a : List[Any] = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(__a : int ): # On TPU it's best to pad everything to the same length or training will be very slow. _a : Dict = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _a : Tuple = 1_6 elif accelerator.mixed_precision != "no": _a : List[Any] = 8 else: _a : List[Any] = None return tokenizer.pad( __a , padding='longest' , max_length=__a , pad_to_multiple_of=__a , return_tensors='pt' , ) # Instantiate dataloaders. _a : Any = DataLoader( tokenized_datasets['train'] , shuffle=__a , collate_fn=__a , batch_size=__a ) _a : Optional[int] = DataLoader( tokenized_datasets['validation'] , shuffle=__a , collate_fn=__a , batch_size=__a ) _a : Optional[Any] = DataLoader( tokenized_datasets['test'] , shuffle=__a , collate_fn=__a , batch_size=__a ) return train_dataloader, eval_dataloader, test_dataloader def UpperCAmelCase_ (__a : Any , __a : Union[str, Any] ): """simple docstring""" _a : Dict = [] # Download the dataset _a : Tuple = load_dataset('glue' , 'mrpc' ) # Create our splits _a : Union[str, Any] = StratifiedKFold(n_splits=int(args.num_folds ) ) # Initialize accelerator _a : Any = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _a : Optional[Any] = config['lr'] _a : Optional[int] = int(config['num_epochs'] ) _a : Dict = int(config['seed'] ) _a : Dict = int(config['batch_size'] ) _a : Optional[int] = evaluate.load('glue' , 'mrpc' ) # If the batch size is too big we use gradient accumulation _a : List[Any] = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: _a : Any = batch_size // MAX_GPU_BATCH_SIZE _a : List[str] = MAX_GPU_BATCH_SIZE set_seed(__a ) # New Code # # Create our folds: _a : int = kfold.split(np.zeros(datasets['train'].num_rows ) , datasets['train']['label'] ) _a : Any = [] # Iterate over them for i, (train_idxs, valid_idxs) in enumerate(__a ): _a, _a, _a : Optional[Any] = get_fold_dataloaders( __a , __a , __a , __a , ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _a : Dict = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=__a ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _a : List[Any] = model.to(accelerator.device ) # Instantiate optimizer _a : List[str] = AdamW(params=model.parameters() , lr=__a ) # Instantiate scheduler _a : List[Any] = get_linear_schedule_with_warmup( optimizer=__a , num_warmup_steps=1_0_0 , num_training_steps=(len(__a ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _a, _a, _a, _a, _a : Union[str, Any] = accelerator.prepare( __a , __a , __a , __a , __a ) # Now we train the model for epoch in range(__a ): model.train() for step, batch in enumerate(__a ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _a : Dict = model(**__a ) _a : int = outputs.loss _a : Any = loss / gradient_accumulation_steps accelerator.backward(__a ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__a ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _a : Union[str, Any] = model(**__a ) _a : Tuple = outputs.logits.argmax(dim=-1 ) _a, _a : Any = accelerator.gather_for_metrics((predictions, batch['labels']) ) metric.add_batch( predictions=__a , references=__a , ) _a : List[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" , __a ) # New Code # # We also run predictions on the test set at the very end _a : Any = [] for step, batch in enumerate(__a ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _a : Tuple = model(**__a ) _a : Dict = outputs.logits _a, _a : Optional[int] = accelerator.gather_for_metrics((predictions, batch['labels']) ) fold_predictions.append(predictions.cpu() ) if i == 0: # We need all of the test predictions test_references.append(references.cpu() ) # Use accelerator.print to print only on the main process. test_predictions.append(torch.cat(__a , dim=0 ) ) # We now need to release all our memory and get rid of the current model, optimizer, etc accelerator.free_memory() # New Code # # Finally we check the accuracy of our folded results: _a : Dict = torch.cat(__a , dim=0 ) _a : Any = torch.stack(__a , dim=0 ).sum(dim=0 ).div(int(args.num_folds ) ).argmax(dim=-1 ) _a : str = metric.compute(predictions=__a , references=__a ) accelerator.print('Average test metrics from all folds:' , __a ) def UpperCAmelCase_ (): """simple docstring""" _a : Any = argparse.ArgumentParser(description='Simple example of training script.' ) parser.add_argument( '--mixed_precision' , type=__a , default=__a , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.' ) # New Code # parser.add_argument('--num_folds' , type=__a , default=3 , help='The number of splits to perform across the dataset' ) _a : Any = parser.parse_args() _a : int = {'lr': 2e-5, 'num_epochs': 3, 'seed': 4_2, 'batch_size': 1_6} training_function(__a , __a ) if __name__ == "__main__": main()
271
1
'''simple docstring''' import unittest import numpy as np import torch from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" @property def __lowercase ( self : Optional[Any] ): '''simple docstring''' torch.manual_seed(0 ) _a : Dict = UNetaDModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=3 ,out_channels=3 ,down_block_types=('DownBlock2D', 'AttnDownBlock2D') ,up_block_types=('AttnUpBlock2D', 'UpBlock2D') ,) return model def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : Optional[int] = self.dummy_uncond_unet _a : Optional[int] = KarrasVeScheduler() _a : Optional[Any] = KarrasVePipeline(unet=_a ,scheduler=_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) _a : Tuple = torch.manual_seed(0 ) _a : Tuple = pipe(num_inference_steps=2 ,generator=_a ,output_type='numpy' ).images _a : Any = torch.manual_seed(0 ) _a : Optional[Any] = pipe(num_inference_steps=2 ,generator=_a ,output_type='numpy' ,return_dict=_a )[0] _a : Dict = image[0, -3:, -3:, -1] _a : int = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _a : int = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : Any = 'google/ncsnpp-celebahq-256' _a : List[Any] = UNetaDModel.from_pretrained(_a ) _a : List[Any] = KarrasVeScheduler() _a : List[str] = KarrasVePipeline(unet=_a ,scheduler=_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) _a : Dict = torch.manual_seed(0 ) _a : List[str] = pipe(num_inference_steps=20 ,generator=_a ,output_type='numpy' ).images _a : Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) _a : List[str] = np.array([0.578, 0.5811, 0.5924, 0.5809, 0.587, 0.5886, 0.5861, 0.5802, 0.586] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
271
'''simple docstring''' from __future__ import annotations __lowerCAmelCase = [-1_0, -5, 0, 5, 5.1, 1_1, 1_3, 2_1, 3, 4, -2_1, -1_0, -5, -1, 0] __lowerCAmelCase = [-5, 0, 5, 5.1, 1_1, 1_3, 2_1, -1, 4, -1, -1_0, -5, -1, 0, -1] def UpperCAmelCase_ (__a : list[float] ): """simple docstring""" _a : Optional[int] = [] _a : int = len(__a ) for i in range(__a ): _a : float = -1 for j in range(i + 1 , __a ): if arr[i] < arr[j]: _a : Any = arr[j] break result.append(__a ) return result def UpperCAmelCase_ (__a : list[float] ): """simple docstring""" _a : Tuple = [] for i, outer in enumerate(__a ): _a : float = -1 for inner in arr[i + 1 :]: if outer < inner: _a : Dict = inner break result.append(__a ) return result def UpperCAmelCase_ (__a : list[float] ): """simple docstring""" _a : int = len(__a ) _a : list[float] = [] _a : list[float] = [-1] * arr_size for index in reversed(range(__a ) ): if stack: while stack[-1] <= arr[index]: stack.pop() if not stack: break if stack: _a : Dict = stack[-1] stack.append(arr[index] ) return result if __name__ == "__main__": from doctest import testmod from timeit import timeit testmod() print(next_greatest_element_slow(arr)) print(next_greatest_element_fast(arr)) print(next_greatest_element(arr)) __lowerCAmelCase = ( """from __main__ import arr, next_greatest_element_slow, """ """next_greatest_element_fast, next_greatest_element""" ) print( """next_greatest_element_slow():""", timeit("""next_greatest_element_slow(arr)""", setup=setup), ) print( """next_greatest_element_fast():""", timeit("""next_greatest_element_fast(arr)""", setup=setup), ) print( """ next_greatest_element():""", timeit("""next_greatest_element(arr)""", setup=setup), )
271
1
'''simple docstring''' import math def UpperCAmelCase_ (__a : int ): """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(__a ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def UpperCAmelCase_ (__a : float = 0.1 ): """simple docstring""" _a : Dict = 3 _a : Optional[Any] = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1 , (j + 2) * (j + 2) , j + 1 ): primes += is_prime(__a ) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
271
'''simple docstring''' import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home __lowerCAmelCase = HUGGINGFACE_HUB_CACHE __lowerCAmelCase = """config.json""" __lowerCAmelCase = """diffusion_pytorch_model.bin""" __lowerCAmelCase = """diffusion_flax_model.msgpack""" __lowerCAmelCase = """model.onnx""" __lowerCAmelCase = """diffusion_pytorch_model.safetensors""" __lowerCAmelCase = """weights.pb""" __lowerCAmelCase = """https://huggingface.co""" __lowerCAmelCase = default_cache_path __lowerCAmelCase = """diffusers_modules""" __lowerCAmelCase = os.getenv("""HF_MODULES_CACHE""", os.path.join(hf_cache_home, """modules""")) __lowerCAmelCase = ["""fp16""", """non-ema"""] __lowerCAmelCase = """.self_attn"""
271
1
'''simple docstring''' from __future__ import annotations import random import unittest from transformers import TransfoXLConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, TFTransfoXLForSequenceClassification, TFTransfoXLLMHeadModel, TFTransfoXLModel, ) class UpperCAmelCase__ : """simple docstring""" def __init__( self : int ,_a : Union[str, Any] ,): '''simple docstring''' _a : List[str] = parent _a : Tuple = 13 _a : Tuple = 7 _a : str = 30 _a : Optional[Any] = self.seq_length + self.mem_len _a : Dict = 15 _a : Any = True _a : int = True _a : List[Any] = 99 _a : Tuple = [10, 50, 80] _a : Optional[Any] = 32 _a : str = 32 _a : str = 4 _a : Optional[Any] = 8 _a : Tuple = 128 _a : Optional[int] = 2 _a : Union[str, Any] = 2 _a : List[str] = None _a : Tuple = 1 _a : int = 0 _a : Tuple = 3 _a : str = self.vocab_size - 1 _a : str = 0.01 def __lowercase ( self : List[Any] ): '''simple docstring''' _a : Dict = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) _a : int = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) _a : int = None if self.use_labels: _a : Any = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) _a : List[Any] = TransfoXLConfig( vocab_size=self.vocab_size ,mem_len=self.mem_len ,clamp_len=self.clamp_len ,cutoffs=self.cutoffs ,d_model=self.hidden_size ,d_embed=self.d_embed ,n_head=self.num_attention_heads ,d_head=self.d_head ,d_inner=self.d_inner ,div_val=self.div_val ,n_layer=self.num_hidden_layers ,eos_token_id=self.eos_token_id ,pad_token_id=self.vocab_size - 1 ,init_range=self.init_range ,num_labels=self.num_labels ,) return (config, input_ids_a, input_ids_a, lm_labels) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' random.seed(self.seed ) tf.random.set_seed(self.seed ) def __lowercase ( self : int ,_a : Tuple ,_a : Dict ,_a : str ,_a : List[Any] ): '''simple docstring''' _a : str = TFTransfoXLModel(_a ) _a, _a : str = model(_a ).to_tuple() _a : Optional[int] = {'input_ids': input_ids_a, 'mems': mems_a} _a, _a : Dict = model(_a ).to_tuple() self.parent.assertEqual(hidden_states_a.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(hidden_states_a.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] ,[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers ,) self.parent.assertListEqual( [mem.shape for mem in mems_a] ,[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers ,) def __lowercase ( self : Union[str, Any] ,_a : Optional[int] ,_a : List[Any] ,_a : Optional[Any] ,_a : Any ): '''simple docstring''' _a : Tuple = TFTransfoXLLMHeadModel(_a ) _a, _a : Any = model(_a ).to_tuple() _a : Optional[int] = {'input_ids': input_ids_a, 'labels': lm_labels} _a, _a : int = model(_a ).to_tuple() _a, _a : Any = model([input_ids_a, mems_a] ).to_tuple() _a : List[Any] = {'input_ids': input_ids_a, 'mems': mems_a, 'labels': lm_labels} _a, _a : List[Any] = model(_a ).to_tuple() self.parent.assertEqual(lm_logits_a.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] ,[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers ,) self.parent.assertEqual(lm_logits_a.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] ,[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers ,) def __lowercase ( self : Optional[Any] ,_a : Union[str, Any] ,_a : int ,_a : int ,_a : List[str] ): '''simple docstring''' _a : int = TFTransfoXLForSequenceClassification(_a ) _a : Any = model(_a ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def __lowercase ( self : Dict ): '''simple docstring''' _a : List[Any] = self.prepare_config_and_inputs() ((_a), (_a), (_a), (_a)) : Any = config_and_inputs _a : Union[str, Any] = {'input_ids': input_ids_a} return config, inputs_dict @require_tf class UpperCAmelCase__ ( lowercase__ , lowercase__ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Any = ( (TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else () ) __UpperCAmelCase : Optional[Any] = () if is_tf_available() else () __UpperCAmelCase : Union[str, Any] = ( { '''feature-extraction''': TFTransfoXLModel, '''text-classification''': TFTransfoXLForSequenceClassification, '''text-generation''': TFTransfoXLLMHeadModel, '''zero-shot''': TFTransfoXLForSequenceClassification, } if is_tf_available() else {} ) # TODO: add this test when TFTransfoXLLMHead has a linear output layer implemented __UpperCAmelCase : Optional[Any] = False __UpperCAmelCase : Optional[Any] = False __UpperCAmelCase : Union[str, Any] = False __UpperCAmelCase : int = False def __lowercase ( self : Tuple ,_a : str ,_a : Dict ,_a : List[str] ,_a : Optional[Any] ,_a : int ): '''simple docstring''' if pipeline_test_casse_name == "TextGenerationPipelineTests": # Get `ValueError: AttributeError: 'NoneType' object has no attribute 'new_ones'` or `AssertionError`. # `TransfoXLConfig` was never used in pipeline tests: cannot create a simple # tokenizer. return True return False def __lowercase ( self : List[Any] ): '''simple docstring''' _a : Optional[Any] = TFTransfoXLModelTester(self ) _a : List[str] = ConfigTester(self ,config_class=_a ,d_embed=37 ) def __lowercase ( self : List[Any] ): '''simple docstring''' self.config_tester.run_common_tests() def __lowercase ( self : int ): '''simple docstring''' self.model_tester.set_seed() _a : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_model(*_a ) def __lowercase ( self : int ): '''simple docstring''' self.model_tester.set_seed() _a : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_lm_head(*_a ) def __lowercase ( self : Any ): '''simple docstring''' _a : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_for_sequence_classification(*_a ) def __lowercase ( self : Tuple ): '''simple docstring''' _a, _a : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() _a : str = [TFTransfoXLForSequenceClassification] for model_class in self.all_model_classes: _a : Optional[Any] = model_class(_a ) assert isinstance(model.get_input_embeddings() ,tf.keras.layers.Layer ) if model_class in list_other_models_with_output_ebd: _a : Tuple = model.get_output_embeddings() assert isinstance(_a ,tf.keras.layers.Layer ) _a : Tuple = model.get_bias() assert name is None else: _a : Tuple = model.get_output_embeddings() assert x is None _a : List[str] = model.get_bias() assert name is None def __lowercase ( self : List[str] ): '''simple docstring''' pass @slow def __lowercase ( self : Any ): '''simple docstring''' for model_name in TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Optional[int] = TFTransfoXLModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @unittest.skip(reason='This model doesn\'t play well with fit() due to not returning a single loss.' ) def __lowercase ( self : Optional[int] ): '''simple docstring''' pass @require_tf class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" @unittest.skip('Skip test until #12651 is resolved.' ) @slow def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : List[str] = TFTransfoXLLMHeadModel.from_pretrained('transfo-xl-wt103' ) # fmt: off _a : str = tf.convert_to_tensor([[33,1297,2,1,1009,4,1109,1_1739,4762,358,5,25,245,22,1706,17,2_0098,5,3215,21,37,1110,3,13,1041,4,24,603,490,2,7_1477,2_0098,10_4447,2,2_0961,1,2604,4,1,329,3,6224,831,1_6002,2,8,603,7_8967,2_9546,23,803,20,25,416,5,8,232,4,277,6,1855,4601,3,2_9546,54,8,3609,5,5_7211,49,4,1,277,18,8,1755,1_5691,3,341,25,416,693,4_2573,71,17,401,94,31,1_7919,2,2_9546,7873,18,1,435,23,1_1011,755,5,5167,3,7983,98,84,2,2_9546,3267,8,3609,4,1,4865,1075,2,6087,71,6,346,8,5854,3,2_9546,824,1400,1868,2,19,160,2,311,8,5496,2,2_0920,17,25,1_5097,3,24,24,0]] ,dtype=tf.intaa ) # noqa: E231 # fmt: on # 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> # fmt: off _a : Any = [33,1297,2,1,1009,4,1109,1_1739,4762,358,5,25,245,22,1706,17,2_0098,5,3215,21,37,1110,3,13,1041,4,24,603,490,2,7_1477,2_0098,10_4447,2,2_0961,1,2604,4,1,329,3,6224,831,1_6002,2,8,603,7_8967,2_9546,23,803,20,25,416,5,8,232,4,277,6,1855,4601,3,2_9546,54,8,3609,5,5_7211,49,4,1,277,18,8,1755,1_5691,3,341,25,416,693,4_2573,71,17,401,94,31,1_7919,2,2_9546,7873,18,1,435,23,1_1011,755,5,5167,3,7983,98,84,2,2_9546,3267,8,3609,4,1,4865,1075,2,6087,71,6,346,8,5854,3,2_9546,824,1400,1868,2,19,160,2,311,8,5496,2,2_0920,17,25,1_5097,3,24,24,0,33,1,1857,2,1,1009,4,1109,1_1739,4762,358,5,25,245,28,1110,3,13,1041,4,24,603,490,2,7_1477,2_0098,10_4447,2,2_0961,1,2604,4,1,329,3,0] # noqa: E231 # fmt: on # In 1991, the remains of Russian Tsar Nicholas II and his family ( # except for Alexei and Maria ) are discovered. The voice of 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. <unk> <unk> <eos> In the 1990s, the remains of Russian Tsar # Nicholas II and his family were discovered. The voice of <unk> young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story.<eos> _a : List[Any] = model.generate(_a ,max_length=200 ,do_sample=_a ) self.assertListEqual(output_ids[0].numpy().tolist() ,_a )
271
'''simple docstring''' import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class UpperCAmelCase__ : """simple docstring""" def __init__( self : int ,_a : Any ,_a : Optional[int]=2 ,_a : Optional[Any]=True ,_a : Dict=False ,_a : Dict=10 ,_a : Any=3 ,_a : str=32 * 8 ,_a : Optional[int]=32 * 8 ,_a : int=4 ,_a : str=64 ,): '''simple docstring''' _a : Dict = parent _a : Union[str, Any] = batch_size _a : Tuple = is_training _a : List[str] = use_auxiliary_loss _a : Optional[Any] = num_queries _a : str = num_channels _a : List[str] = min_size _a : int = max_size _a : Optional[int] = num_labels _a : List[str] = hidden_dim _a : int = hidden_dim def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : Tuple = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( _a ) _a : Optional[Any] = torch.ones([self.batch_size, self.min_size, self.max_size] ,device=_a ) _a : Union[str, Any] = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] ,device=_a ) > 0.5 ).float() _a : Tuple = (torch.rand((self.batch_size, self.num_labels) ,device=_a ) > 0.5).long() _a : Dict = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : int = MaskaFormerConfig( hidden_size=self.hidden_dim ,) _a : str = self.num_queries _a : Union[str, Any] = self.num_labels _a : Tuple = [1, 1, 1, 1] _a : Dict = self.num_channels _a : str = 64 _a : Tuple = 128 _a : Optional[Any] = self.hidden_dim _a : Union[str, Any] = self.hidden_dim _a : List[Any] = self.hidden_dim return config def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a, _a, _a, _a, _a : Optional[Any] = self.prepare_config_and_inputs() _a : str = {'pixel_values': pixel_values, 'pixel_mask': pixel_mask} return config, inputs_dict def __lowercase ( self : List[str] ,_a : Optional[Any] ,_a : str ): '''simple docstring''' _a : str = output.encoder_hidden_states _a : Any = output.pixel_decoder_hidden_states _a : Optional[Any] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(_a ) ,len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_a ) ,len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_a ) ,config.decoder_layers ) def __lowercase ( self : List[str] ,_a : str ,_a : List[Any] ,_a : Any ,_a : Union[str, Any]=False ): '''simple docstring''' with torch.no_grad(): _a : str = MaskaFormerModel(config=_a ) model.to(_a ) model.eval() _a : Any = model(pixel_values=_a ,pixel_mask=_a ) _a : Optional[Any] = model(_a ,output_hidden_states=_a ) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape ,(self.batch_size, self.num_queries, self.hidden_dim) ,) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(_a ,_a ) def __lowercase ( self : Tuple ,_a : List[Any] ,_a : Union[str, Any] ,_a : Tuple ,_a : List[str] ,_a : Any ): '''simple docstring''' _a : int = MaskaFormerForUniversalSegmentation(config=_a ) model.to(_a ) model.eval() def comm_check_on_output(_a : Any ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape ,(self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) ,) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape ,(self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): _a : Any = model(pixel_values=_a ,pixel_mask=_a ) _a : Optional[int] = model(_a ) comm_check_on_output(_a ) _a : List[str] = model( pixel_values=_a ,pixel_mask=_a ,mask_labels=_a ,class_labels=_a ) comm_check_on_output(_a ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape ,torch.Size([1] ) ) @require_torch class UpperCAmelCase__ ( lowercase__ , lowercase__ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Optional[int] = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () __UpperCAmelCase : Dict = {'''feature-extraction''': MaskaFormerModel} if is_torch_available() else {} __UpperCAmelCase : Dict = False __UpperCAmelCase : Tuple = False __UpperCAmelCase : Dict = False __UpperCAmelCase : List[Any] = False def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : Union[str, Any] = MaskaFormerModelTester(self ) _a : Dict = ConfigTester(self ,config_class=_a ,has_text_modality=_a ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' self.config_tester.run_common_tests() def __lowercase ( self : Optional[int] ): '''simple docstring''' _a, _a : List[str] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(_a ,**_a ,output_hidden_states=_a ) def __lowercase ( self : str ): '''simple docstring''' _a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*_a ) @unittest.skip(reason='Mask2Former does not use inputs_embeds' ) def __lowercase ( self : Any ): '''simple docstring''' pass @unittest.skip(reason='Mask2Former does not have a get_input_embeddings method' ) def __lowercase ( self : str ): '''simple docstring''' pass @unittest.skip(reason='Mask2Former is not a generative model' ) def __lowercase ( self : List[Any] ): '''simple docstring''' pass @unittest.skip(reason='Mask2Former does not use token embeddings' ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' pass @require_torch_multi_gpu @unittest.skip( reason='Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def __lowercase ( self : Dict ): '''simple docstring''' pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def __lowercase ( self : List[Any] ): '''simple docstring''' pass def __lowercase ( self : int ): '''simple docstring''' _a, _a : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : Union[str, Any] = model_class(_a ) _a : List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _a : Optional[Any] = [*signature.parameters.keys()] _a : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] ,_a ) @slow def __lowercase ( self : List[str] ): '''simple docstring''' for model_name in ["facebook/mask2former-swin-small-coco-instance"]: _a : Dict = MaskaFormerModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def __lowercase ( self : List[Any] ): '''simple docstring''' _a : int = (self.model_tester.min_size,) * 2 _a : Any = { 'pixel_values': torch.randn((2, 3, *size) ,device=_a ), 'mask_labels': torch.randn((2, 10, *size) ,device=_a ), 'class_labels': torch.zeros(2 ,10 ,device=_a ).long(), } _a : List[Any] = self.model_tester.get_config() _a : int = MaskaFormerForUniversalSegmentation(_a ).to(_a ) _a : str = model(**_a ) self.assertTrue(outputs.loss is not None ) def __lowercase ( self : List[str] ): '''simple docstring''' _a, _a : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(_a ,**_a ,output_hidden_states=_a ) def __lowercase ( self : int ): '''simple docstring''' _a, _a : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : Any = model_class(_a ).to(_a ) _a : Optional[int] = model(**_a ,output_attentions=_a ) self.assertTrue(outputs.attentions is not None ) def __lowercase ( self : Tuple ): '''simple docstring''' if not self.model_tester.is_training: return _a : List[str] = self.all_model_classes[1] _a, _a, _a, _a, _a : List[str] = self.model_tester.prepare_config_and_inputs() _a : Any = model_class(_a ) model.to(_a ) model.train() _a : Union[str, Any] = model(_a ,mask_labels=_a ,class_labels=_a ).loss loss.backward() def __lowercase ( self : int ): '''simple docstring''' _a : int = self.all_model_classes[1] _a, _a, _a, _a, _a : List[Any] = self.model_tester.prepare_config_and_inputs() _a : str = True _a : str = True _a : List[str] = model_class(_a ).to(_a ) model.train() _a : Optional[int] = model(_a ,mask_labels=_a ,class_labels=_a ) _a : Tuple = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() _a : str = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() _a : Dict = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() _a : List[str] = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=_a ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) __lowerCAmelCase = 1e-4 def UpperCAmelCase_ (): """simple docstring""" _a : int = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_vision @slow class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" @cached_property def __lowercase ( self : Union[str, Any] ): '''simple docstring''' return "facebook/mask2former-swin-small-coco-instance" @cached_property def __lowercase ( self : Any ): '''simple docstring''' return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None def __lowercase ( self : Any ): '''simple docstring''' _a : List[str] = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(_a ) _a : int = self.default_image_processor _a : Tuple = prepare_img() _a : Any = image_processor(_a ,return_tensors='pt' ).to(_a ) _a : Union[str, Any] = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(_a ,(1, 3, 384, 384) ) with torch.no_grad(): _a : Optional[Any] = model(**_a ) _a : List[Any] = torch.tensor( [[-0.2790, -1.0717, -1.1668], [-0.5128, -0.3128, -0.4987], [-0.5832, 0.1971, -0.0197]] ).to(_a ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] ,_a ,atol=_a ) ) _a : str = torch.tensor( [[0.8973, 1.1847, 1.1776], [1.1934, 1.5040, 1.5128], [1.1153, 1.4486, 1.4951]] ).to(_a ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] ,_a ,atol=_a ) ) _a : Any = torch.tensor( [[2.1152, 1.7000, -0.8603], [1.5808, 1.8004, -0.9353], [1.6043, 1.7495, -0.5999]] ).to(_a ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] ,_a ,atol=_a ) ) def __lowercase ( self : Tuple ): '''simple docstring''' _a : List[Any] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(_a ).eval() _a : Optional[Any] = self.default_image_processor _a : List[Any] = prepare_img() _a : str = image_processor(_a ,return_tensors='pt' ).to(_a ) _a : Any = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(_a ,(1, 3, 384, 384) ) with torch.no_grad(): _a : Optional[int] = model(**_a ) # masks_queries_logits _a : Dict = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape ,(1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ) _a : Dict = [ [-8.7839, -9.0056, -8.8121], [-7.4104, -7.0313, -6.5401], [-6.6105, -6.3427, -6.4675], ] _a : Optional[Any] = torch.tensor(_a ).to(_a ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] ,_a ,atol=_a ) ) # class_queries_logits _a : str = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape ,(1, model.config.num_queries, model.config.num_labels + 1) ) _a : str = torch.tensor( [ [1.8324, -8.0835, -4.1922], [0.8450, -9.0050, -3.6053], [0.3045, -7.7293, -3.0275], ] ).to(_a ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] ,_a ,atol=_a ) ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a : Any = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(_a ).eval() _a : Tuple = self.default_image_processor _a : Tuple = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] ,segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] ,return_tensors='pt' ,) _a : str = inputs['pixel_values'].to(_a ) _a : str = [el.to(_a ) for el in inputs['mask_labels']] _a : Dict = [el.to(_a ) for el in inputs['class_labels']] with torch.no_grad(): _a : List[str] = model(**_a ) self.assertTrue(outputs.loss is not None )
271
1
'''simple docstring''' from __future__ import annotations def UpperCAmelCase_ (__a : list[list[int]] ): """simple docstring""" for i in range(1 , len(matrix[0] ) ): matrix[0][i] += matrix[0][i - 1] # preprocessing the first column for i in range(1 , len(__a ) ): matrix[i][0] += matrix[i - 1][0] # updating the path cost for current position for i in range(1 , len(__a ) ): for j in range(1 , len(matrix[0] ) ): matrix[i][j] += min(matrix[i - 1][j] , matrix[i][j - 1] ) return matrix[-1][-1] if __name__ == "__main__": import doctest doctest.testmod()
271
'''simple docstring''' import argparse import json from typing import List from ltp import LTP from transformers import BertTokenizer def UpperCAmelCase_ (__a : List[Any] ): """simple docstring""" if ( (cp >= 0x4E_00 and cp <= 0x9F_FF) or (cp >= 0x34_00 and cp <= 0x4D_BF) # or (cp >= 0x2_00_00 and cp <= 0x2_A6_DF) # or (cp >= 0x2_A7_00 and cp <= 0x2_B7_3F) # or (cp >= 0x2_B7_40 and cp <= 0x2_B8_1F) # or (cp >= 0x2_B8_20 and cp <= 0x2_CE_AF) # or (cp >= 0xF9_00 and cp <= 0xFA_FF) or (cp >= 0x2_F8_00 and cp <= 0x2_FA_1F) # ): # return True return False def UpperCAmelCase_ (__a : str ): """simple docstring""" for char in word: _a : Union[str, Any] = ord(__a ) if not _is_chinese_char(__a ): return 0 return 1 def UpperCAmelCase_ (__a : List[str] ): """simple docstring""" _a : Dict = set() for token in tokens: _a : str = len(__a ) > 1 and is_chinese(__a ) if chinese_word: word_set.add(__a ) _a : Optional[Any] = list(__a ) return word_list def UpperCAmelCase_ (__a : List[str] , __a : set() ): """simple docstring""" if not chinese_word_set: return bert_tokens _a : Optional[Any] = max([len(__a ) for w in chinese_word_set] ) _a : Optional[int] = bert_tokens _a, _a : Any = 0, len(__a ) while start < end: _a : Tuple = True if is_chinese(bert_word[start] ): _a : Union[str, Any] = min(end - start , __a ) for i in range(__a , 1 , -1 ): _a : Optional[Any] = ''.join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1 , start + i ): _a : Any = '##' + bert_word[j] _a : Union[str, Any] = start + i _a : int = False break if single_word: start += 1 return bert_word def UpperCAmelCase_ (__a : List[str] , __a : LTP , __a : BertTokenizer ): """simple docstring""" _a : int = [] for i in range(0 , len(__a ) , 1_0_0 ): _a : Union[str, Any] = ltp_tokenizer.seg(lines[i : i + 1_0_0] )[0] _a : Optional[Any] = [get_chinese_word(__a ) for r in res] ltp_res.extend(__a ) assert len(__a ) == len(__a ) _a : str = [] for i in range(0 , len(__a ) , 1_0_0 ): _a : List[str] = bert_tokenizer(lines[i : i + 1_0_0] , add_special_tokens=__a , truncation=__a , max_length=5_1_2 ) bert_res.extend(res['input_ids'] ) assert len(__a ) == len(__a ) _a : List[str] = [] for input_ids, chinese_word in zip(__a , __a ): _a : int = [] for id in input_ids: _a : Optional[int] = bert_tokenizer._convert_id_to_token(__a ) input_tokens.append(__a ) _a : List[str] = add_sub_symbol(__a , __a ) _a : Tuple = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(__a ): if token[:2] == "##": _a : str = token[2:] # save chinese tokens' pos if len(__a ) == 1 and _is_chinese_char(ord(__a ) ): ref_id.append(__a ) ref_ids.append(__a ) assert len(__a ) == len(__a ) return ref_ids def UpperCAmelCase_ (__a : Optional[Any] ): """simple docstring""" with open(args.file_name , 'r' , encoding='utf-8' ) as f: _a : Dict = f.readlines() _a : int = [line.strip() for line in data if len(__a ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' _a : int = LTP(args.ltp ) # faster in GPU device _a : Tuple = BertTokenizer.from_pretrained(args.bert ) _a : int = prepare_ref(__a , __a , __a ) with open(args.save_path , 'w' , encoding='utf-8' ) as f: _a : Optional[Any] = [json.dumps(__a ) + '\n' for ref in ref_ids] f.writelines(__a ) if __name__ == "__main__": __lowerCAmelCase = argparse.ArgumentParser(description="""prepare_chinese_ref""") parser.add_argument( """--file_name""", type=str, default="""./resources/chinese-demo.txt""", help="""file need process, same as training data in lm""", ) parser.add_argument( """--ltp""", type=str, default="""./resources/ltp""", help="""resources for LTP tokenizer, usually a path""" ) parser.add_argument("""--bert""", type=str, default="""./resources/robert""", help="""resources for Bert tokenizer""") parser.add_argument("""--save_path""", type=str, default="""./resources/ref.txt""", help="""path to save res""") __lowerCAmelCase = parser.parse_args() main(args)
271
1
'''simple docstring''' import dataclasses import json import sys import types from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError from copy import copy from enum import Enum from inspect import isclass from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints import yaml __lowerCAmelCase = NewType("""DataClass""", Any) __lowerCAmelCase = NewType("""DataClassType""", Any) def UpperCAmelCase_ (__a : Dict ): """simple docstring""" if isinstance(__a , __a ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise ArgumentTypeError( f"""Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive).""" ) def UpperCAmelCase_ (__a : list ): """simple docstring""" _a : Union[str, Any] = {str(__a ): choice for choice in choices} return lambda __a : str_to_choice.get(__a , __a ) def UpperCAmelCase_ (*, __a : Union[str, List[str]] = None , __a : str = None , __a : Any = dataclasses.MISSING , __a : Callable[[], Any] = dataclasses.MISSING , __a : dict = None , **__a : Tuple , ): """simple docstring""" if metadata is None: # Important, don't use as default param in function signature because dict is mutable and shared across function calls _a : Dict = {} if aliases is not None: _a : List[str] = aliases if help is not None: _a : Optional[int] = help return dataclasses.field(metadata=__a , default=__a , default_factory=__a , **__a ) class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : Iterable[DataClassType] def __init__( self : Any ,_a : Union[DataClassType, Iterable[DataClassType]] ,**_a : Any ): '''simple docstring''' if "formatter_class" not in kwargs: _a : Any = ArgumentDefaultsHelpFormatter super().__init__(**_a ) if dataclasses.is_dataclass(_a ): _a : Optional[Any] = [dataclass_types] _a : Dict = list(_a ) for dtype in self.dataclass_types: self._add_dataclass_arguments(_a ) @staticmethod def __lowercase ( _a : ArgumentParser ,_a : dataclasses.Field ): '''simple docstring''' _a : Dict = F"""--{field.name}""" _a : Optional[Any] = field.metadata.copy() # field.metadata is not used at all by Data Classes, # it is provided as a third-party extension mechanism. if isinstance(field.type ,_a ): raise RuntimeError( 'Unresolved type detected, which should have been done with the help of ' '`typing.get_type_hints` method by default' ) _a : Optional[Any] = kwargs.pop('aliases' ,[] ) if isinstance(_a ,_a ): _a : Dict = [aliases] _a : Optional[int] = getattr(field.type ,'__origin__' ,field.type ) if origin_type is Union or (hasattr(_a ,'UnionType' ) and isinstance(_a ,types.UnionType )): if str not in field.type.__args__ and ( len(field.type.__args__ ) != 2 or type(_a ) not in field.type.__args__ ): raise ValueError( 'Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because' ' the argument parser only supports one type per argument.' F""" Problem encountered in field '{field.name}'.""" ) if type(_a ) not in field.type.__args__: # filter `str` in Union _a : Tuple = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1] _a : Any = getattr(field.type ,'__origin__' ,field.type ) elif bool not in field.type.__args__: # filter `NoneType` in Union (except for `Union[bool, NoneType]`) _a : Tuple = ( field.type.__args__[0] if isinstance(_a ,field.type.__args__[1] ) else field.type.__args__[1] ) _a : List[Any] = getattr(field.type ,'__origin__' ,field.type ) # A variable to store kwargs for a boolean field, if needed # so that we can init a `no_*` complement argument (see below) _a : List[str] = {} if origin_type is Literal or (isinstance(field.type ,_a ) and issubclass(field.type ,_a )): if origin_type is Literal: _a : Optional[Any] = field.type.__args__ else: _a : List[Any] = [x.value for x in field.type] _a : int = make_choice_type_function(kwargs['choices'] ) if field.default is not dataclasses.MISSING: _a : List[str] = field.default else: _a : List[str] = True elif field.type is bool or field.type == Optional[bool]: # Copy the currect kwargs to use to instantiate a `no_*` complement argument below. # We do not initialize it here because the `no_*` alternative must be instantiated after the real argument _a : Dict = copy(_a ) # Hack because type=bool in argparse does not behave as we want. _a : Union[str, Any] = string_to_bool if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING): # Default value is False if we have no default when of type bool. _a : List[str] = False if field.default is dataclasses.MISSING else field.default # This is the value that will get picked if we don't include --field_name in any way _a : Union[str, Any] = default # This tells argparse we accept 0 or 1 value after --field_name _a : Optional[int] = '?' # This is the value that will get picked if we do --field_name (without value) _a : Tuple = True elif isclass(_a ) and issubclass(_a ,_a ): _a : Any = field.type.__args__[0] _a : List[Any] = '+' if field.default_factory is not dataclasses.MISSING: _a : Union[str, Any] = field.default_factory() elif field.default is dataclasses.MISSING: _a : Optional[Any] = True else: _a : str = field.type if field.default is not dataclasses.MISSING: _a : List[Any] = field.default elif field.default_factory is not dataclasses.MISSING: _a : Any = field.default_factory() else: _a : Union[str, Any] = True parser.add_argument(_a ,*_a ,**_a ) # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added. # Order is important for arguments with the same destination! # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down # here and we do not need those changes/additional keys. if field.default is True and (field.type is bool or field.type == Optional[bool]): _a : List[str] = False parser.add_argument(F"""--no_{field.name}""" ,action='store_false' ,dest=field.name ,**_a ) def __lowercase ( self : Optional[int] ,_a : DataClassType ): '''simple docstring''' if hasattr(_a ,'_argument_group_name' ): _a : int = self.add_argument_group(dtype._argument_group_name ) else: _a : List[str] = self try: _a : Dict[str, type] = get_type_hints(_a ) except NameError: raise RuntimeError( F"""Type resolution failed for {dtype}. Try declaring the class in global scope or """ 'removing line of `from __future__ import annotations` which opts in Postponed ' 'Evaluation of Annotations (PEP 563)' ) except TypeError as ex: # Remove this block when we drop Python 3.9 support if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(_a ): _a : Optional[int] = '.'.join(map(_a ,sys.version_info[:3] ) ) raise RuntimeError( F"""Type resolution failed for {dtype} on Python {python_version}. Try removing """ 'line of `from __future__ import annotations` which opts in union types as ' '`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To ' 'support Python versions that lower than 3.10, you need to use ' '`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of ' '`X | None`.' ) from ex raise for field in dataclasses.fields(_a ): if not field.init: continue _a : str = type_hints[field.name] self._parse_dataclass_field(_a ,_a ) def __lowercase ( self : Union[str, Any] ,_a : Optional[Any]=None ,_a : Optional[int]=False ,_a : Optional[int]=True ,_a : str=None ,_a : List[Any]=None ,): '''simple docstring''' if args_file_flag or args_filename or (look_for_args_file and len(sys.argv )): _a : List[str] = [] if args_filename: args_files.append(Path(_a ) ) elif look_for_args_file and len(sys.argv ): args_files.append(Path(sys.argv[0] ).with_suffix('.args' ) ) # args files specified via command line flag should overwrite default args files so we add them last if args_file_flag: # Create special parser just to extract the args_file_flag values _a : Optional[Any] = ArgumentParser() args_file_parser.add_argument(_a ,type=_a ,action='append' ) # Use only remaining args for further parsing (remove the args_file_flag) _a, _a : List[Any] = args_file_parser.parse_known_args(args=_a ) _a : Optional[Any] = vars(_a ).get(args_file_flag.lstrip('-' ) ,_a ) if cmd_args_file_paths: args_files.extend([Path(_a ) for p in cmd_args_file_paths] ) _a : Optional[int] = [] for args_file in args_files: if args_file.exists(): file_args += args_file.read_text().split() # in case of duplicate arguments the last one has precedence # args specified via the command line should overwrite args from files, so we add them last _a : Optional[int] = file_args + args if args is not None else file_args + sys.argv[1:] _a, _a : int = self.parse_known_args(args=_a ) _a : Tuple = [] for dtype in self.dataclass_types: _a : Optional[int] = {f.name for f in dataclasses.fields(_a ) if f.init} _a : List[Any] = {k: v for k, v in vars(_a ).items() if k in keys} for k in keys: delattr(_a ,_a ) _a : Union[str, Any] = dtype(**_a ) outputs.append(_a ) if len(namespace.__dict__ ) > 0: # additional namespace. outputs.append(_a ) if return_remaining_strings: return (*outputs, remaining_args) else: if remaining_args: raise ValueError(F"""Some specified arguments are not used by the HfArgumentParser: {remaining_args}""" ) return (*outputs,) def __lowercase ( self : Any ,_a : Dict[str, Any] ,_a : bool = False ): '''simple docstring''' _a : int = set(args.keys() ) _a : int = [] for dtype in self.dataclass_types: _a : str = {f.name for f in dataclasses.fields(_a ) if f.init} _a : Any = {k: v for k, v in args.items() if k in keys} unused_keys.difference_update(inputs.keys() ) _a : Dict = dtype(**_a ) outputs.append(_a ) if not allow_extra_keys and unused_keys: raise ValueError(F"""Some keys are not used by the HfArgumentParser: {sorted(_a )}""" ) return tuple(_a ) def __lowercase ( self : str ,_a : str ,_a : bool = False ): '''simple docstring''' with open(Path(_a ) ,encoding='utf-8' ) as open_json_file: _a : Tuple = json.loads(open_json_file.read() ) _a : List[str] = self.parse_dict(_a ,allow_extra_keys=_a ) return tuple(_a ) def __lowercase ( self : Tuple ,_a : str ,_a : bool = False ): '''simple docstring''' _a : Tuple = self.parse_dict(yaml.safe_load(Path(_a ).read_text() ) ,allow_extra_keys=_a ) return tuple(_a )
271
'''simple docstring''' import warnings from ...utils import logging from .image_processing_videomae import VideoMAEImageProcessor __lowerCAmelCase = logging.get_logger(__name__) class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" def __init__( self : Tuple ,*_a : List[str] ,**_a : Any ): '''simple docstring''' warnings.warn( 'The class VideoMAEFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use VideoMAEImageProcessor instead.' ,_a ,) super().__init__(*_a ,**_a )
271
1
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = {"""vocab_file""": """sentencepiece.bpe.model"""} __lowerCAmelCase = { """vocab_file""": { """camembert-base""": """https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model""", } } __lowerCAmelCase = { """camembert-base""": 5_1_2, } __lowerCAmelCase = """▁""" class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : Tuple = VOCAB_FILES_NAMES __UpperCAmelCase : Tuple = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Optional[int] = ['''input_ids''', '''attention_mask'''] def __init__( self : Tuple ,_a : int ,_a : List[Any]="<s>" ,_a : Union[str, Any]="</s>" ,_a : Dict="</s>" ,_a : List[str]="<s>" ,_a : Union[str, Any]="<unk>" ,_a : str="<pad>" ,_a : List[str]="<mask>" ,_a : List[Any]=["<s>NOTUSED", "</s>NOTUSED"] ,_a : Optional[Dict[str, Any]] = None ,**_a : List[Any] ,): '''simple docstring''' _a : Optional[Any] = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else mask_token _a : Any = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_a ,eos_token=_a ,unk_token=_a ,sep_token=_a ,cls_token=_a ,pad_token=_a ,mask_token=_a ,additional_special_tokens=_a ,sp_model_kwargs=self.sp_model_kwargs ,**_a ,) _a : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_a ) ) _a : Any = vocab_file # HACK: These tokens were added by fairseq but don't seem to be actually used when duplicated in the actual # sentencepiece vocabulary (this is the case for <s> and </s> _a : Union[str, Any] = {'<s>NOTUSED': 0, '<pad>': 1, '</s>NOTUSED': 2, '<unk>': 3} _a : List[str] = len(self.fairseq_tokens_to_ids ) _a : int = len(self.sp_model ) + len(self.fairseq_tokens_to_ids ) _a : str = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __lowercase ( self : Any ,_a : List[int] ,_a : Optional[List[int]] = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _a : Optional[int] = [self.cls_token_id] _a : Union[str, Any] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def __lowercase ( self : List[str] ,_a : List[int] ,_a : Optional[List[int]] = None ,_a : bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a ,token_ids_a=_a ,already_has_special_tokens=_a ) if token_ids_a is None: return [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1, 1] + ([0] * len(_a )) + [1] def __lowercase ( self : Any ,_a : List[int] ,_a : Optional[List[int]] = None ): '''simple docstring''' _a : Optional[int] = [self.sep_token_id] _a : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def __lowercase ( self : str ): '''simple docstring''' return len(self.fairseq_tokens_to_ids ) + len(self.sp_model ) def __lowercase ( self : Dict ): '''simple docstring''' _a : List[Any] = {self.convert_ids_to_tokens(_a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __lowercase ( self : Tuple ,_a : str ): '''simple docstring''' return self.sp_model.encode(_a ,out_type=_a ) def __lowercase ( self : Any ,_a : str ): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] elif self.sp_model.PieceToId(_a ) == 0: # Convert sentence piece unk token to fairseq unk token index return self.unk_token_id return self.fairseq_offset + self.sp_model.PieceToId(_a ) def __lowercase ( self : List[Any] ,_a : Optional[Any] ): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def __lowercase ( self : Union[str, Any] ,_a : List[Any] ): '''simple docstring''' _a : str = [] _a : int = '' _a : Dict = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_a ) + token _a : Optional[Any] = True _a : Dict = [] else: current_sub_tokens.append(_a ) _a : str = False out_string += self.sp_model.decode(_a ) return out_string.strip() def __getstate__( self : Dict ): '''simple docstring''' _a : Tuple = self.__dict__.copy() _a : Tuple = None return state def __setstate__( self : Dict ,_a : List[Any] ): '''simple docstring''' _a : List[Any] = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs' ): _a : Dict = {} _a : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __lowercase ( self : List[Any] ,_a : str ,_a : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(_a ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _a : Any = os.path.join( _a ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,_a ) elif not os.path.isfile(self.vocab_file ): with open(_a ,'wb' ) as fi: _a : Optional[int] = self.sp_model.serialized_model_proto() fi.write(_a ) return (out_vocab_file,)
271
'''simple docstring''' from __future__ import annotations from random import choice def UpperCAmelCase_ (__a : str ): """simple docstring""" return choice(__a ) def UpperCAmelCase_ (__a : list[int] , __a : int ): """simple docstring""" _a : Dict = random_pivot(__a ) # partition based on pivot # linear time _a : Optional[int] = [e for e in lst if e < pivot] _a : List[str] = [e for e in lst if e > pivot] # if we get lucky, pivot might be the element we want. # we can easily see this: # small (elements smaller than k) # + pivot (kth element) # + big (elements larger than k) if len(__a ) == k - 1: return pivot # pivot is in elements bigger than k elif len(__a ) < k - 1: return kth_number(__a , k - len(__a ) - 1 ) # pivot is in elements smaller than k else: return kth_number(__a , __a ) if __name__ == "__main__": import doctest doctest.testmod()
271
1
'''simple docstring''' import unittest from transformers import BigBirdConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax from transformers.models.big_bird.modeling_flax_big_bird import ( FlaxBigBirdForCausalLM, FlaxBigBirdForMaskedLM, FlaxBigBirdForMultipleChoice, FlaxBigBirdForPreTraining, FlaxBigBirdForQuestionAnswering, FlaxBigBirdForSequenceClassification, FlaxBigBirdForTokenClassification, FlaxBigBirdModel, ) class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self : Any ,_a : Optional[int] ,_a : Dict=2 ,_a : List[str]=56 ,_a : Tuple=True ,_a : Optional[Any]=True ,_a : str=True ,_a : Union[str, Any]=True ,_a : List[str]=99 ,_a : Any=32 ,_a : Tuple=2 ,_a : Optional[Any]=2 ,_a : str=7 ,_a : Any="gelu_new" ,_a : Tuple=0.1 ,_a : List[Any]=0.1 ,_a : Optional[int]=512 ,_a : List[str]=16 ,_a : Optional[Any]=2 ,_a : Dict=0.02 ,_a : List[Any]=4 ,_a : str="block_sparse" ,_a : Optional[Any]=True ,_a : List[str]=False ,_a : Dict=2 ,_a : Optional[Any]=3 ,): '''simple docstring''' _a : str = parent _a : Optional[int] = batch_size _a : Tuple = seq_length _a : List[str] = is_training _a : Any = use_attention_mask _a : int = use_token_type_ids _a : Optional[Any] = use_labels _a : Union[str, Any] = vocab_size _a : Dict = hidden_size _a : Optional[int] = num_hidden_layers _a : Tuple = num_attention_heads _a : Union[str, Any] = intermediate_size _a : List[str] = hidden_act _a : List[str] = hidden_dropout_prob _a : Tuple = attention_probs_dropout_prob _a : Any = max_position_embeddings _a : Optional[Any] = type_vocab_size _a : int = type_sequence_label_size _a : Union[str, Any] = initializer_range _a : Optional[int] = num_choices _a : Union[str, Any] = rescale_embeddings _a : Dict = attention_type _a : Any = use_bias _a : Union[str, Any] = block_size _a : List[Any] = num_random_blocks def __lowercase ( self : List[str] ): '''simple docstring''' _a : List[str] = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) _a : Optional[int] = None if self.use_attention_mask: _a : int = random_attention_mask([self.batch_size, self.seq_length] ) _a : Union[str, Any] = None if self.use_token_type_ids: _a : Optional[int] = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) _a : Optional[int] = BigBirdConfig( 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=_a ,initializer_range=self.initializer_range ,attention_type=self.attention_type ,block_size=self.block_size ,num_random_blocks=self.num_random_blocks ,use_bias=self.use_bias ,rescale_embeddings=self.rescale_embeddings ,) return config, input_ids, token_type_ids, attention_mask def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : Dict = self.prepare_config_and_inputs() _a, _a, _a, _a : List[str] = config_and_inputs _a : str = { 'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': attention_mask, } return config, inputs_dict @require_flax class UpperCAmelCase__ ( lowercase__ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = ( ( FlaxBigBirdForCausalLM, FlaxBigBirdModel, FlaxBigBirdForPreTraining, FlaxBigBirdForMaskedLM, FlaxBigBirdForMultipleChoice, FlaxBigBirdForQuestionAnswering, FlaxBigBirdForSequenceClassification, FlaxBigBirdForTokenClassification, ) if is_flax_available() else () ) __UpperCAmelCase : List[str] = False __UpperCAmelCase : Any = False def __lowercase ( self : List[str] ): '''simple docstring''' _a : Dict = FlaxBigBirdModelTester(self ) @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def __lowercase ( self : Any ): '''simple docstring''' super().test_from_pretrained_save_pretrained() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def __lowercase ( self : Union[str, Any] ): '''simple docstring''' super().test_from_pretrained_with_no_automatic_init() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def __lowercase ( self : Optional[Any] ): '''simple docstring''' super().test_no_automatic_init() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def __lowercase ( self : Optional[int] ): '''simple docstring''' super().test_hidden_states_output() @slow def __lowercase ( self : Tuple ): '''simple docstring''' for model_class_name in self.all_model_classes: _a : Optional[Any] = model_class_name.from_pretrained('google/bigbird-roberta-base' ) self.assertIsNotNone(_a ) def __lowercase ( self : List[str] ): '''simple docstring''' if self.test_attn_probs: super().test_attention_outputs() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def __lowercase ( self : List[Any] ): '''simple docstring''' _a, _a : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): _a : Optional[Any] = self._prepare_for_class(_a ,_a ) _a : Union[str, Any] = model_class(_a ) @jax.jit def model_jitted(_a : int ,_a : Union[str, Any]=None ,**_a : Any ): return model(input_ids=_a ,attention_mask=_a ,**_a ) with self.subTest('JIT Enabled' ): _a : List[str] = model_jitted(**_a ).to_tuple() with self.subTest('JIT Disabled' ): with jax.disable_jit(): _a : List[str] = model_jitted(**_a ).to_tuple() self.assertEqual(len(_a ) ,len(_a ) ) for jitted_output, output in zip(_a ,_a ): self.assertEqual(jitted_output.shape ,output.shape ) def __lowercase ( self : Optional[int] ,_a : List[Any] ,_a : Any ,_a : str ,_a : List[Any]=1E-5 ,_a : Any="outputs" ,_a : Optional[Any]=None ): '''simple docstring''' if name.startswith('outputs.attentions' ): return else: super().check_pt_flax_outputs(_a ,_a ,_a ,_a ,_a ,_a )
271
'''simple docstring''' class UpperCAmelCase__ : """simple docstring""" def __init__( self : Dict ): '''simple docstring''' _a : Dict = {} def __lowercase ( self : Union[str, Any] ): '''simple docstring''' print(self.vertex ) for i in self.vertex: print(_a ,' -> ' ,' -> '.join([str(_a ) for j in self.vertex[i]] ) ) def __lowercase ( self : Dict ,_a : int ,_a : int ): '''simple docstring''' if from_vertex in self.vertex: self.vertex[from_vertex].append(_a ) else: # else make a new vertex _a : int = [to_vertex] def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : Tuple = [False] * len(self.vertex ) # call the recursive helper function for i in range(len(self.vertex ) ): if not visited[i]: self.dfs_recursive(_a ,_a ) def __lowercase ( self : Union[str, Any] ,_a : int ,_a : list ): '''simple docstring''' _a : List[Any] = True print(_a ,end=' ' ) # Recur for all the vertices that are adjacent to this node for i in self.vertex: if not visited[i]: self.dfs_recursive(_a ,_a ) if __name__ == "__main__": __lowerCAmelCase = Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) g.print_graph() print("""DFS:""") g.dfs() # OUTPUT: # 0 -> 1 -> 2 # 1 -> 2 # 2 -> 0 -> 3 # 3 -> 3 # DFS: # 0 1 2 3
271
1
'''simple docstring''' def UpperCAmelCase_ (__a : Any ): """simple docstring""" stooge(__a , 0 , len(__a ) - 1 ) return arr def UpperCAmelCase_ (__a : int , __a : Union[str, Any] , __a : Any ): """simple docstring""" if i >= h: return # If first element is smaller than the last then swap them if arr[i] > arr[h]: _a, _a : Any = arr[h], arr[i] # If there are more than 2 elements in the array if h - i + 1 > 2: _a : Dict = (int)((h - i + 1) / 3 ) # Recursively sort first 2/3 elements stooge(__a , __a , (h - t) ) # Recursively sort last 2/3 elements stooge(__a , i + t , (__a) ) # Recursively sort first 2/3 elements stooge(__a , __a , (h - t) ) if __name__ == "__main__": __lowerCAmelCase = input("""Enter numbers separated by a comma:\n""").strip() __lowerCAmelCase = [int(item) for item in user_input.split(""",""")] print(stooge_sort(unsorted))
271
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = """▁""" __lowerCAmelCase = {"""vocab_file""": """sentencepiece.bpe.model""", """monolingual_vocab_file""": """dict.txt"""} __lowerCAmelCase = { """vocab_file""": { """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model""", }, """monolingual_vocab_file""": { """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt""", }, } __lowerCAmelCase = {"""vinai/bartpho-syllable""": 1_0_2_4} class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : Optional[Any] = VOCAB_FILES_NAMES __UpperCAmelCase : Dict = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Dict = ['''input_ids''', '''attention_mask'''] def __init__( self : str ,_a : str ,_a : Any ,_a : Any="<s>" ,_a : Dict="</s>" ,_a : int="</s>" ,_a : Union[str, Any]="<s>" ,_a : List[Any]="<unk>" ,_a : Optional[Any]="<pad>" ,_a : List[str]="<mask>" ,_a : Optional[Dict[str, Any]] = None ,**_a : int ,): '''simple docstring''' _a : Any = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else mask_token _a : Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_a ,eos_token=_a ,unk_token=_a ,sep_token=_a ,cls_token=_a ,pad_token=_a ,mask_token=_a ,sp_model_kwargs=self.sp_model_kwargs ,**_a ,) _a : Optional[int] = vocab_file _a : Union[str, Any] = monolingual_vocab_file _a : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_a ) ) # Load the reduced vocab # Keep order of special tokens for backward compatibility _a : Union[str, Any] = {} _a : int = 0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(_a ) not in self.fairseq_tokens_to_ids: _a : int = cnt cnt += 1 with open(_a ,'r' ,encoding='utf-8' ) as f: for line in f.readlines(): _a : str = line.strip().split()[0] _a : Tuple = len(self.fairseq_tokens_to_ids ) if str(_a ) not in self.fairseq_tokens_to_ids: _a : List[str] = len(self.fairseq_tokens_to_ids ) _a : Tuple = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : Union[str, Any] ): '''simple docstring''' _a : int = self.__dict__.copy() _a : str = None _a : Optional[Any] = self.sp_model.serialized_model_proto() return state def __setstate__( self : Tuple ,_a : Tuple ): '''simple docstring''' _a : Tuple = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs' ): _a : List[str] = {} _a : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def __lowercase ( self : Dict ,_a : List[int] ,_a : Optional[List[int]] = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _a : Dict = [self.cls_token_id] _a : int = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def __lowercase ( self : int ,_a : List[int] ,_a : Optional[List[int]] = None ,_a : bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a ,token_ids_a=_a ,already_has_special_tokens=_a ) if token_ids_a is None: return [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1, 1] + ([0] * len(_a )) + [1] def __lowercase ( self : Tuple ,_a : List[int] ,_a : Optional[List[int]] = None ): '''simple docstring''' _a : List[str] = [self.sep_token_id] _a : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def __lowercase ( self : Dict ): '''simple docstring''' return len(self.fairseq_ids_to_tokens ) def __lowercase ( self : Dict ): '''simple docstring''' _a : List[str] = {self.convert_ids_to_tokens(_a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __lowercase ( self : Tuple ,_a : str ): '''simple docstring''' return self.sp_model.encode(_a ,out_type=_a ) def __lowercase ( self : Union[str, Any] ,_a : Union[str, Any] ): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def __lowercase ( self : Any ,_a : int ): '''simple docstring''' return self.fairseq_ids_to_tokens[index] def __lowercase ( self : Tuple ,_a : Union[str, Any] ): '''simple docstring''' _a : str = ''.join(_a ).replace(_a ,' ' ).strip() return out_string def __lowercase ( self : Union[str, Any] ,_a : str ,_a : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(_a ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _a : int = os.path.join( _a ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) _a : int = os.path.join( _a ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['monolingual_vocab_file'] ,) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,_a ) elif not os.path.isfile(self.vocab_file ): with open(_a ,'wb' ) as fi: _a : List[Any] = self.sp_model.serialized_model_proto() fi.write(_a ) if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath( _a ) and os.path.isfile(self.monolingual_vocab_file ): copyfile(self.monolingual_vocab_file ,_a ) elif not os.path.isfile(self.monolingual_vocab_file ): with open(_a ,'w' ,encoding='utf-8' ) as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(F"""{str(_a )} \n""" ) return out_vocab_file, out_monolingual_vocab_file
271
1
'''simple docstring''' from typing import List from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = { """snap-research/efficientformer-l1-300""": ( """https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json""" ), } class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : Tuple = '''efficientformer''' def __init__( self : Optional[int] ,_a : List[int] = [3, 2, 6, 4] ,_a : List[int] = [48, 96, 224, 448] ,_a : List[bool] = [True, True, True, True] ,_a : int = 448 ,_a : int = 32 ,_a : int = 4 ,_a : int = 7 ,_a : int = 5 ,_a : int = 8 ,_a : int = 4 ,_a : float = 0.0 ,_a : int = 16 ,_a : int = 3 ,_a : int = 3 ,_a : int = 3 ,_a : int = 2 ,_a : int = 1 ,_a : float = 0.0 ,_a : int = 1 ,_a : bool = True ,_a : bool = True ,_a : float = 1E-5 ,_a : str = "gelu" ,_a : float = 0.02 ,_a : float = 1E-12 ,_a : int = 224 ,_a : float = 1E-05 ,**_a : Union[str, Any] ,): '''simple docstring''' super().__init__(**_a ) _a : Union[str, Any] = hidden_act _a : Union[str, Any] = hidden_dropout_prob _a : Optional[int] = hidden_sizes _a : int = num_hidden_layers _a : Optional[int] = num_attention_heads _a : str = initializer_range _a : List[str] = layer_norm_eps _a : List[Any] = patch_size _a : Optional[int] = num_channels _a : List[str] = depths _a : int = mlp_expansion_ratio _a : List[Any] = downsamples _a : Any = dim _a : Tuple = key_dim _a : Union[str, Any] = attention_ratio _a : Union[str, Any] = resolution _a : Union[str, Any] = pool_size _a : Tuple = downsample_patch_size _a : Tuple = downsample_stride _a : str = downsample_pad _a : str = drop_path_rate _a : List[str] = num_metaad_blocks _a : Any = distillation _a : Any = use_layer_scale _a : Optional[Any] = layer_scale_init_value _a : str = image_size _a : List[str] = batch_norm_eps
271
'''simple docstring''' import numpy as np from transformers import BatchFeature from transformers.testing_utils import require_tf, require_torch from .test_feature_extraction_common import FeatureExtractionSavingTestMixin class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = None __UpperCAmelCase : List[Any] = None @property def __lowercase ( self : Dict ): '''simple docstring''' return self.feat_extract_tester.prepare_feat_extract_dict() def __lowercase ( self : str ): '''simple docstring''' _a : Dict = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(_a ,'feature_size' ) ) self.assertTrue(hasattr(_a ,'sampling_rate' ) ) self.assertTrue(hasattr(_a ,'padding_value' ) ) def __lowercase ( self : int ): '''simple docstring''' _a : Any = self.feat_extract_tester.prepare_inputs_for_common() _a : str = self.feature_extraction_class(**self.feat_extract_dict ) _a : int = feat_extract.model_input_names[0] _a : List[Any] = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(_a ) == len(_a ) for x, y in zip(_a ,processed_features[input_name] ) ) ) _a : Any = self.feat_extract_tester.prepare_inputs_for_common(equal_length=_a ) _a : Union[str, Any] = BatchFeature({input_name: speech_inputs} ,tensor_type='np' ) _a : Union[str, Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: _a : Optional[int] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_torch def __lowercase ( self : Any ): '''simple docstring''' _a : List[Any] = self.feat_extract_tester.prepare_inputs_for_common(equal_length=_a ) _a : Dict = self.feature_extraction_class(**self.feat_extract_dict ) _a : int = feat_extract.model_input_names[0] _a : str = BatchFeature({input_name: speech_inputs} ,tensor_type='pt' ) _a : str = processed_features[input_name] if len(batch_features_input.shape ) < 3: _a : str = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_tf def __lowercase ( self : int ): '''simple docstring''' _a : int = self.feat_extract_tester.prepare_inputs_for_common(equal_length=_a ) _a : Dict = self.feature_extraction_class(**self.feat_extract_dict ) _a : Tuple = feat_extract.model_input_names[0] _a : int = BatchFeature({input_name: speech_inputs} ,tensor_type='tf' ) _a : Optional[int] = processed_features[input_name] if len(batch_features_input.shape ) < 3: _a : Optional[Any] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) def __lowercase ( self : Dict ,_a : Any=False ): '''simple docstring''' def _inputs_have_equal_length(_a : Tuple ): _a : Tuple = len(input[0] ) for input_slice in input[1:]: if len(_a ) != length: return False return True def _inputs_are_equal(_a : Optional[Any] ,_a : Union[str, Any] ): if len(_a ) != len(_a ): return False for input_slice_a, input_slice_a in zip(_a ,_a ): if not np.allclose(np.asarray(_a ) ,np.asarray(_a ) ,atol=1E-3 ): return False return True _a : int = self.feature_extraction_class(**self.feat_extract_dict ) _a : Tuple = self.feat_extract_tester.prepare_inputs_for_common(numpify=_a ) _a : Union[str, Any] = feat_extract.model_input_names[0] _a : Tuple = BatchFeature({input_name: speech_inputs} ) _a : str = self.feat_extract_tester.seq_length_diff _a : Dict = self.feat_extract_tester.max_seq_length + pad_diff _a : Dict = self.feat_extract_tester.min_seq_length _a : Optional[Any] = self.feat_extract_tester.batch_size _a : Tuple = self.feat_extract_tester.feature_size # test padding for List[int] + numpy _a : int = feat_extract.pad(_a ,padding=_a ) _a : List[Any] = input_a[input_name] _a : Tuple = feat_extract.pad(_a ,padding='longest' ) _a : Any = input_a[input_name] _a : Optional[Any] = feat_extract.pad(_a ,padding='max_length' ,max_length=len(speech_inputs[-1] ) ) _a : List[str] = input_a[input_name] _a : List[str] = feat_extract.pad(_a ,padding='longest' ,return_tensors='np' ) _a : str = input_a[input_name] # max_length parameter has to be provided when setting `padding="max_length"` with self.assertRaises(_a ): feat_extract.pad(_a ,padding='max_length' )[input_name] _a : int = feat_extract.pad( _a ,padding='max_length' ,max_length=_a ,return_tensors='np' ) _a : Optional[int] = input_a[input_name] self.assertFalse(_inputs_have_equal_length(_a ) ) self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertTrue(_inputs_are_equal(_a ,_a ) ) self.assertTrue(len(input_a[0] ) == pad_min_length ) self.assertTrue(len(input_a[1] ) == pad_min_length + pad_diff ) self.assertTrue(input_a.shape[:2] == (batch_size, len(input_a[0] )) ) self.assertTrue(input_a.shape[:2] == (batch_size, pad_max_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == input_a.shape[2] == feature_size ) # test padding for `pad_to_multiple_of` for List[int] + numpy _a : Tuple = feat_extract.pad(_a ,pad_to_multiple_of=10 ) _a : List[str] = input_a[input_name] _a : str = feat_extract.pad(_a ,padding='longest' ,pad_to_multiple_of=10 ) _a : Tuple = input_a[input_name] _a : Optional[int] = feat_extract.pad( _a ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=_a ) _a : Any = input_a[input_name] _a : Optional[int] = feat_extract.pad( _a ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=_a ,return_tensors='np' ,) _a : Dict = input_a[input_name] self.assertTrue(all(len(_a ) % 10 == 0 for x in input_a ) ) self.assertTrue(_inputs_are_equal(_a ,_a ) ) _a : List[str] = pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10 self.assertTrue(all(len(_a ) == expected_mult_pad_length for x in input_a ) ) self.assertEqual(input_a.shape[:2] ,(batch_size, expected_mult_pad_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == feature_size ) # Check padding value is correct _a : Any = (np.ones(self.feat_extract_tester.feature_size ) * feat_extract.padding_value).sum() self.assertTrue( abs(np.asarray(input_a[0] )[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1E-3 ) self.assertTrue( abs( np.asarray(input_a[1] )[pad_min_length + pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff) ) < 1E-3 ) self.assertTrue( abs( np.asarray(input_a[2] )[pad_min_length + 2 * pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff) ) < 1E-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1E-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length) ) < 1E-3 ) def __lowercase ( self : List[Any] ,_a : Optional[int]=False ): '''simple docstring''' def _inputs_have_equal_length(_a : List[str] ): _a : Union[str, Any] = len(input[0] ) for input_slice in input[1:]: if len(_a ) != length: return False return True def _inputs_are_equal(_a : List[str] ,_a : List[str] ): if len(_a ) != len(_a ): return False for input_slice_a, input_slice_a in zip(_a ,_a ): if not np.allclose(np.asarray(_a ) ,np.asarray(_a ) ,atol=1E-3 ): return False return True _a : Dict = self.feature_extraction_class(**self.feat_extract_dict ) _a : str = self.feat_extract_tester.prepare_inputs_for_common(numpify=_a ) _a : Any = feat_extract.model_input_names[0] _a : List[Any] = BatchFeature({input_name: speech_inputs} ) # truncate to smallest _a : Union[str, Any] = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,truncation=_a ) _a : str = input_a[input_name] _a : List[str] = feat_extract.pad(_a ,padding='max_length' ,max_length=len(speech_inputs[0] ) ) _a : Tuple = input_a[input_name] self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertFalse(_inputs_have_equal_length(_a ) ) # truncate to smallest with np _a : Dict = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ,truncation=_a ,) _a : Any = input_a[input_name] _a : List[Any] = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ) _a : int = input_a[input_name] self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertTrue(input_a.shape[1] == len(speech_inputs[0] ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(_a ) ) # truncate to middle _a : Dict = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=_a ,return_tensors='np' ,) _a : List[Any] = input_a[input_name] _a : Tuple = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=_a ) _a : Tuple = input_a[input_name] _a : Tuple = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,return_tensors='np' ) _a : Dict = input_a[input_name] self.assertTrue(input_a.shape[1] == len(speech_inputs[1] ) ) self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertTrue(_inputs_are_equal(_a ,_a ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(_a ) ) self.assertTrue(len(input_a[-1] ) == len(speech_inputs[-1] ) ) # padding has to be max_length when setting `truncation=True` with self.assertRaises(_a ): feat_extract.pad(_a ,truncation=_a )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(_a ): feat_extract.pad(_a ,padding='longest' ,truncation=_a )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(_a ): feat_extract.pad(_a ,padding='longest' ,truncation=_a )[input_name] # max_length parameter has to be provided when setting `truncation=True` and padding="max_length" with self.assertRaises(_a ): feat_extract.pad(_a ,padding='max_length' ,truncation=_a )[input_name] # test truncation for `pad_to_multiple_of` for List[int] + numpy _a : Optional[Any] = 12 _a : List[Any] = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=_a ,truncation=_a ,) _a : Tuple = input_a[input_name] _a : str = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=_a ,) _a : List[Any] = input_a[input_name] # retrieve expected_length as multiple of pad_to_multiple_of _a : List[Any] = len(speech_inputs[0] ) if expected_length % pad_to_multiple_of != 0: _a : Union[str, Any] = ((len(speech_inputs[0] ) // pad_to_multiple_of) + 1) * pad_to_multiple_of self.assertTrue(len(input_a[0] ) == expected_length ) self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertFalse(_inputs_have_equal_length(_a ) ) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' self._check_padding(numpify=_a ) def __lowercase ( self : Tuple ): '''simple docstring''' self._check_padding(numpify=_a ) def __lowercase ( self : Dict ): '''simple docstring''' self._check_truncation(numpify=_a ) def __lowercase ( self : str ): '''simple docstring''' self._check_truncation(numpify=_a ) @require_torch def __lowercase ( self : Dict ): '''simple docstring''' _a : Any = self.feature_extraction_class(**self.feat_extract_dict ) _a : List[Any] = self.feat_extract_tester.prepare_inputs_for_common() _a : Union[str, Any] = feat_extract.model_input_names[0] _a : Optional[int] = BatchFeature({input_name: speech_inputs} ) _a : List[Any] = feat_extract.pad(_a ,padding='longest' ,return_tensors='np' )[input_name] _a : List[str] = feat_extract.pad(_a ,padding='longest' ,return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1E-2 ) @require_tf def __lowercase ( self : int ): '''simple docstring''' _a : List[str] = self.feature_extraction_class(**self.feat_extract_dict ) _a : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_common() _a : Dict = feat_extract.model_input_names[0] _a : Optional[Any] = BatchFeature({input_name: speech_inputs} ) _a : Dict = feat_extract.pad(_a ,padding='longest' ,return_tensors='np' )[input_name] _a : Any = feat_extract.pad(_a ,padding='longest' ,return_tensors='tf' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_tf.numpy().astype(np.floataa ).sum() ) < 1E-2 ) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : str = self.feat_extract_dict _a : List[Any] = True _a : Optional[int] = self.feature_extraction_class(**_a ) _a : List[Any] = self.feat_extract_tester.prepare_inputs_for_common() _a : Tuple = [len(_a ) for x in speech_inputs] _a : int = feat_extract.model_input_names[0] _a : Optional[Any] = BatchFeature({input_name: speech_inputs} ) _a : str = feat_extract.pad(_a ,padding='longest' ,return_tensors='np' ) self.assertIn('attention_mask' ,_a ) self.assertListEqual(list(processed.attention_mask.shape ) ,list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() ,_a ) def __lowercase ( self : int ): '''simple docstring''' _a : Any = self.feat_extract_dict _a : Tuple = True _a : Optional[int] = self.feature_extraction_class(**_a ) _a : Dict = self.feat_extract_tester.prepare_inputs_for_common() _a : Dict = [len(_a ) for x in speech_inputs] _a : Union[str, Any] = feat_extract.model_input_names[0] _a : Any = BatchFeature({input_name: speech_inputs} ) _a : List[Any] = min(_a ) _a : Dict = feat_extract.pad( _a ,padding='max_length' ,max_length=_a ,truncation=_a ,return_tensors='np' ) self.assertIn('attention_mask' ,_a ) self.assertListEqual( list(processed_pad.attention_mask.shape ) ,[processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() ,[max_length for x in speech_inputs] )
271
1
'''simple docstring''' import math import tensorflow as tf from packaging import version def UpperCAmelCase_ (__a : Tuple ): """simple docstring""" _a : Optional[int] = tf.convert_to_tensor(__a ) _a : Any = 0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0 ) , x.dtype ) )) return x * cdf def UpperCAmelCase_ (__a : Union[str, Any] ): """simple docstring""" _a : Any = tf.convert_to_tensor(__a ) _a : Optional[Any] = tf.cast(math.pi , x.dtype ) _a : Any = tf.cast(0.044715 , x.dtype ) _a : str = 0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi ) * (x + coeff * tf.pow(__a , 3 )) )) return x * cdf def UpperCAmelCase_ (__a : List[str] ): """simple docstring""" _a : List[Any] = tf.convert_to_tensor(__a ) return x * tf.tanh(tf.math.softplus(__a ) ) def UpperCAmelCase_ (__a : Optional[int] ): """simple docstring""" _a : Any = tf.convert_to_tensor(__a ) _a : int = tf.cast(0.044715 , x.dtype ) _a : str = tf.cast(0.7978845608 , x.dtype ) return 0.5 * x * (1.0 + tf.tanh(x * coeffa * (1.0 + coeffa * x * x) )) def UpperCAmelCase_ (__a : str ): """simple docstring""" _a : Union[str, Any] = tf.convert_to_tensor(__a ) _a : List[str] = tf.cast(1.702 , x.dtype ) return x * tf.math.sigmoid(coeff * x ) def UpperCAmelCase_ (__a : List[str] ): """simple docstring""" return tf.clip_by_value(_gelu(__a ) , -1_0 , 1_0 ) def UpperCAmelCase_ (__a : Union[str, Any] , __a : Optional[Any]=-1 ): """simple docstring""" _a, _a : int = tf.split(__a , 2 , axis=__a ) return a * tf.math.sigmoid(__a ) if version.parse(tf.version.VERSION) >= version.parse("""2.4"""): def UpperCAmelCase_ (__a : List[str] ): """simple docstring""" return tf.keras.activations.gelu(__a , approximate=__a ) __lowerCAmelCase = tf.keras.activations.gelu __lowerCAmelCase = approximate_gelu_wrap else: __lowerCAmelCase = _gelu __lowerCAmelCase = _gelu_new __lowerCAmelCase = { """gelu""": gelu, """gelu_10""": gelu_aa, """gelu_fast""": gelu_fast, """gelu_new""": gelu_new, """glu""": glu, """mish""": mish, """quick_gelu""": quick_gelu, """relu""": tf.keras.activations.relu, """sigmoid""": tf.keras.activations.sigmoid, """silu""": tf.keras.activations.swish, """swish""": tf.keras.activations.swish, """tanh""": tf.keras.activations.tanh, } def UpperCAmelCase_ (__a : Any ): """simple docstring""" if activation_string in ACTaFN: return ACTaFN[activation_string] else: raise KeyError(f"""function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys() )}""" )
271
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import KarrasVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : UNetaDModel __UpperCAmelCase : KarrasVeScheduler def __init__( self : Union[str, Any] ,_a : UNetaDModel ,_a : KarrasVeScheduler ): '''simple docstring''' super().__init__() self.register_modules(unet=_a ,scheduler=_a ) @torch.no_grad() def __call__( self : List[Any] ,_a : int = 1 ,_a : int = 50 ,_a : Optional[Union[torch.Generator, List[torch.Generator]]] = None ,_a : Optional[str] = "pil" ,_a : bool = True ,**_a : List[Any] ,): '''simple docstring''' _a : Any = self.unet.config.sample_size _a : Optional[int] = (batch_size, 3, img_size, img_size) _a : Dict = self.unet # sample x_0 ~ N(0, sigma_0^2 * I) _a : Dict = randn_tensor(_a ,generator=_a ,device=self.device ) * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(_a ) for t in self.progress_bar(self.scheduler.timesteps ): # here sigma_t == t_i from the paper _a : Optional[int] = self.scheduler.schedule[t] _a : List[str] = self.scheduler.schedule[t - 1] if t > 0 else 0 # 1. Select temporarily increased noise level sigma_hat # 2. Add new noise to move from sample_i to sample_hat _a, _a : List[Any] = self.scheduler.add_noise_to_input(_a ,_a ,generator=_a ) # 3. Predict the noise residual given the noise magnitude `sigma_hat` # The model inputs and output are adjusted by following eq. (213) in [1]. _a : Optional[int] = (sigma_hat / 2) * model((sample_hat + 1) / 2 ,sigma_hat / 2 ).sample # 4. Evaluate dx/dt at sigma_hat # 5. Take Euler step from sigma to sigma_prev _a : Tuple = self.scheduler.step(_a ,_a ,_a ,_a ) if sigma_prev != 0: # 6. Apply 2nd order correction # The model inputs and output are adjusted by following eq. (213) in [1]. _a : Optional[int] = (sigma_prev / 2) * model((step_output.prev_sample + 1) / 2 ,sigma_prev / 2 ).sample _a : Optional[Any] = self.scheduler.step_correct( _a ,_a ,_a ,_a ,step_output.prev_sample ,step_output['derivative'] ,) _a : Dict = step_output.prev_sample _a : Tuple = (sample / 2 + 0.5).clamp(0 ,1 ) _a : Optional[Any] = sample.cpu().permute(0 ,2 ,3 ,1 ).numpy() if output_type == "pil": _a : List[str] = self.numpy_to_pil(_a ) if not return_dict: return (image,) return ImagePipelineOutput(images=_a )
271
1
'''simple docstring''' # Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING import numpy as np import pyarrow as pa from .. import config from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import torch class UpperCAmelCase__ ( TensorFormatter[Mapping, '''torch.Tensor''', Mapping] ): """simple docstring""" def __init__( self : Union[str, Any] ,_a : Any=None ,**_a : Optional[int] ): '''simple docstring''' super().__init__(features=_a ) _a : List[Any] = torch_tensor_kwargs import torch # noqa import torch at initialization def __lowercase ( self : Dict ,_a : Union[str, Any] ): '''simple docstring''' import torch if isinstance(_a ,_a ) and column: if all( isinstance(_a ,torch.Tensor ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return torch.stack(_a ) return column def __lowercase ( self : int ,_a : Dict ): '''simple docstring''' import torch if isinstance(_a ,(str, bytes, type(_a )) ): return value elif isinstance(_a ,(np.character, np.ndarray) ) and np.issubdtype(value.dtype ,np.character ): return value.tolist() _a : Tuple = {} if isinstance(_a ,(np.number, np.ndarray) ) and np.issubdtype(value.dtype ,np.integer ): _a : Optional[Any] = {'dtype': torch.intaa} elif isinstance(_a ,(np.number, np.ndarray) ) and np.issubdtype(value.dtype ,np.floating ): _a : List[Any] = {'dtype': torch.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(_a ,PIL.Image.Image ): _a : Union[str, Any] = np.asarray(_a ) return torch.tensor(_a ,**{**default_dtype, **self.torch_tensor_kwargs} ) def __lowercase ( self : Any ,_a : Dict ): '''simple docstring''' import torch # support for torch, tf, jax etc. if hasattr(_a ,'__array__' ) and not isinstance(_a ,torch.Tensor ): _a : Dict = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(_a ,np.ndarray ): if data_struct.dtype == object: # torch tensors cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(_a ) for substruct in data_struct] ) elif isinstance(_a ,(list, tuple) ): return self._consolidate([self.recursive_tensorize(_a ) for substruct in data_struct] ) return self._tensorize(_a ) def __lowercase ( self : List[Any] ,_a : dict ): '''simple docstring''' return map_nested(self._recursive_tensorize ,_a ,map_list=_a ) def __lowercase ( self : Any ,_a : pa.Table ): '''simple docstring''' _a : int = self.numpy_arrow_extractor().extract_row(_a ) _a : Optional[int] = self.python_features_decoder.decode_row(_a ) return self.recursive_tensorize(_a ) def __lowercase ( self : Union[str, Any] ,_a : pa.Table ): '''simple docstring''' _a : Tuple = self.numpy_arrow_extractor().extract_column(_a ) _a : Tuple = self.python_features_decoder.decode_column(_a ,pa_table.column_names[0] ) _a : Tuple = self.recursive_tensorize(_a ) _a : Optional[int] = self._consolidate(_a ) return column def __lowercase ( self : Tuple ,_a : pa.Table ): '''simple docstring''' _a : Any = self.numpy_arrow_extractor().extract_batch(_a ) _a : Optional[Any] = self.python_features_decoder.decode_batch(_a ) _a : str = self.recursive_tensorize(_a ) for column_name in batch: _a : Union[str, Any] = self._consolidate(batch[column_name] ) return batch
271
'''simple docstring''' import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version from .. import __version__ from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging __lowerCAmelCase = ( """https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py""" ) __lowerCAmelCase = logging.get_logger(__name__) # pylint: disable=invalid-name def UpperCAmelCase_ (): """simple docstring""" _a : Optional[int] = 'https://pypi.org/pypi/diffusers/json' _a : int = json.loads(request.urlopen(__a ).read() )['releases'].keys() return sorted(__a , key=lambda __a : version.Version(__a ) ) def UpperCAmelCase_ (): """simple docstring""" if HF_MODULES_CACHE in sys.path: return sys.path.append(__a ) os.makedirs(__a , exist_ok=__a ) _a : str = Path(__a ) / '__init__.py' if not init_path.exists(): init_path.touch() def UpperCAmelCase_ (__a : Union[str, os.PathLike] ): """simple docstring""" init_hf_modules() _a : Dict = Path(__a ) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent ) os.makedirs(__a , exist_ok=__a ) _a : Optional[int] = dynamic_module_path / '__init__.py' if not init_path.exists(): init_path.touch() def UpperCAmelCase_ (__a : str ): """simple docstring""" with open(__a , 'r' , encoding='utf-8' ) as f: _a : int = f.read() # Imports of the form `import .xxx` _a : Tuple = re.findall('^\s*import\s+\.(\S+)\s*$' , __a , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall('^\s*from\s+\.(\S+)\s+import' , __a , flags=re.MULTILINE ) # Unique-ify return list(set(__a ) ) def UpperCAmelCase_ (__a : Any ): """simple docstring""" _a : Optional[int] = False _a : Optional[int] = [module_file] _a : List[str] = [] # Let's recurse through all relative imports while not no_change: _a : str = [] for f in files_to_check: new_imports.extend(get_relative_imports(__a ) ) _a : Union[str, Any] = Path(__a ).parent _a : str = [str(module_path / m ) for m in new_imports] _a : Tuple = [f for f in new_import_files if f not in all_relative_imports] _a : Dict = [f"""{f}.py""" for f in new_import_files] _a : List[str] = len(__a ) == 0 all_relative_imports.extend(__a ) return all_relative_imports def UpperCAmelCase_ (__a : Tuple ): """simple docstring""" with open(__a , 'r' , encoding='utf-8' ) as f: _a : Dict = f.read() # Imports of the form `import xxx` _a : Optional[int] = re.findall('^\s*import\s+(\S+)\s*$' , __a , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall('^\s*from\s+(\S+)\s+import' , __a , flags=re.MULTILINE ) # Only keep the top-level module _a : List[str] = [imp.split('.' )[0] for imp in imports if not imp.startswith('.' )] # Unique-ify and test we got them all _a : Optional[int] = list(set(__a ) ) _a : List[str] = [] for imp in imports: try: importlib.import_module(__a ) except ImportError: missing_packages.append(__a ) if len(__a ) > 0: raise ImportError( 'This modeling file requires the following packages that were not found in your environment: ' f"""{', '.join(__a )}. Run `pip install {' '.join(__a )}`""" ) return get_relative_imports(__a ) def UpperCAmelCase_ (__a : Any , __a : str ): """simple docstring""" _a : Any = module_path.replace(os.path.sep , '.' ) _a : Union[str, Any] = importlib.import_module(__a ) if class_name is None: return find_pipeline_class(__a ) return getattr(__a , __a ) def UpperCAmelCase_ (__a : Optional[int] ): """simple docstring""" from ..pipelines import DiffusionPipeline _a : List[str] = dict(inspect.getmembers(__a , inspect.isclass ) ) _a : str = None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , __a ) and cls.__module__.split('.' )[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( f"""Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:""" f""" {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in""" f""" {loaded_module}.""" ) _a : Any = cls return pipeline_class def UpperCAmelCase_ (__a : Union[str, os.PathLike] , __a : str , __a : Optional[Union[str, os.PathLike]] = None , __a : bool = False , __a : bool = False , __a : Optional[Dict[str, str]] = None , __a : Optional[Union[bool, str]] = None , __a : Optional[str] = None , __a : bool = False , ): """simple docstring""" _a : str = str(__a ) _a : Optional[Any] = os.path.join(__a , __a ) if os.path.isfile(__a ): _a : Tuple = module_file_or_url _a : Optional[Any] = 'local' elif pretrained_model_name_or_path.count('/' ) == 0: _a : int = get_diffusers_versions() # cut ".dev0" _a : Any = 'v' + '.'.join(__version__.split('.' )[:3] ) # retrieve github version that matches if revision is None: _a : Any = latest_version if latest_version[1:] in available_versions else 'main' logger.info(f"""Defaulting to latest_version: {revision}.""" ) elif revision in available_versions: _a : Any = f"""v{revision}""" elif revision == "main": _a : Optional[int] = revision else: raise ValueError( f"""`custom_revision`: {revision} does not exist. Please make sure to choose one of""" f""" {', '.join(available_versions + ['main'] )}.""" ) # community pipeline on GitHub _a : Tuple = COMMUNITY_PIPELINES_URL.format(revision=__a , pipeline=__a ) try: _a : Any = cached_download( __a , cache_dir=__a , force_download=__a , proxies=__a , resume_download=__a , local_files_only=__a , use_auth_token=__a , ) _a : List[Any] = 'git' _a : Any = pretrained_model_name_or_path + '.py' except EnvironmentError: logger.error(f"""Could not locate the {module_file} inside {pretrained_model_name_or_path}.""" ) raise else: try: # Load from URL or cache if already cached _a : Optional[Any] = hf_hub_download( __a , __a , cache_dir=__a , force_download=__a , proxies=__a , resume_download=__a , local_files_only=__a , use_auth_token=__a , ) _a : List[Any] = os.path.join('local' , '--'.join(pretrained_model_name_or_path.split('/' ) ) ) except EnvironmentError: logger.error(f"""Could not locate the {module_file} inside {pretrained_model_name_or_path}.""" ) raise # Check we have all the requirements in our environment _a : Optional[int] = check_imports(__a ) # Now we move the module inside our cached dynamic modules. _a : Optional[Any] = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(__a ) _a : Any = Path(__a ) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copy(__a , submodule_path / module_file ) for module_needed in modules_needed: _a : Dict = f"""{module_needed}.py""" shutil.copy(os.path.join(__a , __a ) , submodule_path / module_needed ) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. if isinstance(__a , __a ): _a : Optional[Any] = use_auth_token elif use_auth_token is True: _a : List[Any] = HfFolder.get_token() else: _a : Dict = None _a : int = model_info(__a , revision=__a , token=__a ).sha # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. _a : Optional[int] = submodule_path / commit_hash _a : str = full_submodule + os.path.sep + commit_hash create_dynamic_module(__a ) if not (submodule_path / module_file).exists(): shutil.copy(__a , submodule_path / module_file ) # Make sure we also have every file with relative for module_needed in modules_needed: if not (submodule_path / module_needed).exists(): get_cached_module_file( __a , f"""{module_needed}.py""" , cache_dir=__a , force_download=__a , resume_download=__a , proxies=__a , use_auth_token=__a , revision=__a , local_files_only=__a , ) return os.path.join(__a , __a ) def UpperCAmelCase_ (__a : Union[str, os.PathLike] , __a : str , __a : Optional[str] = None , __a : Optional[Union[str, os.PathLike]] = None , __a : bool = False , __a : bool = False , __a : Optional[Dict[str, str]] = None , __a : Optional[Union[bool, str]] = None , __a : Optional[str] = None , __a : bool = False , **__a : str , ): """simple docstring""" _a : Dict = get_cached_module_file( __a , __a , cache_dir=__a , force_download=__a , resume_download=__a , proxies=__a , use_auth_token=__a , revision=__a , local_files_only=__a , ) return get_class_in_module(__a , final_module.replace('.py' , '' ) )
271
1
'''simple docstring''' from __future__ import annotations from cmath import sqrt def UpperCAmelCase_ (__a : int , __a : int , __a : int ): """simple docstring""" if a == 0: raise ValueError('Coefficient \'a\' must not be zero.' ) _a : Optional[Any] = b * b - 4 * a * c _a : Optional[int] = (-b + sqrt(__a )) / (2 * a) _a : Dict = (-b - sqrt(__a )) / (2 * a) return ( root_a.real if not root_a.imag else root_a, root_a.real if not root_a.imag else root_a, ) def UpperCAmelCase_ (): """simple docstring""" _a, _a : Tuple = quadratic_roots(a=5 , b=6 , c=1 ) print(f"""The solutions are: {solutiona} and {solutiona}""" ) if __name__ == "__main__": main()
271
'''simple docstring''' def UpperCAmelCase_ (__a : list , __a : list , __a : int ): """simple docstring""" _a : Optional[Any] = len(__a ) _a : int = [[0] * n for i in range(__a )] for i in range(__a ): _a : Tuple = y_points[i] for i in range(2 , __a ): for j in range(__a , __a ): _a : Tuple = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
271
1
'''simple docstring''' __lowerCAmelCase = [sum(int(c, 1_0) ** 2 for c in i.__str__()) for i in range(1_0_0_0_0_0)] def UpperCAmelCase_ (__a : int ): """simple docstring""" _a : Union[str, Any] = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 1_0_0_0_0_0] number //= 1_0_0_0_0_0 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution __lowerCAmelCase = [None] * 1_0_0_0_0_0_0_0 __lowerCAmelCase = True __lowerCAmelCase = False def UpperCAmelCase_ (__a : int ): """simple docstring""" if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore _a : List[Any] = chain(next_number(__a ) ) _a : Union[str, Any] = number_chain while number < 1_0_0_0_0_0_0_0: _a : Optional[Any] = number_chain number *= 1_0 return number_chain def UpperCAmelCase_ (__a : int = 1_0_0_0_0_0_0_0 ): """simple docstring""" for i in range(1 , __a ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__a ) if __name__ == "__main__": import doctest doctest.testmod() print(f'''{solution() = }''')
271
'''simple docstring''' import inspect import os import unittest from pathlib import Path import torch import accelerate from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils.testing import run_command class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Optional[Any] = inspect.getfile(accelerate.test_utils ) __UpperCAmelCase : List[str] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_cli.py'''] ) __UpperCAmelCase : Dict = ['''accelerate''', '''launch'''] __UpperCAmelCase : Dict = Path.home() / '''.cache/huggingface/accelerate''' __UpperCAmelCase : Dict = '''default_config.yaml''' __UpperCAmelCase : Optional[Any] = config_folder / config_file __UpperCAmelCase : Dict = config_folder / '''_default_config.yaml''' __UpperCAmelCase : Any = Path('''tests/test_configs''' ) @classmethod def __lowercase ( cls : int ): '''simple docstring''' if cls.config_path.is_file(): cls.config_path.rename(cls.changed_path ) @classmethod def __lowercase ( cls : List[Any] ): '''simple docstring''' if cls.changed_path.is_file(): cls.changed_path.rename(cls.config_path ) def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : Dict = self.base_cmd if torch.cuda.is_available() and (torch.cuda.device_count() > 1): cmd += ["--multi_gpu"] execute_subprocess_async(cmd + [self.test_file_path] ,env=os.environ.copy() ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' for config in sorted(self.test_config_path.glob('**/*.yaml' ) ): with self.subTest(config_file=_a ): execute_subprocess_async( self.base_cmd + ['--config_file', str(_a ), self.test_file_path] ,env=os.environ.copy() ) def __lowercase ( self : Optional[int] ): '''simple docstring''' execute_subprocess_async(['accelerate', 'test'] ,env=os.environ.copy() ) class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Optional[Any] = '''test-tpu''' __UpperCAmelCase : Any = '''us-central1-a''' __UpperCAmelCase : List[Any] = '''ls''' __UpperCAmelCase : Any = ['''accelerate''', '''tpu-config'''] __UpperCAmelCase : Dict = '''cd /usr/share''' __UpperCAmelCase : Any = '''tests/test_samples/test_command_file.sh''' __UpperCAmelCase : List[Any] = '''Running gcloud compute tpus tpu-vm ssh''' def __lowercase ( self : Dict ): '''simple docstring''' _a : Optional[Any] = run_command( self.cmd + ['--command', self.command, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug'] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" ,_a ,) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Any = run_command( self.cmd + [ '--config_file', 'tests/test_configs/0_12_0.yaml', '--command', self.command, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug', ] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" ,_a ,) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Optional[int] = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--debug'] ,return_stdout=_a ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_a ,) def __lowercase ( self : int ): '''simple docstring''' _a : Optional[Any] = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--command', self.command, '--debug'] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" ,_a ,) def __lowercase ( self : str ): '''simple docstring''' _a : List[str] = run_command( self.cmd + [ '--config_file', 'tests/test_configs/latest.yaml', '--command', self.command, '--command', 'echo "Hello World"', '--debug', ] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo \"Hello World\" --worker all""" ,_a ,) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : Any = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--command_file', self.command_file, '--debug'] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_a ,) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : Union[str, Any] = run_command( self.cmd + [ '--config_file', 'tests/test_configs/0_12_0.yaml', '--command_file', self.command_file, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug', ] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_a ,) def __lowercase ( self : Any ): '''simple docstring''' _a : Optional[int] = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--install_accelerate', '--debug'] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_a ,) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Optional[int] = run_command( self.cmd + [ '--config_file', 'tests/test_configs/latest.yaml', '--install_accelerate', '--accelerate_version', '12.0.0', '--debug', ] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_a ,)
271
1
'''simple docstring''' import importlib.metadata from typing import Union from packaging.version import Version, parse from .constants import STR_OPERATION_TO_FUNC __lowerCAmelCase = parse(importlib.metadata.version("""torch""")) def UpperCAmelCase_ (__a : Union[str, Version] , __a : str , __a : str ): """simple docstring""" if operation not in STR_OPERATION_TO_FUNC.keys(): raise ValueError(f"""`operation` must be one of {list(STR_OPERATION_TO_FUNC.keys() )}, received {operation}""" ) _a : Optional[Any] = STR_OPERATION_TO_FUNC[operation] if isinstance(__a , __a ): _a : Dict = parse(importlib.metadata.version(__a ) ) return operation(__a , parse(__a ) ) def UpperCAmelCase_ (__a : str , __a : str ): """simple docstring""" return compare_versions(__a , __a , __a )
271
'''simple docstring''' from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar __lowerCAmelCase = TypeVar("""T""") class UpperCAmelCase__ ( Generic[T] ): """simple docstring""" def __init__( self : Tuple ,_a : T ): '''simple docstring''' _a : List[str] = data _a : Node[T] | None = None def __str__( self : Dict ): '''simple docstring''' return F"""{self.data}""" class UpperCAmelCase__ ( Generic[T] ): """simple docstring""" def __init__( self : Optional[int] ): '''simple docstring''' _a : Node[T] | None = None def __iter__( self : str ): '''simple docstring''' _a : Tuple = self.top while node: yield node.data _a : int = node.next def __str__( self : str ): '''simple docstring''' return "->".join([str(_a ) for item in self] ) def __len__( self : Optional[Any] ): '''simple docstring''' return len(tuple(iter(self ) ) ) def __lowercase ( self : str ): '''simple docstring''' return self.top is None def __lowercase ( self : List[Any] ,_a : T ): '''simple docstring''' _a : int = Node(_a ) if not self.is_empty(): _a : Optional[Any] = self.top _a : List[str] = node def __lowercase ( self : Tuple ): '''simple docstring''' if self.is_empty(): raise IndexError('pop from empty stack' ) assert isinstance(self.top ,_a ) _a : List[Any] = self.top _a : int = self.top.next return pop_node.data def __lowercase ( self : List[str] ): '''simple docstring''' if self.is_empty(): raise IndexError('peek from empty stack' ) assert self.top is not None return self.top.data def __lowercase ( self : List[str] ): '''simple docstring''' _a : Optional[int] = None if __name__ == "__main__": from doctest import testmod testmod()
271
1
'''simple docstring''' import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel __lowerCAmelCase = logging.getLogger(__name__) def UpperCAmelCase_ (__a : List[str] , __a : int ): """simple docstring""" if os.path.exists(__a ): if os.path.exists(os.path.join(__a , 'config.json' ) ) and os.path.isfile( os.path.join(__a , 'config.json' ) ): os.remove(os.path.join(__a , 'config.json' ) ) if os.path.exists(os.path.join(__a , 'pytorch_model.bin' ) ) and os.path.isfile( os.path.join(__a , 'pytorch_model.bin' ) ): os.remove(os.path.join(__a , 'pytorch_model.bin' ) ) else: os.makedirs(__a ) model.save_pretrained(__a ) def UpperCAmelCase_ (__a : Optional[Any] , __a : Union[str, Any]=False ): """simple docstring""" _a : Optional[int] = 2 if unlogit: _a : List[str] = torch.pow(__a , __a ) _a : Union[str, Any] = p * torch.log(__a ) _a : int = 0 return -plogp.sum(dim=-1 ) def UpperCAmelCase_ (__a : Union[str, Any] ): """simple docstring""" logger.info('lv, h >\t' + '\t'.join(f"""{x + 1}""" for x in range(len(__a ) ) ) ) for row in range(len(__a ) ): if tensor.dtype != torch.long: logger.info(f"""layer {row + 1}:\t""" + '\t'.join(f"""{x:.5f}""" for x in tensor[row].cpu().data ) ) else: logger.info(f"""layer {row + 1}:\t""" + '\t'.join(f"""{x:d}""" for x in tensor[row].cpu().data ) ) def UpperCAmelCase_ (__a : Optional[int] , __a : List[Any] , __a : Any , __a : str=True , __a : Any=True , __a : List[Any]=None , __a : Optional[int]=False ): """simple docstring""" _a, _a : Optional[Any] = model.config.num_hidden_layers, model.config.num_attention_heads _a : Optional[int] = torch.zeros(__a , __a ).to(args.device ) _a : Any = torch.zeros(__a , __a ).to(args.device ) if head_mask is None: _a : Union[str, Any] = torch.ones(__a , __a ).to(args.device ) head_mask.requires_grad_(requires_grad=__a ) # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch if actually_pruned: _a : List[str] = None _a : List[Any] = 0.0 _a : List[str] = 0.0 for step, inputs in enumerate(tqdm(__a , desc='Iteration' , disable=args.local_rank not in [-1, 0] ) ): _a : Optional[int] = tuple(t.to(args.device ) for t in inputs ) ((_a), ) : List[str] = inputs # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below) _a : Any = model(__a , labels=__a , head_mask=__a ) # (loss), lm_logits, presents, (all hidden_states), (attentions) _a, _a, _a : Union[str, Any] = ( outputs[0], outputs[1], outputs[-1], ) # Loss and logits are the first, attention the last loss.backward() # Backpropagate to populate the gradients in the head mask total_loss += loss.detach().cpu().numpy() if compute_entropy: for layer, attn in enumerate(__a ): _a : List[Any] = entropy(attn.detach() , __a ) attn_entropy[layer] += masked_entropy.sum(-1 ).sum(0 ).sum(0 ).detach() if compute_importance: head_importance += head_mask.grad.abs().detach() tot_tokens += torch.ones_like(__a ).float().detach().sum().data # Normalize attn_entropy /= tot_tokens head_importance /= tot_tokens # Layerwise importance normalization if not args.dont_normalize_importance_by_layer: _a : str = 2 _a : Any = torch.pow(torch.pow(__a , __a ).sum(-1 ) , 1 / exponent ) head_importance /= norm_by_layer.unsqueeze(-1 ) + 1e-20 if not args.dont_normalize_global_importance: _a : str = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min()) # Print matrices if compute_entropy: logger.info('Attention entropies' ) print_ad_tensor(__a ) if compute_importance: logger.info('Head importance scores' ) print_ad_tensor(__a ) logger.info('Head ranked by importance scores' ) _a : Optional[Any] = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device ) _a : Any = torch.arange( head_importance.numel() , device=args.device ) _a : Union[str, Any] = head_ranks.view_as(__a ) print_ad_tensor(__a ) return attn_entropy, head_importance, total_loss def UpperCAmelCase_ (__a : int , __a : List[str] , __a : List[Any] ): """simple docstring""" _a, _a, _a : str = compute_heads_importance(__a , __a , __a , compute_entropy=__a ) _a : List[Any] = 1 / loss # instead of downsteam score use the LM loss logger.info('Pruning: original score: %f, threshold: %f' , __a , original_score * args.masking_threshold ) _a : Any = torch.ones_like(__a ) _a : Union[str, Any] = max(1 , int(new_head_mask.numel() * args.masking_amount ) ) _a : List[str] = original_score while current_score >= original_score * args.masking_threshold: _a : str = new_head_mask.clone().detach() # save current head mask # heads from least important to most - keep only not-masked heads _a : Tuple = float('Inf' ) _a : Any = head_importance.view(-1 ).sort()[1] if len(__a ) <= num_to_mask: print('BREAK BY num_to_mask' ) break # mask heads _a : int = current_heads_to_mask[:num_to_mask] logger.info('Heads to mask: %s' , str(current_heads_to_mask.tolist() ) ) _a : Tuple = new_head_mask.view(-1 ) _a : str = 0.0 _a : List[Any] = new_head_mask.view_as(__a ) _a : Any = new_head_mask.clone().detach() print_ad_tensor(__a ) # Compute metric and head importance again _a, _a, _a : Tuple = compute_heads_importance( __a , __a , __a , compute_entropy=__a , head_mask=__a ) _a : List[str] = 1 / loss logger.info( 'Masking: current score: %f, remaining heads %d (%.1f percents)' , __a , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 1_0_0 , ) logger.info('Final head mask' ) print_ad_tensor(__a ) np.save(os.path.join(args.output_dir , 'head_mask.npy' ) , head_mask.detach().cpu().numpy() ) return head_mask def UpperCAmelCase_ (__a : List[Any] , __a : List[str] , __a : Dict , __a : List[Any] ): """simple docstring""" _a : List[Any] = datetime.now() _a, _a, _a : Any = compute_heads_importance( __a , __a , __a , compute_entropy=__a , compute_importance=__a , head_mask=__a ) _a : List[Any] = 1 / loss _a : Union[str, Any] = datetime.now() - before_time _a : List[Any] = sum(p.numel() for p in model.parameters() ) _a : Tuple = { layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(__a ) ) } for k, v in heads_to_prune.items(): if isinstance(__a , __a ): _a : List[str] = [ v, ] assert sum(len(__a ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item() model.prune_heads(__a ) _a : Optional[Any] = sum(p.numel() for p in model.parameters() ) _a : Union[str, Any] = datetime.now() _a, _a, _a : Any = compute_heads_importance( __a , __a , __a , compute_entropy=__a , compute_importance=__a , head_mask=__a , actually_pruned=__a , ) _a : int = 1 / loss _a : Any = datetime.now() - before_time logger.info( 'Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)' , __a , __a , pruned_num_params / original_num_params * 1_0_0 , ) logger.info('Pruning: score with masking: %f score with pruning: %f' , __a , __a ) logger.info('Pruning: speed ratio (original timing / new timing): %f percents' , original_time / new_time * 1_0_0 ) save_model(__a , args.output_dir ) def UpperCAmelCase_ (): """simple docstring""" _a : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '--data_dir' , default=__a , type=__a , required=__a , help='The input data dir. Should contain the .tsv files (or other data files) for the task.' , ) parser.add_argument( '--model_name_or_path' , default=__a , type=__a , required=__a , help='Path to pretrained model or model identifier from huggingface.co/models' , ) parser.add_argument( '--output_dir' , default=__a , type=__a , required=__a , help='The output directory where the model predictions and checkpoints will be written.' , ) # Other parameters parser.add_argument( '--config_name' , default='' , type=__a , help='Pretrained config name or path if not the same as model_name_or_path' , ) parser.add_argument( '--tokenizer_name' , default='' , type=__a , help='Pretrained tokenizer name or path if not the same as model_name_or_path' , ) parser.add_argument( '--cache_dir' , default=__a , type=__a , help='Where do you want to store the pre-trained models downloaded from s3' , ) parser.add_argument( '--data_subset' , type=__a , default=-1 , help='If > 0: limit the data to a subset of data_subset instances.' ) parser.add_argument( '--overwrite_output_dir' , action='store_true' , help='Whether to overwrite data in output directory' ) parser.add_argument( '--overwrite_cache' , action='store_true' , help='Overwrite the cached training and evaluation sets' ) parser.add_argument( '--dont_normalize_importance_by_layer' , action='store_true' , help='Don\'t normalize importance score by layers' ) parser.add_argument( '--dont_normalize_global_importance' , action='store_true' , help='Don\'t normalize all importance scores between 0 and 1' , ) parser.add_argument( '--try_masking' , action='store_true' , help='Whether to try to mask head until a threshold of accuracy.' ) parser.add_argument( '--masking_threshold' , default=0.9 , type=__a , help='masking threshold in term of metrics (stop masking when metric < threshold * original metric value).' , ) parser.add_argument( '--masking_amount' , default=0.1 , type=__a , help='Amount to heads to masking at each masking step.' ) parser.add_argument('--metric_name' , default='acc' , type=__a , help='Metric to use for head masking.' ) parser.add_argument( '--max_seq_length' , default=1_2_8 , type=__a , help=( 'The maximum total input sequence length after WordPiece tokenization. \n' 'Sequences longer than this will be truncated, sequences shorter padded.' ) , ) parser.add_argument('--batch_size' , default=1 , type=__a , help='Batch size.' ) parser.add_argument('--seed' , type=__a , default=4_2 ) parser.add_argument('--local_rank' , type=__a , default=-1 , help='local_rank for distributed training on gpus' ) parser.add_argument('--no_cuda' , action='store_true' , help='Whether not to use CUDA when available' ) parser.add_argument('--server_ip' , type=__a , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=__a , default='' , help='Can be used for distant debugging.' ) _a : str = parser.parse_args() if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=__a ) ptvsd.wait_for_attach() # Setup devices and distributed training if args.local_rank == -1 or args.no_cuda: _a : Optional[Any] = torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu' ) _a : List[str] = 0 if args.no_cuda else torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank ) _a : int = torch.device('cuda' , args.local_rank ) _a : Dict = 1 torch.distributed.init_process_group(backend='nccl' ) # Initializes the distributed backend # Setup logging logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN ) logger.info('device: {} n_gpu: {}, distributed: {}'.format(args.device , args.n_gpu , bool(args.local_rank != -1 ) ) ) _a : List[Any] = GPTaLMHeadModel.from_pretrained(args.model_name_or_path ) # Distributed and parallel training model.to(args.device ) if args.local_rank != -1: _a : Any = nn.parallel.DistributedDataParallel( __a , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=__a ) elif args.n_gpu > 1: _a : Union[str, Any] = nn.DataParallel(__a ) # Print/save training arguments os.makedirs(args.output_dir , exist_ok=__a ) torch.save(__a , os.path.join(args.output_dir , 'run_args.bin' ) ) logger.info('Training/evaluation parameters %s' , __a ) # Prepare dataset _a : Optional[Any] = np.concatenate( [ np.loadtxt(args.data_dir , dtype=np.intaa ), ] ) _a : Optional[int] = (torch.from_numpy(__a ),) _a : Optional[int] = TensorDataset(*__a ) _a : List[str] = RandomSampler(__a ) _a : int = DataLoader(__a , sampler=__a , batch_size=args.batch_size ) # Compute head entropy and importance score compute_heads_importance(__a , __a , __a ) # Try head masking (set heads to zero until the score goes under a threshole) # and head pruning (remove masked heads and see the effect on the network) if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0: _a : Optional[int] = mask_heads(__a , __a , __a ) prune_heads(__a , __a , __a , __a ) if __name__ == "__main__": main()
271
'''simple docstring''' import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" @property def __lowercase ( self : List[str] ): '''simple docstring''' torch.manual_seed(0 ) _a : int = UNetaDModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=3 ,out_channels=3 ,down_block_types=('DownBlock2D', 'AttnDownBlock2D') ,up_block_types=('AttnUpBlock2D', 'UpBlock2D') ,) return model def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a : str = self.dummy_uncond_unet _a : int = PNDMScheduler() _a : str = PNDMPipeline(unet=_a ,scheduler=_a ) pndm.to(_a ) pndm.set_progress_bar_config(disable=_a ) _a : Optional[int] = torch.manual_seed(0 ) _a : Optional[Any] = pndm(generator=_a ,num_inference_steps=20 ,output_type='numpy' ).images _a : List[str] = torch.manual_seed(0 ) _a : Any = pndm(generator=_a ,num_inference_steps=20 ,output_type='numpy' ,return_dict=_a )[0] _a : List[Any] = image[0, -3:, -3:, -1] _a : Any = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _a : List[Any] = np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self : Tuple ): '''simple docstring''' _a : List[str] = 'google/ddpm-cifar10-32' _a : str = UNetaDModel.from_pretrained(_a ) _a : Union[str, Any] = PNDMScheduler() _a : Tuple = PNDMPipeline(unet=_a ,scheduler=_a ) pndm.to(_a ) pndm.set_progress_bar_config(disable=_a ) _a : str = torch.manual_seed(0 ) _a : Optional[Any] = pndm(generator=_a ,output_type='numpy' ).images _a : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _a : Tuple = np.array([0.1564, 0.1_4645, 0.1406, 0.1_4715, 0.1_2425, 0.1_4045, 0.1_3115, 0.1_2175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
271
1
'''simple docstring''' from dataclasses import dataclass from typing import Dict, Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .attention_processor import AttentionProcessor, AttnProcessor from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, DiagonalGaussianDistribution, Encoder @dataclass class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : "DiagonalGaussianDistribution" class UpperCAmelCase__ ( lowercase__ , lowercase__ ): """simple docstring""" __UpperCAmelCase : Any = True @register_to_config def __init__( self : Tuple ,_a : int = 3 ,_a : int = 3 ,_a : Tuple[str] = ("DownEncoderBlock2D",) ,_a : Tuple[str] = ("UpDecoderBlock2D",) ,_a : Tuple[int] = (64,) ,_a : int = 1 ,_a : str = "silu" ,_a : int = 4 ,_a : int = 32 ,_a : int = 32 ,_a : float = 0.1_8215 ,): '''simple docstring''' super().__init__() # pass init params to Encoder _a : int = Encoder( in_channels=_a ,out_channels=_a ,down_block_types=_a ,block_out_channels=_a ,layers_per_block=_a ,act_fn=_a ,norm_num_groups=_a ,double_z=_a ,) # pass init params to Decoder _a : Any = Decoder( in_channels=_a ,out_channels=_a ,up_block_types=_a ,block_out_channels=_a ,layers_per_block=_a ,norm_num_groups=_a ,act_fn=_a ,) _a : Optional[int] = nn.Convad(2 * latent_channels ,2 * latent_channels ,1 ) _a : Union[str, Any] = nn.Convad(_a ,_a ,1 ) _a : List[str] = False _a : Union[str, Any] = False # only relevant if vae tiling is enabled _a : Optional[Any] = self.config.sample_size _a : int = ( self.config.sample_size[0] if isinstance(self.config.sample_size ,(list, tuple) ) else self.config.sample_size ) _a : List[Any] = int(sample_size / (2 ** (len(self.config.block_out_channels ) - 1)) ) _a : Any = 0.25 def __lowercase ( self : Optional[int] ,_a : Dict ,_a : Dict=False ): '''simple docstring''' if isinstance(_a ,(Encoder, Decoder) ): _a : Tuple = value def __lowercase ( self : Tuple ,_a : bool = True ): '''simple docstring''' _a : str = use_tiling def __lowercase ( self : Dict ): '''simple docstring''' self.enable_tiling(_a ) def __lowercase ( self : List[str] ): '''simple docstring''' _a : List[str] = True def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a : Union[str, Any] = False @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a : Union[str, Any] = {} def fn_recursive_add_processors(_a : str ,_a : torch.nn.Module ,_a : Dict[str, AttentionProcessor] ): if hasattr(_a ,'set_processor' ): _a : Optional[Any] = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(F"""{name}.{sub_name}""" ,_a ,_a ) return processors for name, module in self.named_children(): fn_recursive_add_processors(_a ,_a ,_a ) return processors def __lowercase ( self : Optional[int] ,_a : Union[AttentionProcessor, Dict[str, AttentionProcessor]] ): '''simple docstring''' _a : str = len(self.attn_processors.keys() ) if isinstance(_a ,_a ) and len(_a ) != count: raise ValueError( F"""A dict of processors was passed, but the number of processors {len(_a )} does not match the""" F""" number of attention layers: {count}. Please make sure to pass {count} processor classes.""" ) def fn_recursive_attn_processor(_a : str ,_a : torch.nn.Module ,_a : Union[str, Any] ): if hasattr(_a ,'set_processor' ): if not isinstance(_a ,_a ): module.set_processor(_a ) else: module.set_processor(processor.pop(F"""{name}.processor""" ) ) for sub_name, child in module.named_children(): fn_recursive_attn_processor(F"""{name}.{sub_name}""" ,_a ,_a ) for name, module in self.named_children(): fn_recursive_attn_processor(_a ,_a ,_a ) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' self.set_attn_processor(AttnProcessor() ) @apply_forward_hook def __lowercase ( self : Dict ,_a : torch.FloatTensor ,_a : bool = True ): '''simple docstring''' if self.use_tiling and (x.shape[-1] > self.tile_sample_min_size or x.shape[-2] > self.tile_sample_min_size): return self.tiled_encode(_a ,return_dict=_a ) if self.use_slicing and x.shape[0] > 1: _a : Tuple = [self.encoder(_a ) for x_slice in x.split(1 )] _a : List[Any] = torch.cat(_a ) else: _a : List[Any] = self.encoder(_a ) _a : Any = self.quant_conv(_a ) _a : str = DiagonalGaussianDistribution(_a ) if not return_dict: return (posterior,) return AutoencoderKLOutput(latent_dist=_a ) def __lowercase ( self : List[str] ,_a : torch.FloatTensor ,_a : bool = True ): '''simple docstring''' if self.use_tiling and (z.shape[-1] > self.tile_latent_min_size or z.shape[-2] > self.tile_latent_min_size): return self.tiled_decode(_a ,return_dict=_a ) _a : Any = self.post_quant_conv(_a ) _a : int = self.decoder(_a ) if not return_dict: return (dec,) return DecoderOutput(sample=_a ) @apply_forward_hook def __lowercase ( self : Any ,_a : torch.FloatTensor ,_a : bool = True ): '''simple docstring''' if self.use_slicing and z.shape[0] > 1: _a : List[str] = [self._decode(_a ).sample for z_slice in z.split(1 )] _a : Union[str, Any] = torch.cat(_a ) else: _a : Union[str, Any] = self._decode(_a ).sample if not return_dict: return (decoded,) return DecoderOutput(sample=_a ) def __lowercase ( self : Any ,_a : Any ,_a : Optional[int] ,_a : Any ): '''simple docstring''' _a : int = min(a.shape[2] ,b.shape[2] ,_a ) for y in range(_a ): _a : List[Any] = a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent) return b def __lowercase ( self : Optional[Any] ,_a : List[Any] ,_a : Union[str, Any] ,_a : Tuple ): '''simple docstring''' _a : Any = min(a.shape[3] ,b.shape[3] ,_a ) for x in range(_a ): _a : Any = a[:, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, x] * (x / blend_extent) return b def __lowercase ( self : str ,_a : torch.FloatTensor ,_a : bool = True ): '''simple docstring''' _a : int = int(self.tile_sample_min_size * (1 - self.tile_overlap_factor) ) _a : Any = int(self.tile_latent_min_size * self.tile_overlap_factor ) _a : List[Any] = self.tile_latent_min_size - blend_extent # Split the image into 512x512 tiles and encode them separately. _a : List[str] = [] for i in range(0 ,x.shape[2] ,_a ): _a : Optional[int] = [] for j in range(0 ,x.shape[3] ,_a ): _a : Union[str, Any] = x[:, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size] _a : Optional[int] = self.encoder(_a ) _a : Optional[int] = self.quant_conv(_a ) row.append(_a ) rows.append(_a ) _a : Dict = [] for i, row in enumerate(_a ): _a : str = [] for j, tile in enumerate(_a ): # blend the above tile and the left tile # to the current tile and add the current tile to the result row if i > 0: _a : Optional[Any] = self.blend_v(rows[i - 1][j] ,_a ,_a ) if j > 0: _a : Union[str, Any] = self.blend_h(row[j - 1] ,_a ,_a ) result_row.append(tile[:, :, :row_limit, :row_limit] ) result_rows.append(torch.cat(_a ,dim=3 ) ) _a : List[str] = torch.cat(_a ,dim=2 ) _a : Optional[int] = DiagonalGaussianDistribution(_a ) if not return_dict: return (posterior,) return AutoencoderKLOutput(latent_dist=_a ) def __lowercase ( self : Optional[int] ,_a : torch.FloatTensor ,_a : bool = True ): '''simple docstring''' _a : Optional[Any] = int(self.tile_latent_min_size * (1 - self.tile_overlap_factor) ) _a : Any = int(self.tile_sample_min_size * self.tile_overlap_factor ) _a : str = self.tile_sample_min_size - blend_extent # Split z into overlapping 64x64 tiles and decode them separately. # The tiles have an overlap to avoid seams between tiles. _a : Dict = [] for i in range(0 ,z.shape[2] ,_a ): _a : str = [] for j in range(0 ,z.shape[3] ,_a ): _a : Any = z[:, :, i : i + self.tile_latent_min_size, j : j + self.tile_latent_min_size] _a : List[str] = self.post_quant_conv(_a ) _a : Any = self.decoder(_a ) row.append(_a ) rows.append(_a ) _a : Union[str, Any] = [] for i, row in enumerate(_a ): _a : str = [] for j, tile in enumerate(_a ): # blend the above tile and the left tile # to the current tile and add the current tile to the result row if i > 0: _a : Union[str, Any] = self.blend_v(rows[i - 1][j] ,_a ,_a ) if j > 0: _a : Tuple = self.blend_h(row[j - 1] ,_a ,_a ) result_row.append(tile[:, :, :row_limit, :row_limit] ) result_rows.append(torch.cat(_a ,dim=3 ) ) _a : int = torch.cat(_a ,dim=2 ) if not return_dict: return (dec,) return DecoderOutput(sample=_a ) def __lowercase ( self : Optional[int] ,_a : torch.FloatTensor ,_a : bool = False ,_a : bool = True ,_a : Optional[torch.Generator] = None ,): '''simple docstring''' _a : List[str] = sample _a : Optional[Any] = self.encode(_a ).latent_dist if sample_posterior: _a : Optional[int] = posterior.sample(generator=_a ) else: _a : str = posterior.mode() _a : Any = self.decode(_a ).sample if not return_dict: return (dec,) return DecoderOutput(sample=_a )
271
'''simple docstring''' import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow __lowerCAmelCase = logging.getLogger() @unittest.skip('''Temporarily disable the doc tests.''' ) @require_torch @require_tf @slow class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self : str ,_a : Path ,_a : Union[str, None] = None ,_a : Union[List[str], None] = None ,_a : Union[str, List[str], None] = None ,_a : bool = True ,): '''simple docstring''' _a : Optional[int] = [file for file in os.listdir(_a ) if os.path.isfile(os.path.join(_a ,_a ) )] if identifier is not None: _a : List[str] = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(_a ,_a ): for n_ in n_identifier: _a : Tuple = [file for file in files if n_ not in file] else: _a : Optional[Any] = [file for file in files if n_identifier not in file] _a : List[str] = ignore_files or [] ignore_files.append('__init__.py' ) _a : Tuple = [file for file in files if file not in ignore_files] for file in files: # Open all files print('Testing' ,_a ) if only_modules: _a : Any = file.split('.' )[0] try: _a : List[str] = getattr(_a ,_a ) _a : int = doctest.DocTestSuite(_a ) _a : Any = unittest.TextTestRunner().run(_a ) self.assertIs(len(result.failures ) ,0 ) except AttributeError: logger.info(F"""{module_identifier} is not a module.""" ) else: _a : Union[str, Any] = doctest.testfile(str('..' / directory / file ) ,optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed ,0 ) def __lowercase ( self : Any ): '''simple docstring''' _a : int = Path('src/transformers' ) _a : List[Any] = 'modeling' _a : Optional[Any] = [ 'modeling_ctrl.py', 'modeling_tf_ctrl.py', ] self.analyze_directory(_a ,identifier=_a ,ignore_files=_a ) def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : Optional[Any] = Path('src/transformers' ) _a : Optional[Any] = 'tokenization' self.analyze_directory(_a ,identifier=_a ) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Dict = Path('src/transformers' ) _a : str = 'configuration' self.analyze_directory(_a ,identifier=_a ) def __lowercase ( self : Any ): '''simple docstring''' _a : Tuple = Path('src/transformers' ) _a : List[Any] = ['configuration', 'modeling', 'tokenization'] self.analyze_directory(_a ,n_identifier=_a ) def __lowercase ( self : Tuple ): '''simple docstring''' _a : List[Any] = Path('docs/source' ) _a : List[str] = ['favicon.ico'] self.analyze_directory(_a ,ignore_files=_a ,only_modules=_a )
271
1
'''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: __lowerCAmelCase = None __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = {"""vocab_file""": """sentencepiece.bpe.model""", """tokenizer_file""": """tokenizer.json"""} __lowerCAmelCase = { """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""", }, } __lowerCAmelCase = { """facebook/mbart-large-en-ro""": 1_0_2_4, """facebook/mbart-large-cc25""": 1_0_2_4, } # fmt: off __lowerCAmelCase = ["""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 UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : Tuple = VOCAB_FILES_NAMES __UpperCAmelCase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : List[Any] = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Optional[Any] = ['''input_ids''', '''attention_mask'''] __UpperCAmelCase : Union[str, Any] = MBartTokenizer __UpperCAmelCase : List[int] = [] __UpperCAmelCase : List[int] = [] def __init__( self : Dict ,_a : List[Any]=None ,_a : Tuple=None ,_a : Optional[int]="<s>" ,_a : Dict="</s>" ,_a : List[str]="</s>" ,_a : Union[str, Any]="<s>" ,_a : List[str]="<unk>" ,_a : str="<pad>" ,_a : Optional[Any]="<mask>" ,_a : List[Any]=None ,_a : Union[str, Any]=None ,_a : Union[str, Any]=None ,**_a : Any ,): '''simple docstring''' _a : Union[str, Any] = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else mask_token super().__init__( vocab_file=_a ,tokenizer_file=_a ,bos_token=_a ,eos_token=_a ,sep_token=_a ,cls_token=_a ,unk_token=_a ,pad_token=_a ,mask_token=_a ,src_lang=_a ,tgt_lang=_a ,additional_special_tokens=_a ,**_a ,) _a : Tuple = vocab_file _a : Union[str, Any] = False if not self.vocab_file else True _a : Dict = 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} ) _a : Dict = { lang_code: self.convert_tokens_to_ids(_a ) for lang_code in FAIRSEQ_LANGUAGE_CODES } _a : Dict = src_lang if src_lang is not None else 'en_XX' _a : Optional[Any] = self.convert_tokens_to_ids(self._src_lang ) _a : Any = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def __lowercase ( self : List[Any] ): '''simple docstring''' return self._src_lang @src_lang.setter def __lowercase ( self : Union[str, Any] ,_a : str ): '''simple docstring''' _a : Dict = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __lowercase ( self : List[str] ,_a : List[int] ,_a : Optional[List[int]] = None ): '''simple docstring''' 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 __lowercase ( self : Optional[int] ,_a : List[int] ,_a : Optional[List[int]] = None ): '''simple docstring''' _a : Union[str, Any] = [self.sep_token_id] _a : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __lowercase ( self : List[Any] ,_a : List[str] ,_a : str ,_a : Optional[str] ,_a : Optional[str] ,**_a : List[str] ): '''simple docstring''' if src_lang is None or tgt_lang is None: raise ValueError('Translation requires a `src_lang` and a `tgt_lang` for this model' ) _a : Tuple = src_lang _a : str = self(_a ,add_special_tokens=_a ,return_tensors=_a ,**_a ) _a : Optional[int] = self.convert_tokens_to_ids(_a ) _a : Union[str, Any] = tgt_lang_id return inputs def __lowercase ( self : Optional[Any] ,_a : List[str] ,_a : str = "en_XX" ,_a : Optional[List[str]] = None ,_a : str = "ro_RO" ,**_a : Dict ,): '''simple docstring''' _a : Tuple = src_lang _a : List[str] = tgt_lang return super().prepare_seqaseq_batch(_a ,_a ,**_a ) def __lowercase ( self : str ): '''simple docstring''' return self.set_src_lang_special_tokens(self.src_lang ) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' return self.set_tgt_lang_special_tokens(self.tgt_lang ) def __lowercase ( self : Optional[Any] ,_a : Union[str, Any] ): '''simple docstring''' _a : Union[str, Any] = self.convert_tokens_to_ids(_a ) _a : Optional[int] = [] _a : List[str] = [self.eos_token_id, self.cur_lang_code] _a : List[str] = self.convert_ids_to_tokens(self.prefix_tokens ) _a : List[Any] = self.convert_ids_to_tokens(self.suffix_tokens ) _a : Dict = 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 __lowercase ( self : Optional[Any] ,_a : str ): '''simple docstring''' _a : Union[str, Any] = self.convert_tokens_to_ids(_a ) _a : List[str] = [] _a : Tuple = [self.eos_token_id, self.cur_lang_code] _a : str = self.convert_ids_to_tokens(self.prefix_tokens ) _a : Tuple = self.convert_ids_to_tokens(self.suffix_tokens ) _a : Dict = 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 __lowercase ( self : Dict ,_a : str ,_a : Optional[str] = None ): '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( 'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ' 'tokenizer.' ) if not os.path.isdir(_a ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory.""" ) return _a : List[Any] = os.path.join( _a ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ): copyfile(self.vocab_file ,_a ) return (out_vocab_file,)
271
'''simple docstring''' import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def UpperCAmelCase_ (__a : Optional[Any] , __a : str , __a : Optional[Any]=None ): """simple docstring""" assert torch_layer.weight.shape == weight.shape, f"""{torch_layer} layer.weight does not match""" _a : str = nn.Parameter(__a ) if bias is not None: assert torch_layer.bias.shape == bias.shape, f"""{torch_layer} layer.bias does not match""" _a : Any = nn.Parameter(__a ) def UpperCAmelCase_ (__a : int , __a : Optional[Any] , __a : int ): """simple docstring""" _a : Tuple = np.asarray(weights[0] ) _a : Union[str, Any] = np.asarray(weights[1] ) _a : Dict = np.asarray(weights[2] ) set_param( torch_layer.self_attention.query_key , torch.tensor(__a ).transpose(1 , 2 ).contiguous().view(-1 , __a ) , ) set_param( torch_layer.self_attention.value , torch.tensor(__a ).transpose(1 , 2 ).contiguous().view(-1 , __a ) , ) set_param( torch_layer.output.dense , torch.tensor(__a ).view(-1 , __a ).contiguous().transpose(0 , 1 ) , ) def UpperCAmelCase_ (__a : Optional[Any] , __a : Optional[int] , __a : List[str] ): """simple docstring""" _a : Dict = np.asarray(weights[0] ) _a : Union[str, Any] = np.asarray(weights[1] ) _a : str = np.asarray(weights[2] ) _a : int = np.asarray(weights[3] ) set_param( torch_layer.self_attention.query , torch.tensor(__a ).transpose(1 , 2 ).contiguous().view(-1 , __a ) , ) set_param( torch_layer.self_attention.key , torch.tensor(__a ).transpose(1 , 2 ).contiguous().view(-1 , __a ) , ) set_param( torch_layer.self_attention.value , torch.tensor(__a ).transpose(1 , 2 ).contiguous().view(-1 , __a ) , ) set_param( torch_layer.output.dense , torch.tensor(__a ).view(-1 , __a ).contiguous().transpose(0 , 1 ) , ) def UpperCAmelCase_ (__a : Any , __a : Any , __a : Optional[Any] ): """simple docstring""" _a : List[str] = weights[0][0][0] _a : List[Any] = np.asarray(layer_norm_a[0] ) _a : List[str] = np.asarray(layer_norm_a[1] ) set_param( torch_block.attention.layer_norm , torch.tensor(__a ) , torch.tensor(__a ) , ) # lsh weights + output _a : List[str] = weights[0][1] if len(__a ) < 4: set_layer_weights_in_torch_lsh(__a , torch_block.attention , __a ) else: set_layer_weights_in_torch_local(__a , torch_block.attention , __a ) # intermediate weighs _a : Optional[Any] = weights[2][0][1][2] # Chunked Feed Forward if len(__a ) == 4: _a : Union[str, Any] = intermediate_weights[2] # layernorm 2 _a : Any = np.asarray(intermediate_weights[0][0] ) _a : List[Any] = np.asarray(intermediate_weights[0][1] ) set_param( torch_block.feed_forward.layer_norm , torch.tensor(__a ) , torch.tensor(__a ) , ) # intermediate dense _a : Any = np.asarray(intermediate_weights[1][0] ) _a : Any = np.asarray(intermediate_weights[1][1] ) set_param( torch_block.feed_forward.dense.dense , torch.tensor(__a ).transpose(0 , 1 ).contiguous() , torch.tensor(__a ) , ) # intermediate out _a : Optional[int] = np.asarray(intermediate_weights[4][0] ) _a : int = np.asarray(intermediate_weights[4][1] ) set_param( torch_block.feed_forward.output.dense , torch.tensor(__a ).transpose(0 , 1 ).contiguous() , torch.tensor(__a ) , ) def UpperCAmelCase_ (__a : Dict , __a : Dict , __a : List[Any] ): """simple docstring""" _a : Optional[int] = torch_model.reformer # word embeds _a : Tuple = np.asarray(weights[1] ) set_param( torch_model_reformer.embeddings.word_embeddings , torch.tensor(__a ) , ) if isinstance(weights[3] , __a ): _a : Any = torch_model_reformer.embeddings.position_embeddings for emb_idx in range(len(position_embeddings.weights ) ): _a : List[Any] = np.asarray(weights[3][emb_idx][0] ) assert ( position_embeddings.weights[emb_idx].shape == emb_weights.shape ), f"""{position_embeddings[emb_idx]} emb does not match""" _a : Any = nn.Parameter(torch.tensor(__a ) ) _a : List[str] = weights[5] assert len(torch_model_reformer.encoder.layers ) * 4 == len( __a ), "HF and trax model do not have the same number of layers" for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ): _a : Tuple = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)] set_block_weights_in_torch(__a , __a , __a ) # output layer norm _a : Optional[Any] = np.asarray(weights[7][0] ) _a : int = np.asarray(weights[7][1] ) set_param( torch_model_reformer.encoder.layer_norm , torch.tensor(__a ) , torch.tensor(__a ) , ) # output embeddings _a : List[str] = np.asarray(weights[9][0] ) _a : int = np.asarray(weights[9][1] ) set_param( torch_model.lm_head.decoder , torch.tensor(__a ).transpose(0 , 1 ).contiguous() , torch.tensor(__a ) , ) def UpperCAmelCase_ (__a : Tuple , __a : Optional[Any] , __a : Dict ): """simple docstring""" _a : List[Any] = ReformerConfig.from_json_file(__a ) print(f"""Building PyTorch model from configuration: {config}""" ) _a : int = ReformerModelWithLMHead(__a ) with open(__a , 'rb' ) as f: _a : Optional[Any] = pickle.load(__a )['weights'] set_model_weights_in_torch(__a , __a , config.hidden_size ) # Save pytorch-model print(f"""Save PyTorch model to {pytorch_dump_path}""" ) torch.save(model.state_dict() , __a ) if __name__ == "__main__": __lowerCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--trax_model_pkl_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained Reformer model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) __lowerCAmelCase = parser.parse_args() convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
271
1
'''simple docstring''' from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput from .mel import Mel class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = ['''vqvae'''] def __init__( self : Dict ,_a : AutoencoderKL ,_a : UNetaDConditionModel ,_a : Mel ,_a : Union[DDIMScheduler, DDPMScheduler] ,): '''simple docstring''' super().__init__() self.register_modules(unet=_a ,scheduler=_a ,mel=_a ,vqvae=_a ) def __lowercase ( self : int ): '''simple docstring''' return 50 if isinstance(self.scheduler ,_a ) else 1000 @torch.no_grad() def __call__( self : int ,_a : int = 1 ,_a : str = None ,_a : np.ndarray = None ,_a : int = 0 ,_a : int = 0 ,_a : int = None ,_a : torch.Generator = None ,_a : float = 0 ,_a : float = 0 ,_a : torch.Generator = None ,_a : float = 0 ,_a : torch.Tensor = None ,_a : torch.Tensor = None ,_a : Union[str, Any]=True ,): '''simple docstring''' _a : Union[str, Any] = steps or self.get_default_steps() self.scheduler.set_timesteps(_a ) _a : Optional[int] = step_generator or generator # For backwards compatibility if type(self.unet.config.sample_size ) == int: _a : Tuple = (self.unet.config.sample_size, self.unet.config.sample_size) if noise is None: _a : Optional[Any] = randn_tensor( ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size[0], self.unet.config.sample_size[1], ) ,generator=_a ,device=self.device ,) _a : Optional[int] = noise _a : str = None if audio_file is not None or raw_audio is not None: self.mel.load_audio(_a ,_a ) _a : List[Any] = self.mel.audio_slice_to_image(_a ) _a : Optional[Any] = np.frombuffer(input_image.tobytes() ,dtype='uint8' ).reshape( (input_image.height, input_image.width) ) _a : Union[str, Any] = (input_image / 255) * 2 - 1 _a : Optional[int] = torch.tensor(input_image[np.newaxis, :, :] ,dtype=torch.float ).to(self.device ) if self.vqvae is not None: _a : Dict = self.vqvae.encode(torch.unsqueeze(_a ,0 ) ).latent_dist.sample( generator=_a )[0] _a : Optional[Any] = self.vqvae.config.scaling_factor * input_images if start_step > 0: _a : str = self.scheduler.add_noise(_a ,_a ,self.scheduler.timesteps[start_step - 1] ) _a : int = ( self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length ) _a : Optional[Any] = int(mask_start_secs * pixels_per_second ) _a : Any = int(mask_end_secs * pixels_per_second ) _a : int = self.scheduler.add_noise(_a ,_a ,torch.tensor(self.scheduler.timesteps[start_step:] ) ) for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:] ) ): if isinstance(self.unet ,_a ): _a : Union[str, Any] = self.unet(_a ,_a ,_a )['sample'] else: _a : List[Any] = self.unet(_a ,_a )['sample'] if isinstance(self.scheduler ,_a ): _a : Optional[Any] = self.scheduler.step( model_output=_a ,timestep=_a ,sample=_a ,eta=_a ,generator=_a ,)['prev_sample'] else: _a : str = self.scheduler.step( model_output=_a ,timestep=_a ,sample=_a ,generator=_a ,)['prev_sample'] if mask is not None: if mask_start > 0: _a : str = mask[:, step, :, :mask_start] if mask_end > 0: _a : Union[str, Any] = mask[:, step, :, -mask_end:] if self.vqvae is not None: # 0.18215 was scaling factor used in training to ensure unit variance _a : Tuple = 1 / self.vqvae.config.scaling_factor * images _a : Any = self.vqvae.decode(_a )['sample'] _a : List[Any] = (images / 2 + 0.5).clamp(0 ,1 ) _a : Union[str, Any] = images.cpu().permute(0 ,2 ,3 ,1 ).numpy() _a : Union[str, Any] = (images * 255).round().astype('uint8' ) _a : Optional[int] = list( (Image.fromarray(_[:, :, 0] ) for _ in images) if images.shape[3] == 1 else (Image.fromarray(_a ,mode='RGB' ).convert('L' ) for _ in images) ) _a : int = [self.mel.image_to_audio(_a ) for _ in images] if not return_dict: return images, (self.mel.get_sample_rate(), audios) return BaseOutput(**AudioPipelineOutput(np.array(_a )[:, np.newaxis, :] ) ,**ImagePipelineOutput(_a ) ) @torch.no_grad() def __lowercase ( self : int ,_a : List[Image.Image] ,_a : int = 50 ): '''simple docstring''' assert isinstance(self.scheduler ,_a ) self.scheduler.set_timesteps(_a ) _a : int = np.array( [np.frombuffer(image.tobytes() ,dtype='uint8' ).reshape((1, image.height, image.width) ) for image in images] ) _a : Union[str, Any] = (sample / 255) * 2 - 1 _a : str = torch.Tensor(_a ).to(self.device ) for t in self.progress_bar(torch.flip(self.scheduler.timesteps ,(0,) ) ): _a : Dict = t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps _a : List[str] = self.scheduler.alphas_cumprod[t] _a : Dict = ( self.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.scheduler.final_alpha_cumprod ) _a : Any = 1 - alpha_prod_t _a : List[Any] = self.unet(_a ,_a )['sample'] _a : List[str] = (1 - alpha_prod_t_prev) ** 0.5 * model_output _a : Dict = (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5) _a : List[Any] = sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output return sample @staticmethod def __lowercase ( _a : torch.Tensor ,_a : torch.Tensor ,_a : float ): '''simple docstring''' _a : Union[str, Any] = acos(torch.dot(torch.flatten(_a ) ,torch.flatten(_a ) ) / torch.norm(_a ) / torch.norm(_a ) ) return sin((1 - alpha) * theta ) * xa / sin(_a ) + sin(alpha * theta ) * xa / sin(_a )
271
'''simple docstring''' import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" @property def __lowercase ( self : Union[str, Any] ): '''simple docstring''' torch.manual_seed(0 ) _a : Any = UNetaDModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=3 ,out_channels=3 ,down_block_types=('DownBlock2D', 'AttnDownBlock2D') ,up_block_types=('AttnUpBlock2D', 'UpBlock2D') ,) return model @property def __lowercase ( self : Optional[int] ): '''simple docstring''' torch.manual_seed(0 ) _a : Union[str, Any] = VQModel( block_out_channels=[32, 64] ,in_channels=3 ,out_channels=3 ,down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] ,up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] ,latent_channels=3 ,) return model @property def __lowercase ( self : Optional[int] ): '''simple docstring''' torch.manual_seed(0 ) _a : Any = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1E-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1000 ,) return CLIPTextModel(_a ) def __lowercase ( self : Tuple ): '''simple docstring''' _a : Dict = self.dummy_uncond_unet _a : List[Any] = DDIMScheduler() _a : List[Any] = self.dummy_vq_model _a : str = LDMPipeline(unet=_a ,vqvae=_a ,scheduler=_a ) ldm.to(_a ) ldm.set_progress_bar_config(disable=_a ) _a : List[str] = torch.manual_seed(0 ) _a : List[str] = ldm(generator=_a ,num_inference_steps=2 ,output_type='numpy' ).images _a : List[str] = torch.manual_seed(0 ) _a : Union[str, Any] = ldm(generator=_a ,num_inference_steps=2 ,output_type='numpy' ,return_dict=_a )[0] _a : Tuple = image[0, -3:, -3:, -1] _a : Optional[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _a : int = np.array([0.8512, 0.818, 0.6411, 0.6808, 0.4465, 0.5618, 0.46, 0.6231, 0.5172] ) _a : Any = 1E-2 if torch_device != 'mps' else 3E-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < tolerance @slow @require_torch class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a : List[str] = LDMPipeline.from_pretrained('CompVis/ldm-celebahq-256' ) ldm.to(_a ) ldm.set_progress_bar_config(disable=_a ) _a : Optional[int] = torch.manual_seed(0 ) _a : Dict = ldm(generator=_a ,num_inference_steps=5 ,output_type='numpy' ).images _a : str = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) _a : Optional[int] = np.array([0.4399, 0.4_4975, 0.4_6825, 0.474, 0.4359, 0.4581, 0.4_5095, 0.4341, 0.4447] ) _a : int = 1E-2 if torch_device != 'mps' else 3E-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance
271
1
'''simple docstring''' import heapq as hq import math from collections.abc import Iterator class UpperCAmelCase__ : """simple docstring""" def __init__( self : Optional[Any] ,_a : Any ): '''simple docstring''' _a : Union[str, Any] = str(id_ ) _a : List[Any] = None _a : int = None _a : Union[str, Any] = [] _a : Any = {} # {vertex:distance} def __lt__( self : Any ,_a : Optional[Any] ): '''simple docstring''' return self.key < other.key def __repr__( self : List[Any] ): '''simple docstring''' return self.id def __lowercase ( self : List[str] ,_a : str ): '''simple docstring''' self.neighbors.append(_a ) def __lowercase ( self : Any ,_a : Any ,_a : Dict ): '''simple docstring''' _a : Dict = weight def UpperCAmelCase_ (__a : List[Any] , __a : Union[str, Any] , __a : int , __a : Tuple ): """simple docstring""" graph[a - 1].add_neighbor(graph[b - 1] ) graph[b - 1].add_neighbor(graph[a - 1] ) # add the edges: graph[a - 1].add_edge(graph[b - 1] , __a ) graph[b - 1].add_edge(graph[a - 1] , __a ) def UpperCAmelCase_ (__a : list , __a : Vertex ): """simple docstring""" _a : List[str] = [] for u in graph: _a : Any = math.inf _a : Optional[Any] = None _a : Any = 0 _a : Tuple = graph[:] while q: _a : Any = min(__a ) q.remove(__a ) for v in u.neighbors: if (v in q) and (u.edges[v.id] < v.key): _a : List[Any] = u _a : Any = u.edges[v.id] for i in range(1 , len(__a ) ): a.append((int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) ) return a def UpperCAmelCase_ (__a : list , __a : Vertex ): """simple docstring""" for u in graph: _a : Any = math.inf _a : List[Any] = None _a : Union[str, Any] = 0 _a : Tuple = list(__a ) hq.heapify(__a ) while h: _a : Any = hq.heappop(__a ) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): _a : int = u _a : str = u.edges[v.id] hq.heapify(__a ) for i in range(1 , len(__a ) ): yield (int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) def UpperCAmelCase_ (): """simple docstring""" if __name__ == "__main__": import doctest doctest.testmod()
271
'''simple docstring''' import warnings from ...utils import logging from .image_processing_beit import BeitImageProcessor __lowerCAmelCase = logging.get_logger(__name__) class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" def __init__( self : int ,*_a : Optional[int] ,**_a : str ): '''simple docstring''' warnings.warn( 'The class BeitFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use BeitImageProcessor instead.' ,_a ,) super().__init__(*_a ,**_a )
271
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __lowerCAmelCase = { """configuration_xlm_roberta""": [ """XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XLMRobertaConfig""", """XLMRobertaOnnxConfig""", ], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = ["""XLMRobertaTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = ["""XLMRobertaTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ """XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST""", """XLMRobertaForCausalLM""", """XLMRobertaForMaskedLM""", """XLMRobertaForMultipleChoice""", """XLMRobertaForQuestionAnswering""", """XLMRobertaForSequenceClassification""", """XLMRobertaForTokenClassification""", """XLMRobertaModel""", """XLMRobertaPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ """TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFXLMRobertaForCausalLM""", """TFXLMRobertaForMaskedLM""", """TFXLMRobertaForMultipleChoice""", """TFXLMRobertaForQuestionAnswering""", """TFXLMRobertaForSequenceClassification""", """TFXLMRobertaForTokenClassification""", """TFXLMRobertaModel""", """TFXLMRobertaPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ """FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST""", """FlaxXLMRobertaForMaskedLM""", """FlaxXLMRobertaForCausalLM""", """FlaxXLMRobertaForMultipleChoice""", """FlaxXLMRobertaForQuestionAnswering""", """FlaxXLMRobertaForSequenceClassification""", """FlaxXLMRobertaForTokenClassification""", """FlaxXLMRobertaModel""", """FlaxXLMRobertaPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_xlm_roberta import ( XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMRobertaConfig, XLMRobertaOnnxConfig, ) try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlm_roberta import XLMRobertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlm_roberta_fast import XLMRobertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm_roberta import ( XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, XLMRobertaForCausalLM, XLMRobertaForMaskedLM, XLMRobertaForMultipleChoice, XLMRobertaForQuestionAnswering, XLMRobertaForSequenceClassification, XLMRobertaForTokenClassification, XLMRobertaModel, XLMRobertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm_roberta import ( TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMRobertaForCausalLM, TFXLMRobertaForMaskedLM, TFXLMRobertaForMultipleChoice, TFXLMRobertaForQuestionAnswering, TFXLMRobertaForSequenceClassification, TFXLMRobertaForTokenClassification, TFXLMRobertaModel, TFXLMRobertaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xlm_roberta import ( FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxXLMRobertaForCausalLM, FlaxXLMRobertaForMaskedLM, FlaxXLMRobertaForMultipleChoice, FlaxXLMRobertaForQuestionAnswering, FlaxXLMRobertaForSequenceClassification, FlaxXLMRobertaForTokenClassification, FlaxXLMRobertaModel, FlaxXLMRobertaPreTrainedModel, ) else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
271
'''simple docstring''' from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.utils.data import DistributedSampler, RandomSampler from transformers import PreTrainedModel, Trainer, logging from transformers.integrations import is_fairscale_available from transformers.models.fsmt.configuration_fsmt import FSMTConfig from transformers.optimization 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_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.trainer_pt_utils import get_tpu_sampler from transformers.training_args import ParallelMode from transformers.utils import is_torch_tpu_available if is_fairscale_available(): from fairscale.optim import OSS __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = { """linear""": get_linear_schedule_with_warmup, """cosine""": get_cosine_schedule_with_warmup, """cosine_w_restarts""": get_cosine_with_hard_restarts_schedule_with_warmup, """polynomial""": get_polynomial_decay_schedule_with_warmup, """constant""": get_constant_schedule, """constant_w_warmup""": get_constant_schedule_with_warmup, } class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" def __init__( self : Optional[int] ,_a : Optional[Any]=None ,_a : Dict=None ,*_a : int ,**_a : str ): '''simple docstring''' super().__init__(*_a ,**_a ) if config is None: assert isinstance(self.model ,_a ), ( "If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is" F""" {self.model.__class__}""" ) _a : List[Any] = self.model.config else: _a : Optional[int] = config _a : List[str] = data_args _a : List[Any] = self.config.tgt_vocab_size if isinstance(self.config ,_a ) else self.config.vocab_size if self.args.label_smoothing != 0 or (self.data_args is not None and self.data_args.ignore_pad_token_for_loss): assert self.config.pad_token_id is not None, ( "Make sure that `config.pad_token_id` is correcly defined when ignoring `pad_token` for loss" " calculation or doing label smoothing." ) if self.config.pad_token_id is None and self.config.eos_token_id is not None: logger.warning( F"""The `config.pad_token_id` is `None`. Using `config.eos_token_id` = {self.config.eos_token_id} for""" ' padding..' ) if self.args.label_smoothing == 0: _a : List[str] = torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id ) else: # dynamically import label_smoothed_nll_loss from utils import label_smoothed_nll_loss _a : Tuple = label_smoothed_nll_loss def __lowercase ( self : List[str] ,_a : int ): '''simple docstring''' if self.optimizer is None: _a : Union[str, Any] = ['bias', 'LayerNorm.weight'] _a : Tuple = [ { 'params': [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay )], 'weight_decay': self.args.weight_decay, }, { 'params': [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay )], 'weight_decay': 0.0, }, ] _a : Optional[int] = Adafactor if self.args.adafactor else AdamW if self.args.adafactor: _a : Any = Adafactor _a : Dict = {'scale_parameter': False, 'relative_step': False} else: _a : Union[str, Any] = AdamW _a : str = { 'betas': (self.args.adam_betaa, self.args.adam_betaa), 'eps': self.args.adam_epsilon, } _a : Union[str, Any] = self.args.learning_rate if self.sharded_ddp: _a : str = OSS( params=_a ,optim=_a ,**_a ,) else: _a : Tuple = optimizer_cls(_a ,**_a ) if self.lr_scheduler is None: _a : List[Any] = self._get_lr_scheduler(_a ) else: # ignoring --lr_scheduler logger.warning('scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored.' ) def __lowercase ( self : List[Any] ,_a : List[Any] ): '''simple docstring''' _a : str = arg_to_scheduler[self.args.lr_scheduler] if self.args.lr_scheduler == "constant": _a : int = schedule_func(self.optimizer ) elif self.args.lr_scheduler == "constant_w_warmup": _a : List[str] = schedule_func(self.optimizer ,num_warmup_steps=self.args.warmup_steps ) else: _a : Optional[int] = schedule_func( self.optimizer ,num_warmup_steps=self.args.warmup_steps ,num_training_steps=_a ) return scheduler def __lowercase ( self : Tuple ): '''simple docstring''' if isinstance(self.train_dataset ,torch.utils.data.IterableDataset ): return None elif is_torch_tpu_available(): return get_tpu_sampler(self.train_dataset ) else: if self.args.sortish_sampler: self.train_dataset.make_sortish_sampler( self.args.per_device_train_batch_size ,distributed=(self.args.parallel_mode == ParallelMode.DISTRIBUTED) ,) return ( RandomSampler(self.train_dataset ) if self.args.local_rank == -1 else DistributedSampler(self.train_dataset ) ) def __lowercase ( self : Dict ,_a : Dict ,_a : Any ,_a : Dict ): '''simple docstring''' if self.args.label_smoothing == 0: if self.data_args is not None and self.data_args.ignore_pad_token_for_loss: # force training to ignore pad token _a : List[Any] = model(**_a ,use_cache=_a )[0] _a : Union[str, Any] = self.loss_fn(logits.view(-1 ,logits.shape[-1] ) ,labels.view(-1 ) ) else: # compute usual loss via models _a, _a : Union[str, Any] = model(**_a ,labels=_a ,use_cache=_a )[:2] else: # compute label smoothed loss _a : List[Any] = model(**_a ,use_cache=_a )[0] _a : Any = torch.nn.functional.log_softmax(_a ,dim=-1 ) _a, _a : List[str] = self.loss_fn(_a ,_a ,self.args.label_smoothing ,ignore_index=self.config.pad_token_id ) return loss, logits def __lowercase ( self : Optional[int] ,_a : Union[str, Any] ,_a : List[Any] ): '''simple docstring''' _a : Optional[int] = inputs.pop('labels' ) _a, _a : int = self._compute_loss(_a ,_a ,_a ) return loss def __lowercase ( self : Optional[Any] ,_a : nn.Module ,_a : Dict[str, Union[torch.Tensor, Any]] ,_a : bool ,_a : Optional[List[str]] = None ,): '''simple docstring''' _a : int = self._prepare_inputs(_a ) _a : Any = { 'max_length': self.data_args.val_max_target_length if self.data_args is not None else self.config.max_length, 'num_beams': self.data_args.eval_beams if self.data_args is not None else self.config.num_beams, } if self.args.predict_with_generate and not self.args.prediction_loss_only: _a : int = self.model.generate( inputs['input_ids'] ,attention_mask=inputs['attention_mask'] ,**_a ,) # in case the batch is shorter than max length, the output should be padded if generated_tokens.shape[-1] < gen_kwargs["max_length"]: _a : int = self._pad_tensors_to_max_len(_a ,gen_kwargs['max_length'] ) _a : Union[str, Any] = inputs.pop('labels' ) with torch.no_grad(): # compute loss on predict data _a, _a : Optional[int] = self._compute_loss(_a ,_a ,_a ) _a : Optional[Any] = loss.mean().detach() if self.args.prediction_loss_only: return (loss, None, None) _a : Optional[Any] = generated_tokens if self.args.predict_with_generate else logits if labels.shape[-1] < gen_kwargs["max_length"]: _a : Dict = self._pad_tensors_to_max_len(_a ,gen_kwargs['max_length'] ) return (loss, logits, labels) def __lowercase ( self : str ,_a : Tuple ,_a : Tuple ): '''simple docstring''' _a : List[Any] = self.config.pad_token_id if self.config.pad_token_id is not None else self.config.eos_token_id if pad_token_id is None: raise ValueError( 'Make sure that either `config.pad_token_id` or `config.eos_token_id` is defined if tensor has to be' F""" padded to `max_length`={max_length}""" ) _a : int = pad_token_id * torch.ones( (tensor.shape[0], max_length) ,dtype=tensor.dtype ,device=tensor.device ) _a : Union[str, Any] = tensor return padded_tensor
271
1
'''simple docstring''' import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( UniSpeechConfig, UniSpeechForCTC, UniSpeechForPreTraining, WavaVecaFeatureExtractor, WavaVecaPhonemeCTCTokenizer, WavaVecaProcessor, logging, ) logging.set_verbosity_info() __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = { """post_extract_proj""": """feature_projection.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.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """quantizer.weight_proj""": """quantizer.weight_proj""", """quantizer.vars""": """quantizer.codevectors""", """project_q""": """project_q""", """final_proj""": """project_hid""", """w2v_encoder.proj""": """ctc_proj""", """mask_emb""": """masked_spec_embed""", } __lowerCAmelCase = [ """ctc_proj""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", ] def UpperCAmelCase_ (__a : Dict , __a : List[Any] , __a : Any , __a : Optional[int] , __a : Tuple , __a : Dict ): """simple docstring""" for attribute in key.split('.' ): if is_finetuned: if attribute in ["quantizer", "project_q", "project_hid"]: # those layers are only relevant for pretraining and should be dropped return if attribute == "ctc_proj": # we should rename `ctc_proj` to `lm_head` for fine-tuned phoneme models _a : Any = 'lm_head' _a : Any = getattr(__a , __a ) if weight_type is not None: _a : List[Any] = getattr(__a , __a ).shape else: _a : Optional[int] = 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": _a : List[Any] = value elif weight_type == "weight_g": _a : Union[str, Any] = value elif weight_type == "weight_v": _a : Dict = value elif weight_type == "bias": _a : Optional[Any] = value else: _a : Any = value logger.info(f"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.""" ) def UpperCAmelCase_ (__a : int , __a : Optional[Any] , __a : Optional[int] ): """simple docstring""" _a : int = [] _a : List[str] = fairseq_model.state_dict() _a : List[Any] = hf_model.unispeech.feature_extractor for name, value in fairseq_dict.items(): _a : Any = False if "conv_layers" in name: load_conv_layer( __a , __a , __a , __a , hf_model.config.feat_extract_norm == 'group' , ) _a : List[str] = True else: for key, mapped_key in MAPPING.items(): _a : Optional[int] = 'unispeech.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: _a : Union[str, Any] = True if "*" in mapped_key: _a : Dict = name.split(__a )[0].split('.' )[-2] _a : Optional[int] = mapped_key.replace('*' , __a ) if "weight_g" in name: _a : List[Any] = 'weight_g' elif "weight_v" in name: _a : str = 'weight_v' elif "bias" in name: _a : Dict = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj _a : str = 'weight' else: _a : List[str] = None set_recursively(__a , __a , __a , __a , __a , __a ) continue if not is_used: unused_weights.append(__a ) logger.warning(f"""Unused weights: {unused_weights}""" ) def UpperCAmelCase_ (__a : Union[str, Any] , __a : List[Any] , __a : List[Any] , __a : Dict , __a : int ): """simple docstring""" _a : Any = full_name.split('conv_layers.' )[-1] _a : int = name.split('.' ) _a : Optional[Any] = int(items[0] ) _a : Union[str, Any] = 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.""" ) _a : int = 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.""" ) _a : Tuple = 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." ) _a : List[str] = 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.""" ) _a : Optional[Any] = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(__a ) @torch.no_grad() def UpperCAmelCase_ (__a : Union[str, Any] , __a : Union[str, Any] , __a : Any=None , __a : Optional[Any]=None , __a : Union[str, Any]=True ): """simple docstring""" if config_path is not None: _a : Optional[Any] = UniSpeechConfig.from_pretrained(__a ) else: _a : str = UniSpeechConfig() if is_finetuned: if dict_path: _a : int = Dictionary.load_from_json(__a ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq _a : Optional[int] = target_dict.pad_index _a : Union[str, Any] = target_dict.bos_index _a : List[str] = target_dict.eos_index _a : List[str] = len(target_dict.symbols ) _a : Optional[Any] = os.path.join(__a , 'vocab.json' ) if not os.path.isdir(__a ): logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(__a ) ) return os.makedirs(__a , exist_ok=__a ) _a : Optional[Any] = target_dict.indices # fairseq has the <pad> and <s> switched _a : Optional[Any] = 4_2 _a : Any = 4_3 with open(__a , 'w' , encoding='utf-8' ) as vocab_handle: json.dump(__a , __a ) _a : Tuple = WavaVecaPhonemeCTCTokenizer( __a , 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=__a , ) _a : str = True if config.feat_extract_norm == 'layer' else False _a : Tuple = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6_0_0_0 , padding_value=0 , do_normalize=__a , return_attention_mask=__a , ) _a : int = WavaVecaProcessor(feature_extractor=__a , tokenizer=__a ) processor.save_pretrained(__a ) _a : str = UniSpeechForCTC(__a ) else: _a : str = UniSpeechForPreTraining(__a ) if is_finetuned: _a, _a, _a : str = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] ), 'w2v_path': checkpoint_path} ) else: _a, _a, _a : Union[str, Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) _a : Union[str, Any] = model[0].eval() recursively_load_weights(__a , __a , __a ) hf_unispeech.save_pretrained(__a ) if __name__ == "__main__": __lowerCAmelCase = 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( """--not_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) __lowerCAmelCase = parser.parse_args() convert_unispeech_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
271
'''simple docstring''' import gzip import hashlib import json import multiprocessing import os import re import shutil import time from pathlib import Path import numpy as np from arguments import PreprocessingArguments from datasets import load_dataset from minhash_deduplication import deduplicate_dataset from transformers import AutoTokenizer, HfArgumentParser __lowerCAmelCase = re.compile(r"""\s+""") def UpperCAmelCase_ (__a : Any ): """simple docstring""" return {"hash": hashlib.mda(re.sub(__a , '' , example['content'] ).encode('utf-8' ) ).hexdigest()} def UpperCAmelCase_ (__a : str ): """simple docstring""" _a : List[str] = [len(__a ) for line in example['content'].splitlines()] return {"line_mean": np.mean(__a ), "line_max": max(__a )} def UpperCAmelCase_ (__a : str ): """simple docstring""" _a : Union[str, Any] = np.mean([c.isalnum() for c in example['content']] ) return {"alpha_frac": alpha_frac} def UpperCAmelCase_ (__a : Optional[int] , __a : Any ): """simple docstring""" if example["hash"] in uniques: uniques.remove(example['hash'] ) return True else: return False def UpperCAmelCase_ (__a : int , __a : Union[str, Any]=5 ): """simple docstring""" _a : Optional[int] = ['auto-generated', 'autogenerated', 'automatically generated'] _a : List[str] = example['content'].splitlines() for _, line in zip(range(__a ) , __a ): for keyword in keywords: if keyword in line.lower(): return {"autogenerated": True} else: return {"autogenerated": False} def UpperCAmelCase_ (__a : List[str] , __a : Dict=5 , __a : Tuple=0.05 ): """simple docstring""" _a : Optional[int] = ['unit tests', 'test file', 'configuration file'] _a : int = example['content'].splitlines() _a : int = 0 _a : Dict = 0 # first test for _, line in zip(range(__a ) , __a ): for keyword in keywords: if keyword in line.lower(): return {"config_or_test": True} # second test _a : int = example['content'].count('\n' ) _a : int = int(coeff * nlines ) for line in lines: count_config += line.lower().count('config' ) count_test += line.lower().count('test' ) if count_config > threshold or count_test > threshold: return {"config_or_test": True} return {"config_or_test": False} def UpperCAmelCase_ (__a : Optional[int] ): """simple docstring""" _a : List[str] = ['def ', 'class ', 'for ', 'while '] _a : str = example['content'].splitlines() for line in lines: for keyword in keywords: if keyword in line.lower(): return {"has_no_keywords": False} return {"has_no_keywords": True} def UpperCAmelCase_ (__a : int , __a : Any=4 ): """simple docstring""" _a : List[str] = example['content'].splitlines() _a : Dict = 0 for line in lines: counter += line.lower().count('=' ) if counter > minimum: return {"has_few_assignments": False} return {"has_few_assignments": True} def UpperCAmelCase_ (__a : str ): """simple docstring""" _a : Optional[Any] = tokenizer(example['content'] , truncation=__a )['input_ids'] _a : Optional[int] = len(example['content'] ) / len(__a ) return {"ratio": ratio} def UpperCAmelCase_ (__a : str ): """simple docstring""" _a : Dict = {} results.update(get_hash(__a ) ) results.update(line_stats(__a ) ) results.update(alpha_stats(__a ) ) results.update(char_token_ratio(__a ) ) results.update(is_autogenerated(__a ) ) results.update(is_config_or_test(__a ) ) results.update(has_no_keywords(__a ) ) results.update(has_few_assignments(__a ) ) return results def UpperCAmelCase_ (__a : Any , __a : Any , __a : str ): """simple docstring""" if not check_uniques(__a , __a ): return False elif example["autogenerated"]: return False elif example["line_max"] > args.line_max: return False elif example["line_mean"] > args.line_mean: return False elif example["alpha_frac"] < args.alpha_frac: return False elif example["ratio"] < args.min_token_ratio: return False elif example["config_or_test"] and np.random.rand() <= args.filter_proba: return False elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba: return False elif example["has_few_assignments"]: return False else: return True def UpperCAmelCase_ (__a : Union[str, Any] ): """simple docstring""" with open(__a , 'rb' ) as f_in: with gzip.open(str(__a ) + '.gz' , 'wb' , compresslevel=6 ) as f_out: shutil.copyfileobj(__a , __a ) os.unlink(__a ) # Settings __lowerCAmelCase = HfArgumentParser(PreprocessingArguments) __lowerCAmelCase = parser.parse_args() if args.num_workers is None: __lowerCAmelCase = multiprocessing.cpu_count() __lowerCAmelCase = AutoTokenizer.from_pretrained(args.tokenizer_dir) # Load dataset __lowerCAmelCase = time.time() __lowerCAmelCase = load_dataset(args.dataset_name, split="""train""") print(f'''Time to load dataset: {time.time()-t_start:.2f}''') # Run preprocessing __lowerCAmelCase = time.time() __lowerCAmelCase = ds.map(preprocess, num_proc=args.num_workers) print(f'''Time to preprocess dataset: {time.time()-t_start:.2f}''') # Deduplicate hashes __lowerCAmelCase = set(ds.unique("""hash""")) __lowerCAmelCase = len(uniques) / len(ds) print(f'''Fraction of duplicates: {1-frac:.2%}''') # Deduplicate data and apply heuristics __lowerCAmelCase = time.time() __lowerCAmelCase = ds.filter(filter, fn_kwargs={"""uniques""": uniques, """args""": args}) print(f'''Time to filter dataset: {time.time()-t_start:.2f}''') print(f'''Size of filtered dataset: {len(ds_filter)}''') # Deduplicate with minhash and jaccard similarity if args.near_deduplication: __lowerCAmelCase = time.time() __lowerCAmelCase , __lowerCAmelCase = deduplicate_dataset(ds_filter, args.jaccard_threshold) print(f'''Time to deduplicate dataset: {time.time()-t_start:.2f}''') print(f'''Size of deduplicate dataset: {len(ds_filter)}''') # Save data in batches of samples_per_file __lowerCAmelCase = Path(args.output_dir) output_dir.mkdir(exist_ok=True) # save duplicate_clusters in the output_dir as artifacts # not sure it is the right place the save it if args.near_deduplication: with open(output_dir / """duplicate_clusters.json""", """w""") as f: json.dump(duplicate_clusters, f) __lowerCAmelCase = output_dir / """data""" data_dir.mkdir(exist_ok=True) __lowerCAmelCase = time.time() for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)): __lowerCAmelCase = str(data_dir / f'''file-{file_number+1:012}.json''') __lowerCAmelCase = min(len(ds_filter), index + args.samples_per_file) ds_filter.select(list(range(index, end_index))).to_json(file_path) compress_file(file_path) print(f'''Time to save dataset: {time.time()-t_start:.2f}''')
271
1
'''simple docstring''' import requests __lowerCAmelCase = """""" # <-- Put your OpenWeatherMap appid here! __lowerCAmelCase = """https://api.openweathermap.org/data/2.5/""" def UpperCAmelCase_ (__a : str = "Chicago" , __a : str = APPID ): """simple docstring""" return requests.get(URL_BASE + 'weather' , params=locals() ).json() def UpperCAmelCase_ (__a : str = "Kolkata, India" , __a : str = APPID ): """simple docstring""" return requests.get(URL_BASE + 'forecast' , params=locals() ).json() def UpperCAmelCase_ (__a : float = 55.68 , __a : float = 12.57 , __a : str = APPID ): """simple docstring""" return requests.get(URL_BASE + 'onecall' , params=locals() ).json() if __name__ == "__main__": from pprint import pprint while True: __lowerCAmelCase = input("""Enter a location:""").strip() if location: pprint(current_weather(location)) else: break
271
'''simple docstring''' import argparse from typing import List import evaluate import numpy as np import torch from datasets import DatasetDict, load_dataset # New Code # # We'll be using StratifiedKFold for this example from sklearn.model_selection import StratifiedKFold from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to perform Cross Validation, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## __lowerCAmelCase = 1_6 __lowerCAmelCase = 3_2 def UpperCAmelCase_ (__a : Accelerator , __a : DatasetDict , __a : List[int] , __a : List[int] , __a : int = 1_6 ): """simple docstring""" _a : Union[str, Any] = AutoTokenizer.from_pretrained('bert-base-cased' ) _a : str = DatasetDict( { 'train': dataset['train'].select(__a ), 'validation': dataset['train'].select(__a ), 'test': dataset['validation'], } ) def tokenize_function(__a : List[Any] ): # max_length=None => use the model max length (it's actually the default) _a : Optional[int] = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=__a , max_length=__a ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): _a : List[str] = datasets.map( __a , batched=__a , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _a : List[Any] = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(__a : int ): # On TPU it's best to pad everything to the same length or training will be very slow. _a : Dict = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _a : Tuple = 1_6 elif accelerator.mixed_precision != "no": _a : List[Any] = 8 else: _a : List[Any] = None return tokenizer.pad( __a , padding='longest' , max_length=__a , pad_to_multiple_of=__a , return_tensors='pt' , ) # Instantiate dataloaders. _a : Any = DataLoader( tokenized_datasets['train'] , shuffle=__a , collate_fn=__a , batch_size=__a ) _a : Optional[int] = DataLoader( tokenized_datasets['validation'] , shuffle=__a , collate_fn=__a , batch_size=__a ) _a : Optional[Any] = DataLoader( tokenized_datasets['test'] , shuffle=__a , collate_fn=__a , batch_size=__a ) return train_dataloader, eval_dataloader, test_dataloader def UpperCAmelCase_ (__a : Any , __a : Union[str, Any] ): """simple docstring""" _a : Dict = [] # Download the dataset _a : Tuple = load_dataset('glue' , 'mrpc' ) # Create our splits _a : Union[str, Any] = StratifiedKFold(n_splits=int(args.num_folds ) ) # Initialize accelerator _a : Any = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _a : Optional[Any] = config['lr'] _a : Optional[int] = int(config['num_epochs'] ) _a : Dict = int(config['seed'] ) _a : Dict = int(config['batch_size'] ) _a : Optional[int] = evaluate.load('glue' , 'mrpc' ) # If the batch size is too big we use gradient accumulation _a : List[Any] = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: _a : Any = batch_size // MAX_GPU_BATCH_SIZE _a : List[str] = MAX_GPU_BATCH_SIZE set_seed(__a ) # New Code # # Create our folds: _a : int = kfold.split(np.zeros(datasets['train'].num_rows ) , datasets['train']['label'] ) _a : Any = [] # Iterate over them for i, (train_idxs, valid_idxs) in enumerate(__a ): _a, _a, _a : Optional[Any] = get_fold_dataloaders( __a , __a , __a , __a , ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _a : Dict = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=__a ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _a : List[Any] = model.to(accelerator.device ) # Instantiate optimizer _a : List[str] = AdamW(params=model.parameters() , lr=__a ) # Instantiate scheduler _a : List[Any] = get_linear_schedule_with_warmup( optimizer=__a , num_warmup_steps=1_0_0 , num_training_steps=(len(__a ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _a, _a, _a, _a, _a : Union[str, Any] = accelerator.prepare( __a , __a , __a , __a , __a ) # Now we train the model for epoch in range(__a ): model.train() for step, batch in enumerate(__a ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _a : Dict = model(**__a ) _a : int = outputs.loss _a : Any = loss / gradient_accumulation_steps accelerator.backward(__a ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__a ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _a : Union[str, Any] = model(**__a ) _a : Tuple = outputs.logits.argmax(dim=-1 ) _a, _a : Any = accelerator.gather_for_metrics((predictions, batch['labels']) ) metric.add_batch( predictions=__a , references=__a , ) _a : List[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" , __a ) # New Code # # We also run predictions on the test set at the very end _a : Any = [] for step, batch in enumerate(__a ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _a : Tuple = model(**__a ) _a : Dict = outputs.logits _a, _a : Optional[int] = accelerator.gather_for_metrics((predictions, batch['labels']) ) fold_predictions.append(predictions.cpu() ) if i == 0: # We need all of the test predictions test_references.append(references.cpu() ) # Use accelerator.print to print only on the main process. test_predictions.append(torch.cat(__a , dim=0 ) ) # We now need to release all our memory and get rid of the current model, optimizer, etc accelerator.free_memory() # New Code # # Finally we check the accuracy of our folded results: _a : Dict = torch.cat(__a , dim=0 ) _a : Any = torch.stack(__a , dim=0 ).sum(dim=0 ).div(int(args.num_folds ) ).argmax(dim=-1 ) _a : str = metric.compute(predictions=__a , references=__a ) accelerator.print('Average test metrics from all folds:' , __a ) def UpperCAmelCase_ (): """simple docstring""" _a : Any = argparse.ArgumentParser(description='Simple example of training script.' ) parser.add_argument( '--mixed_precision' , type=__a , default=__a , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.' ) # New Code # parser.add_argument('--num_folds' , type=__a , default=3 , help='The number of splits to perform across the dataset' ) _a : Any = parser.parse_args() _a : int = {'lr': 2e-5, 'num_epochs': 3, 'seed': 4_2, 'batch_size': 1_6} training_function(__a , __a ) if __name__ == "__main__": main()
271
1
'''simple docstring''' from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : List[Any] = '''''' __UpperCAmelCase : str = '''hf-legacy''' # "hf://"" is reserved for hffs def __init__( self : Optional[Any] ,_a : Optional[DatasetInfo] = None ,_a : Optional[str] = None ,**_a : str ,): '''simple docstring''' super().__init__(self ,**_a ) _a : Dict = repo_info _a : Tuple = token _a : Any = None def __lowercase ( self : Optional[Any] ): '''simple docstring''' if self.dir_cache is None: _a : int = {} for hf_file in self.repo_info.siblings: # TODO(QL): add sizes _a : str = { 'name': hf_file.rfilename, 'size': None, 'type': 'file', } self.dir_cache.update( { str(_a ): {'name': str(_a ), 'size': None, 'type': 'directory'} for d in list(PurePosixPath(hf_file.rfilename ).parents )[:-1] } ) def __lowercase ( self : int ,_a : str ,_a : str = "rb" ,**_a : Optional[int] ,): '''simple docstring''' if not isinstance(self.repo_info ,_a ): raise NotImplementedError(F"""Open is only implemented for dataset repositories, but got {self.repo_info}""" ) _a : Dict = hf_hub_url(self.repo_info.id ,_a ,revision=self.repo_info.sha ) return fsspec.open( _a ,mode=_a ,headers=get_authentication_headers_for_url(_a ,use_auth_token=self.token ) ,client_kwargs={'trust_env': True} ,).open() def __lowercase ( self : Optional[Any] ,_a : int ,**_a : Optional[Any] ): '''simple docstring''' self._get_dirs() _a : Any = self._strip_protocol(_a ) if path in self.dir_cache: return self.dir_cache[path] else: raise FileNotFoundError(_a ) def __lowercase ( self : Dict ,_a : int ,_a : Optional[Any]=False ,**_a : Any ): '''simple docstring''' self._get_dirs() _a : List[str] = PurePosixPath(path.strip('/' ) ) _a : Dict = {} for p, f in self.dir_cache.items(): _a : int = PurePosixPath(p.strip('/' ) ) _a : Union[str, Any] = p.parent if root == path: _a : str = f _a : str = list(paths.values() ) if detail: return out else: return sorted(f['name'] for f in out )
271
'''simple docstring''' from __future__ import annotations __lowerCAmelCase = [-1_0, -5, 0, 5, 5.1, 1_1, 1_3, 2_1, 3, 4, -2_1, -1_0, -5, -1, 0] __lowerCAmelCase = [-5, 0, 5, 5.1, 1_1, 1_3, 2_1, -1, 4, -1, -1_0, -5, -1, 0, -1] def UpperCAmelCase_ (__a : list[float] ): """simple docstring""" _a : Optional[int] = [] _a : int = len(__a ) for i in range(__a ): _a : float = -1 for j in range(i + 1 , __a ): if arr[i] < arr[j]: _a : Any = arr[j] break result.append(__a ) return result def UpperCAmelCase_ (__a : list[float] ): """simple docstring""" _a : Tuple = [] for i, outer in enumerate(__a ): _a : float = -1 for inner in arr[i + 1 :]: if outer < inner: _a : Dict = inner break result.append(__a ) return result def UpperCAmelCase_ (__a : list[float] ): """simple docstring""" _a : int = len(__a ) _a : list[float] = [] _a : list[float] = [-1] * arr_size for index in reversed(range(__a ) ): if stack: while stack[-1] <= arr[index]: stack.pop() if not stack: break if stack: _a : Dict = stack[-1] stack.append(arr[index] ) return result if __name__ == "__main__": from doctest import testmod from timeit import timeit testmod() print(next_greatest_element_slow(arr)) print(next_greatest_element_fast(arr)) print(next_greatest_element(arr)) __lowerCAmelCase = ( """from __main__ import arr, next_greatest_element_slow, """ """next_greatest_element_fast, next_greatest_element""" ) print( """next_greatest_element_slow():""", timeit("""next_greatest_element_slow(arr)""", setup=setup), ) print( """next_greatest_element_fast():""", timeit("""next_greatest_element_fast(arr)""", setup=setup), ) print( """ next_greatest_element():""", timeit("""next_greatest_element(arr)""", setup=setup), )
271
1
'''simple docstring''' import inspect import os import unittest from pathlib import Path import torch import accelerate from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils.testing import run_command class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Optional[Any] = inspect.getfile(accelerate.test_utils ) __UpperCAmelCase : List[str] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_cli.py'''] ) __UpperCAmelCase : Dict = ['''accelerate''', '''launch'''] __UpperCAmelCase : Dict = Path.home() / '''.cache/huggingface/accelerate''' __UpperCAmelCase : Dict = '''default_config.yaml''' __UpperCAmelCase : Optional[Any] = config_folder / config_file __UpperCAmelCase : Dict = config_folder / '''_default_config.yaml''' __UpperCAmelCase : Any = Path('''tests/test_configs''' ) @classmethod def __lowercase ( cls : int ): '''simple docstring''' if cls.config_path.is_file(): cls.config_path.rename(cls.changed_path ) @classmethod def __lowercase ( cls : List[Any] ): '''simple docstring''' if cls.changed_path.is_file(): cls.changed_path.rename(cls.config_path ) def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : Dict = self.base_cmd if torch.cuda.is_available() and (torch.cuda.device_count() > 1): cmd += ["--multi_gpu"] execute_subprocess_async(cmd + [self.test_file_path] ,env=os.environ.copy() ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' for config in sorted(self.test_config_path.glob('**/*.yaml' ) ): with self.subTest(config_file=_a ): execute_subprocess_async( self.base_cmd + ['--config_file', str(_a ), self.test_file_path] ,env=os.environ.copy() ) def __lowercase ( self : Optional[int] ): '''simple docstring''' execute_subprocess_async(['accelerate', 'test'] ,env=os.environ.copy() ) class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Optional[Any] = '''test-tpu''' __UpperCAmelCase : Any = '''us-central1-a''' __UpperCAmelCase : List[Any] = '''ls''' __UpperCAmelCase : Any = ['''accelerate''', '''tpu-config'''] __UpperCAmelCase : Dict = '''cd /usr/share''' __UpperCAmelCase : Any = '''tests/test_samples/test_command_file.sh''' __UpperCAmelCase : List[Any] = '''Running gcloud compute tpus tpu-vm ssh''' def __lowercase ( self : Dict ): '''simple docstring''' _a : Optional[Any] = run_command( self.cmd + ['--command', self.command, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug'] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" ,_a ,) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Any = run_command( self.cmd + [ '--config_file', 'tests/test_configs/0_12_0.yaml', '--command', self.command, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug', ] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" ,_a ,) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Optional[int] = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--debug'] ,return_stdout=_a ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_a ,) def __lowercase ( self : int ): '''simple docstring''' _a : Optional[Any] = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--command', self.command, '--debug'] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" ,_a ,) def __lowercase ( self : str ): '''simple docstring''' _a : List[str] = run_command( self.cmd + [ '--config_file', 'tests/test_configs/latest.yaml', '--command', self.command, '--command', 'echo "Hello World"', '--debug', ] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo \"Hello World\" --worker all""" ,_a ,) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : Any = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--command_file', self.command_file, '--debug'] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_a ,) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : Union[str, Any] = run_command( self.cmd + [ '--config_file', 'tests/test_configs/0_12_0.yaml', '--command_file', self.command_file, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug', ] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_a ,) def __lowercase ( self : Any ): '''simple docstring''' _a : Optional[int] = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--install_accelerate', '--debug'] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_a ,) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Optional[int] = run_command( self.cmd + [ '--config_file', 'tests/test_configs/latest.yaml', '--install_accelerate', '--accelerate_version', '12.0.0', '--debug', ] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_a ,)
271
'''simple docstring''' import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home __lowerCAmelCase = HUGGINGFACE_HUB_CACHE __lowerCAmelCase = """config.json""" __lowerCAmelCase = """diffusion_pytorch_model.bin""" __lowerCAmelCase = """diffusion_flax_model.msgpack""" __lowerCAmelCase = """model.onnx""" __lowerCAmelCase = """diffusion_pytorch_model.safetensors""" __lowerCAmelCase = """weights.pb""" __lowerCAmelCase = """https://huggingface.co""" __lowerCAmelCase = default_cache_path __lowerCAmelCase = """diffusers_modules""" __lowerCAmelCase = os.getenv("""HF_MODULES_CACHE""", os.path.join(hf_cache_home, """modules""")) __lowerCAmelCase = ["""fp16""", """non-ema"""] __lowerCAmelCase = """.self_attn"""
271
1
'''simple docstring''' import sys from typing import Tuple import numpy as np import torch from PIL import Image from torch import nn from transformers.image_utils import PILImageResampling from utils import img_tensorize class UpperCAmelCase__ : """simple docstring""" def __init__( self : Any ,_a : List[Any] ,_a : List[str]=sys.maxsize ): '''simple docstring''' _a : List[str] = 'bilinear' _a : List[Any] = max_size _a : Dict = short_edge_length def __call__( self : int ,_a : List[Any] ): '''simple docstring''' _a : List[str] = [] for img in imgs: _a, _a : Union[str, Any] = img.shape[:2] # later: provide list and randomly choose index for resize _a : Optional[int] = np.random.randint(self.short_edge_length[0] ,self.short_edge_length[1] + 1 ) if size == 0: return img _a : Any = size * 1.0 / min(_a ,_a ) if h < w: _a, _a : Optional[Any] = size, scale * w else: _a, _a : Union[str, Any] = scale * h, size if max(_a ,_a ) > self.max_size: _a : Any = self.max_size * 1.0 / max(_a ,_a ) _a : Any = newh * scale _a : Dict = neww * scale _a : str = int(neww + 0.5 ) _a : Optional[Any] = int(newh + 0.5 ) if img.dtype == np.uinta: _a : Any = Image.fromarray(_a ) _a : List[Any] = pil_image.resize((neww, newh) ,PILImageResampling.BILINEAR ) _a : Tuple = np.asarray(_a ) else: _a : Dict = img.permute(2 ,0 ,1 ).unsqueeze(0 ) # 3, 0, 1) # hw(c) -> nchw _a : Any = nn.functional.interpolate( _a ,(newh, neww) ,mode=self.interp_method ,align_corners=_a ).squeeze(0 ) img_augs.append(_a ) return img_augs class UpperCAmelCase__ : """simple docstring""" def __init__( self : str ,_a : Union[str, Any] ): '''simple docstring''' _a : Dict = ResizeShortestEdge([cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST] ,cfg.INPUT.MAX_SIZE_TEST ) _a : Any = cfg.INPUT.FORMAT _a : List[Any] = cfg.SIZE_DIVISIBILITY _a : str = cfg.PAD_VALUE _a : List[str] = cfg.INPUT.MAX_SIZE_TEST _a : Union[str, Any] = cfg.MODEL.DEVICE _a : Optional[Any] = torch.tensor(cfg.MODEL.PIXEL_STD ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) ,1 ,1 ) _a : Optional[int] = torch.tensor(cfg.MODEL.PIXEL_MEAN ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) ,1 ,1 ) _a : Optional[Any] = lambda _a : (x - self.pixel_mean) / self.pixel_std def __lowercase ( self : int ,_a : Optional[Any] ): '''simple docstring''' _a : List[Any] = tuple(max(_a ) for s in zip(*[img.shape for img in images] ) ) _a : List[Any] = [im.shape[-2:] for im in images] _a : Dict = [ nn.functional.pad( _a ,[0, max_size[-1] - size[1], 0, max_size[-2] - size[0]] ,value=self.pad_value ,) for size, im in zip(_a ,_a ) ] return torch.stack(_a ), torch.tensor(_a ) def __call__( self : List[Any] ,_a : Union[str, Any] ,_a : Union[str, Any]=False ): '''simple docstring''' with torch.no_grad(): if not isinstance(_a ,_a ): _a : Optional[Any] = [images] if single_image: assert len(_a ) == 1 for i in range(len(_a ) ): if isinstance(images[i] ,torch.Tensor ): images.insert(_a ,images.pop(_a ).to(self.device ).float() ) elif not isinstance(images[i] ,torch.Tensor ): images.insert( _a ,torch.as_tensor(img_tensorize(images.pop(_a ) ,input_format=self.input_format ) ) .to(self.device ) .float() ,) # resize smallest edge _a : List[Any] = torch.tensor([im.shape[:2] for im in images] ) _a : Any = self.aug(_a ) # transpose images and convert to torch tensors # images = [torch.as_tensor(i.astype("float32")).permute(2, 0, 1).to(self.device) for i in images] # now normalize before pad to avoid useless arithmetic _a : Any = [self.normalizer(_a ) for x in images] # now pad them to do the following operations _a, _a : Any = self.pad(_a ) # Normalize if self.size_divisibility > 0: raise NotImplementedError() # pad _a : List[str] = torch.true_divide(_a ,_a ) if single_image: return images[0], sizes[0], scales_yx[0] else: return images, sizes, scales_yx def UpperCAmelCase_ (__a : Tuple , __a : List[Any] ): """simple docstring""" boxes[:, 0::2] *= scale_yx[:, 1] boxes[:, 1::2] *= scale_yx[:, 0] return boxes def UpperCAmelCase_ (__a : Any , __a : Tuple[int, int] ): """simple docstring""" assert torch.isfinite(__a ).all(), "Box tensor contains infinite or NaN!" _a, _a : List[str] = box_size tensor[:, 0].clamp_(min=0 , max=__a ) tensor[:, 1].clamp_(min=0 , max=__a ) tensor[:, 2].clamp_(min=0 , max=__a ) tensor[:, 3].clamp_(min=0 , max=__a )
271
'''simple docstring''' import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class UpperCAmelCase__ : """simple docstring""" def __init__( self : int ,_a : Any ,_a : Optional[int]=2 ,_a : Optional[Any]=True ,_a : Dict=False ,_a : Dict=10 ,_a : Any=3 ,_a : str=32 * 8 ,_a : Optional[int]=32 * 8 ,_a : int=4 ,_a : str=64 ,): '''simple docstring''' _a : Dict = parent _a : Union[str, Any] = batch_size _a : Tuple = is_training _a : List[str] = use_auxiliary_loss _a : Optional[Any] = num_queries _a : str = num_channels _a : List[str] = min_size _a : int = max_size _a : Optional[int] = num_labels _a : List[str] = hidden_dim _a : int = hidden_dim def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : Tuple = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( _a ) _a : Optional[Any] = torch.ones([self.batch_size, self.min_size, self.max_size] ,device=_a ) _a : Union[str, Any] = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] ,device=_a ) > 0.5 ).float() _a : Tuple = (torch.rand((self.batch_size, self.num_labels) ,device=_a ) > 0.5).long() _a : Dict = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : int = MaskaFormerConfig( hidden_size=self.hidden_dim ,) _a : str = self.num_queries _a : Union[str, Any] = self.num_labels _a : Tuple = [1, 1, 1, 1] _a : Dict = self.num_channels _a : str = 64 _a : Tuple = 128 _a : Optional[Any] = self.hidden_dim _a : Union[str, Any] = self.hidden_dim _a : List[Any] = self.hidden_dim return config def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a, _a, _a, _a, _a : Optional[Any] = self.prepare_config_and_inputs() _a : str = {'pixel_values': pixel_values, 'pixel_mask': pixel_mask} return config, inputs_dict def __lowercase ( self : List[str] ,_a : Optional[Any] ,_a : str ): '''simple docstring''' _a : str = output.encoder_hidden_states _a : Any = output.pixel_decoder_hidden_states _a : Optional[Any] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(_a ) ,len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_a ) ,len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_a ) ,config.decoder_layers ) def __lowercase ( self : List[str] ,_a : str ,_a : List[Any] ,_a : Any ,_a : Union[str, Any]=False ): '''simple docstring''' with torch.no_grad(): _a : str = MaskaFormerModel(config=_a ) model.to(_a ) model.eval() _a : Any = model(pixel_values=_a ,pixel_mask=_a ) _a : Optional[Any] = model(_a ,output_hidden_states=_a ) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape ,(self.batch_size, self.num_queries, self.hidden_dim) ,) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(_a ,_a ) def __lowercase ( self : Tuple ,_a : List[Any] ,_a : Union[str, Any] ,_a : Tuple ,_a : List[str] ,_a : Any ): '''simple docstring''' _a : int = MaskaFormerForUniversalSegmentation(config=_a ) model.to(_a ) model.eval() def comm_check_on_output(_a : Any ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape ,(self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) ,) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape ,(self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): _a : Any = model(pixel_values=_a ,pixel_mask=_a ) _a : Optional[int] = model(_a ) comm_check_on_output(_a ) _a : List[str] = model( pixel_values=_a ,pixel_mask=_a ,mask_labels=_a ,class_labels=_a ) comm_check_on_output(_a ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape ,torch.Size([1] ) ) @require_torch class UpperCAmelCase__ ( lowercase__ , lowercase__ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Optional[int] = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () __UpperCAmelCase : Dict = {'''feature-extraction''': MaskaFormerModel} if is_torch_available() else {} __UpperCAmelCase : Dict = False __UpperCAmelCase : Tuple = False __UpperCAmelCase : Dict = False __UpperCAmelCase : List[Any] = False def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : Union[str, Any] = MaskaFormerModelTester(self ) _a : Dict = ConfigTester(self ,config_class=_a ,has_text_modality=_a ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' self.config_tester.run_common_tests() def __lowercase ( self : Optional[int] ): '''simple docstring''' _a, _a : List[str] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(_a ,**_a ,output_hidden_states=_a ) def __lowercase ( self : str ): '''simple docstring''' _a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*_a ) @unittest.skip(reason='Mask2Former does not use inputs_embeds' ) def __lowercase ( self : Any ): '''simple docstring''' pass @unittest.skip(reason='Mask2Former does not have a get_input_embeddings method' ) def __lowercase ( self : str ): '''simple docstring''' pass @unittest.skip(reason='Mask2Former is not a generative model' ) def __lowercase ( self : List[Any] ): '''simple docstring''' pass @unittest.skip(reason='Mask2Former does not use token embeddings' ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' pass @require_torch_multi_gpu @unittest.skip( reason='Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def __lowercase ( self : Dict ): '''simple docstring''' pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def __lowercase ( self : List[Any] ): '''simple docstring''' pass def __lowercase ( self : int ): '''simple docstring''' _a, _a : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : Union[str, Any] = model_class(_a ) _a : List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _a : Optional[Any] = [*signature.parameters.keys()] _a : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] ,_a ) @slow def __lowercase ( self : List[str] ): '''simple docstring''' for model_name in ["facebook/mask2former-swin-small-coco-instance"]: _a : Dict = MaskaFormerModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def __lowercase ( self : List[Any] ): '''simple docstring''' _a : int = (self.model_tester.min_size,) * 2 _a : Any = { 'pixel_values': torch.randn((2, 3, *size) ,device=_a ), 'mask_labels': torch.randn((2, 10, *size) ,device=_a ), 'class_labels': torch.zeros(2 ,10 ,device=_a ).long(), } _a : List[Any] = self.model_tester.get_config() _a : int = MaskaFormerForUniversalSegmentation(_a ).to(_a ) _a : str = model(**_a ) self.assertTrue(outputs.loss is not None ) def __lowercase ( self : List[str] ): '''simple docstring''' _a, _a : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(_a ,**_a ,output_hidden_states=_a ) def __lowercase ( self : int ): '''simple docstring''' _a, _a : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : Any = model_class(_a ).to(_a ) _a : Optional[int] = model(**_a ,output_attentions=_a ) self.assertTrue(outputs.attentions is not None ) def __lowercase ( self : Tuple ): '''simple docstring''' if not self.model_tester.is_training: return _a : List[str] = self.all_model_classes[1] _a, _a, _a, _a, _a : List[str] = self.model_tester.prepare_config_and_inputs() _a : Any = model_class(_a ) model.to(_a ) model.train() _a : Union[str, Any] = model(_a ,mask_labels=_a ,class_labels=_a ).loss loss.backward() def __lowercase ( self : int ): '''simple docstring''' _a : int = self.all_model_classes[1] _a, _a, _a, _a, _a : List[Any] = self.model_tester.prepare_config_and_inputs() _a : str = True _a : str = True _a : List[str] = model_class(_a ).to(_a ) model.train() _a : Optional[int] = model(_a ,mask_labels=_a ,class_labels=_a ) _a : Tuple = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() _a : str = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() _a : Dict = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() _a : List[str] = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=_a ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) __lowerCAmelCase = 1e-4 def UpperCAmelCase_ (): """simple docstring""" _a : int = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_vision @slow class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" @cached_property def __lowercase ( self : Union[str, Any] ): '''simple docstring''' return "facebook/mask2former-swin-small-coco-instance" @cached_property def __lowercase ( self : Any ): '''simple docstring''' return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None def __lowercase ( self : Any ): '''simple docstring''' _a : List[str] = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(_a ) _a : int = self.default_image_processor _a : Tuple = prepare_img() _a : Any = image_processor(_a ,return_tensors='pt' ).to(_a ) _a : Union[str, Any] = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(_a ,(1, 3, 384, 384) ) with torch.no_grad(): _a : Optional[Any] = model(**_a ) _a : List[Any] = torch.tensor( [[-0.2790, -1.0717, -1.1668], [-0.5128, -0.3128, -0.4987], [-0.5832, 0.1971, -0.0197]] ).to(_a ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] ,_a ,atol=_a ) ) _a : str = torch.tensor( [[0.8973, 1.1847, 1.1776], [1.1934, 1.5040, 1.5128], [1.1153, 1.4486, 1.4951]] ).to(_a ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] ,_a ,atol=_a ) ) _a : Any = torch.tensor( [[2.1152, 1.7000, -0.8603], [1.5808, 1.8004, -0.9353], [1.6043, 1.7495, -0.5999]] ).to(_a ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] ,_a ,atol=_a ) ) def __lowercase ( self : Tuple ): '''simple docstring''' _a : List[Any] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(_a ).eval() _a : Optional[Any] = self.default_image_processor _a : List[Any] = prepare_img() _a : str = image_processor(_a ,return_tensors='pt' ).to(_a ) _a : Any = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(_a ,(1, 3, 384, 384) ) with torch.no_grad(): _a : Optional[int] = model(**_a ) # masks_queries_logits _a : Dict = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape ,(1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ) _a : Dict = [ [-8.7839, -9.0056, -8.8121], [-7.4104, -7.0313, -6.5401], [-6.6105, -6.3427, -6.4675], ] _a : Optional[Any] = torch.tensor(_a ).to(_a ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] ,_a ,atol=_a ) ) # class_queries_logits _a : str = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape ,(1, model.config.num_queries, model.config.num_labels + 1) ) _a : str = torch.tensor( [ [1.8324, -8.0835, -4.1922], [0.8450, -9.0050, -3.6053], [0.3045, -7.7293, -3.0275], ] ).to(_a ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] ,_a ,atol=_a ) ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a : Any = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(_a ).eval() _a : Tuple = self.default_image_processor _a : Tuple = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] ,segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] ,return_tensors='pt' ,) _a : str = inputs['pixel_values'].to(_a ) _a : str = [el.to(_a ) for el in inputs['mask_labels']] _a : Dict = [el.to(_a ) for el in inputs['class_labels']] with torch.no_grad(): _a : List[str] = model(**_a ) self.assertTrue(outputs.loss is not None )
271
1
'''simple docstring''' import json import os from datetime import date from pathlib import Path from tabulate import DataRow, TableFormat, tabulate __lowerCAmelCase = TableFormat( lineabove=None, linebelowheader=None, linebetweenrows=None, linebelow=None, headerrow=DataRow("""""", """|""", """|"""), datarow=DataRow("""""", """|""", """|"""), padding=1, with_header_hide=None, ) __lowerCAmelCase = [] __lowerCAmelCase = [] __lowerCAmelCase = {"""type""": """section""", """text""": {"""type""": """plain_text""", """text""": """No failed tests! 🤗""", """emoji""": True}} __lowerCAmelCase = [ { """type""": """header""", """text""": { """type""": """plain_text""", """text""": f'''🤗 Accelerate nightly {os.environ.get('TEST_TYPE', '')} test results''', """emoji""": True, }, } ] __lowerCAmelCase = 0 for log in Path().glob("""*.log"""): __lowerCAmelCase = 0 with open(log, """r""") as f: for line in f: __lowerCAmelCase = json.loads(line) if line.get("""nodeid""", """""") != "": __lowerCAmelCase = line["""nodeid"""] if line.get("""duration""", None) is not None: __lowerCAmelCase = f'''{line['duration']:.4f}''' if line.get("""outcome""", """""") == "failed": section_num_failed += 1 failed.append([test, duration, log.name.split("""_""")[0]]) total_num_failed += 1 group_info.append([str(log), section_num_failed, failed]) __lowerCAmelCase = [] log.unlink() __lowerCAmelCase = """""" __lowerCAmelCase = [] if total_num_failed > 0: for name, num_failed, failed_tests in group_info: if num_failed > 0: if num_failed == 1: message += f"*{name[1:]}: {num_failed} failed test*\n" else: message += f"*{name[1:]}: {num_failed} failed tests*\n" __lowerCAmelCase = [] __lowerCAmelCase = {} for test in failed_tests: __lowerCAmelCase = test[0].split("""::""") __lowerCAmelCase = data[0].split("""/""")[-1] if data[0] not in filesafailed: __lowerCAmelCase = [data[1:]] else: filesafailed[data[0]] += [data[1:]] failed_table.append(data) __lowerCAmelCase = [test[0] for test in failed_table] __lowerCAmelCase = list(set(files)) # Count number of instances in failed_tests __lowerCAmelCase = [] for file in individual_files: table.append([file, len(filesafailed[file])]) __lowerCAmelCase = tabulate( table, headers=["""Test Location""", """Num Failed"""], tablefmt=hf_table_format, stralign="""right""", ) message += f"\n```\n{failed_table}\n```" all_filesafailed.append(filesafailed) if len(message) > 3_0_0_0: __lowerCAmelCase = """Too many failed tests, please see the full report in the Action results.""" __lowerCAmelCase = len(err) + 1_0 __lowerCAmelCase = message[: 3_0_0_0 - offset] + f'''\n...\n```\n{err}''' print(f'''### {message}''') else: __lowerCAmelCase = """No failed tests! 🤗""" print(f'''## {message}''') payload.append(no_error_payload) if os.environ.get("""TEST_TYPE""", """""") != "": from slack_sdk import WebClient __lowerCAmelCase = WebClient(token=os.environ["""SLACK_API_TOKEN"""]) if message != "No failed tests! 🤗": __lowerCAmelCase = { """type""": """section""", """text""": { """type""": """mrkdwn""", """text""": message, }, } payload.append(md_report) __lowerCAmelCase = { """type""": """section""", """text""": { """type""": """mrkdwn""", """text""": """*For more details:*""", }, """accessory""": { """type""": """button""", """text""": { """type""": """plain_text""", """text""": """Check Action results""", """emoji""": True, }, """url""": f'''https://github.com/{os.environ['GITHUB_REPOSITORY']}/actions/runs/{os.environ['GITHUB_RUN_ID']}''', }, } payload.append(action_button) __lowerCAmelCase = { """type""": """context""", """elements""": [ { """type""": """plain_text""", """text""": f'''Nightly {os.environ.get('TEST_TYPE')} test results for {date.today()}''', } ], } payload.append(date_report) __lowerCAmelCase = client.chat_postMessage(channel="""#accelerate-ci-daily""", text=message, blocks=payload) __lowerCAmelCase = response.data["""ts"""] for failed_file in all_filesafailed: for test_location, test_failures in failed_file.items(): # Keep only the first instance of the test name __lowerCAmelCase = """""" for i, row in enumerate(test_failures): if row[0] != test_class: __lowerCAmelCase = row[0] else: __lowerCAmelCase = """""" __lowerCAmelCase = { """type""": """section""", """text""": { """type""": """mrkdwn""", """text""": f'''Test location: {test_location}\n```\n{tabulate(test_failures, headers=['Class', 'Test'], tablefmt=hf_table_format, stralign='right')}\n```''', }, } client.chat_postMessage( channel="""#accelerate-ci-daily""", thread_ts=ts, blocks=[payload], )
271
'''simple docstring''' import argparse import json from typing import List from ltp import LTP from transformers import BertTokenizer def UpperCAmelCase_ (__a : List[Any] ): """simple docstring""" if ( (cp >= 0x4E_00 and cp <= 0x9F_FF) or (cp >= 0x34_00 and cp <= 0x4D_BF) # or (cp >= 0x2_00_00 and cp <= 0x2_A6_DF) # or (cp >= 0x2_A7_00 and cp <= 0x2_B7_3F) # or (cp >= 0x2_B7_40 and cp <= 0x2_B8_1F) # or (cp >= 0x2_B8_20 and cp <= 0x2_CE_AF) # or (cp >= 0xF9_00 and cp <= 0xFA_FF) or (cp >= 0x2_F8_00 and cp <= 0x2_FA_1F) # ): # return True return False def UpperCAmelCase_ (__a : str ): """simple docstring""" for char in word: _a : Union[str, Any] = ord(__a ) if not _is_chinese_char(__a ): return 0 return 1 def UpperCAmelCase_ (__a : List[str] ): """simple docstring""" _a : Dict = set() for token in tokens: _a : str = len(__a ) > 1 and is_chinese(__a ) if chinese_word: word_set.add(__a ) _a : Optional[Any] = list(__a ) return word_list def UpperCAmelCase_ (__a : List[str] , __a : set() ): """simple docstring""" if not chinese_word_set: return bert_tokens _a : Optional[Any] = max([len(__a ) for w in chinese_word_set] ) _a : Optional[int] = bert_tokens _a, _a : Any = 0, len(__a ) while start < end: _a : Tuple = True if is_chinese(bert_word[start] ): _a : Union[str, Any] = min(end - start , __a ) for i in range(__a , 1 , -1 ): _a : Optional[Any] = ''.join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1 , start + i ): _a : Any = '##' + bert_word[j] _a : Union[str, Any] = start + i _a : int = False break if single_word: start += 1 return bert_word def UpperCAmelCase_ (__a : List[str] , __a : LTP , __a : BertTokenizer ): """simple docstring""" _a : int = [] for i in range(0 , len(__a ) , 1_0_0 ): _a : Union[str, Any] = ltp_tokenizer.seg(lines[i : i + 1_0_0] )[0] _a : Optional[Any] = [get_chinese_word(__a ) for r in res] ltp_res.extend(__a ) assert len(__a ) == len(__a ) _a : str = [] for i in range(0 , len(__a ) , 1_0_0 ): _a : List[str] = bert_tokenizer(lines[i : i + 1_0_0] , add_special_tokens=__a , truncation=__a , max_length=5_1_2 ) bert_res.extend(res['input_ids'] ) assert len(__a ) == len(__a ) _a : List[str] = [] for input_ids, chinese_word in zip(__a , __a ): _a : int = [] for id in input_ids: _a : Optional[int] = bert_tokenizer._convert_id_to_token(__a ) input_tokens.append(__a ) _a : List[str] = add_sub_symbol(__a , __a ) _a : Tuple = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(__a ): if token[:2] == "##": _a : str = token[2:] # save chinese tokens' pos if len(__a ) == 1 and _is_chinese_char(ord(__a ) ): ref_id.append(__a ) ref_ids.append(__a ) assert len(__a ) == len(__a ) return ref_ids def UpperCAmelCase_ (__a : Optional[Any] ): """simple docstring""" with open(args.file_name , 'r' , encoding='utf-8' ) as f: _a : Dict = f.readlines() _a : int = [line.strip() for line in data if len(__a ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' _a : int = LTP(args.ltp ) # faster in GPU device _a : Tuple = BertTokenizer.from_pretrained(args.bert ) _a : int = prepare_ref(__a , __a , __a ) with open(args.save_path , 'w' , encoding='utf-8' ) as f: _a : Optional[Any] = [json.dumps(__a ) + '\n' for ref in ref_ids] f.writelines(__a ) if __name__ == "__main__": __lowerCAmelCase = argparse.ArgumentParser(description="""prepare_chinese_ref""") parser.add_argument( """--file_name""", type=str, default="""./resources/chinese-demo.txt""", help="""file need process, same as training data in lm""", ) parser.add_argument( """--ltp""", type=str, default="""./resources/ltp""", help="""resources for LTP tokenizer, usually a path""" ) parser.add_argument("""--bert""", type=str, default="""./resources/robert""", help="""resources for Bert tokenizer""") parser.add_argument("""--save_path""", type=str, default="""./resources/ref.txt""", help="""path to save res""") __lowerCAmelCase = parser.parse_args() main(args)
271
1
'''simple docstring''' import torch from diffusers import UnCLIPScheduler from .test_schedulers import SchedulerCommonTest class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : List[Any] = (UnCLIPScheduler,) def __lowercase ( self : Any ,**_a : str ): '''simple docstring''' _a : Dict = { 'num_train_timesteps': 1000, 'variance_type': 'fixed_small_log', 'clip_sample': True, 'clip_sample_range': 1.0, 'prediction_type': 'epsilon', } config.update(**_a ) return config def __lowercase ( self : str ): '''simple docstring''' for timesteps in [1, 5, 100, 1000]: self.check_over_configs(num_train_timesteps=_a ) def __lowercase ( self : List[Any] ): '''simple docstring''' for variance in ["fixed_small_log", "learned_range"]: self.check_over_configs(variance_type=_a ) def __lowercase ( self : List[str] ): '''simple docstring''' for clip_sample in [True, False]: self.check_over_configs(clip_sample=_a ) def __lowercase ( self : int ): '''simple docstring''' for clip_sample_range in [1, 5, 10, 20]: self.check_over_configs(clip_sample_range=_a ) def __lowercase ( self : List[str] ): '''simple docstring''' for prediction_type in ["epsilon", "sample"]: self.check_over_configs(prediction_type=_a ) def __lowercase ( self : List[Any] ): '''simple docstring''' for time_step in [0, 500, 999]: for prev_timestep in [None, 5, 100, 250, 500, 750]: if prev_timestep is not None and prev_timestep >= time_step: continue self.check_over_forward(time_step=_a ,prev_timestep=_a ) def __lowercase ( self : int ): '''simple docstring''' _a : Optional[Any] = self.scheduler_classes[0] _a : str = self.get_scheduler_config(variance_type='fixed_small_log' ) _a : Union[str, Any] = scheduler_class(**_a ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 1.0000E-10 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.054_9625 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.999_4987 ) ) < 1E-5 def __lowercase ( self : Any ): '''simple docstring''' _a : int = self.scheduler_classes[0] _a : str = self.get_scheduler_config(variance_type='learned_range' ) _a : str = scheduler_class(**_a ) _a : Any = 0.5 assert scheduler._get_variance(1 ,predicted_variance=_a ) - -10.171_2790 < 1E-5 assert scheduler._get_variance(487 ,predicted_variance=_a ) - -5.799_8052 < 1E-5 assert scheduler._get_variance(999 ,predicted_variance=_a ) - -0.001_0011 < 1E-5 def __lowercase ( self : List[Any] ): '''simple docstring''' _a : Optional[Any] = self.scheduler_classes[0] _a : Dict = self.get_scheduler_config() _a : int = scheduler_class(**_a ) _a : List[str] = scheduler.timesteps _a : int = self.dummy_model() _a : Any = self.dummy_sample_deter _a : Dict = torch.manual_seed(0 ) for i, t in enumerate(_a ): # 1. predict noise residual _a : List[str] = model(_a ,_a ) # 2. predict previous mean of sample x_t-1 _a : Any = scheduler.step(_a ,_a ,_a ,generator=_a ).prev_sample _a : List[str] = pred_prev_sample _a : Tuple = torch.sum(torch.abs(_a ) ) _a : List[Any] = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 252.268_2495 ) < 1E-2 assert abs(result_mean.item() - 0.328_4743 ) < 1E-3 def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a : Union[str, Any] = self.scheduler_classes[0] _a : List[Any] = self.get_scheduler_config() _a : Optional[int] = scheduler_class(**_a ) scheduler.set_timesteps(25 ) _a : List[str] = scheduler.timesteps _a : List[str] = self.dummy_model() _a : List[str] = self.dummy_sample_deter _a : str = torch.manual_seed(0 ) for i, t in enumerate(_a ): # 1. predict noise residual _a : List[str] = model(_a ,_a ) if i + 1 == timesteps.shape[0]: _a : Optional[int] = None else: _a : List[str] = timesteps[i + 1] # 2. predict previous mean of sample x_t-1 _a : List[Any] = scheduler.step( _a ,_a ,_a ,prev_timestep=_a ,generator=_a ).prev_sample _a : Dict = pred_prev_sample _a : Any = torch.sum(torch.abs(_a ) ) _a : List[Any] = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 258.204_4983 ) < 1E-2 assert abs(result_mean.item() - 0.336_2038 ) < 1E-3 def __lowercase ( self : Any ): '''simple docstring''' pass def __lowercase ( self : Tuple ): '''simple docstring''' pass
271
'''simple docstring''' import warnings from ...utils import logging from .image_processing_videomae import VideoMAEImageProcessor __lowerCAmelCase = logging.get_logger(__name__) class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" def __init__( self : Tuple ,*_a : List[str] ,**_a : Any ): '''simple docstring''' warnings.warn( 'The class VideoMAEFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use VideoMAEImageProcessor instead.' ,_a ,) super().__init__(*_a ,**_a )
271
1
'''simple docstring''' from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.utils.data import DistributedSampler, RandomSampler from transformers import PreTrainedModel, Trainer, logging from transformers.integrations import is_fairscale_available from transformers.models.fsmt.configuration_fsmt import FSMTConfig from transformers.optimization 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_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.trainer_pt_utils import get_tpu_sampler from transformers.training_args import ParallelMode from transformers.utils import is_torch_tpu_available if is_fairscale_available(): from fairscale.optim import OSS __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = { """linear""": get_linear_schedule_with_warmup, """cosine""": get_cosine_schedule_with_warmup, """cosine_w_restarts""": get_cosine_with_hard_restarts_schedule_with_warmup, """polynomial""": get_polynomial_decay_schedule_with_warmup, """constant""": get_constant_schedule, """constant_w_warmup""": get_constant_schedule_with_warmup, } class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" def __init__( self : Optional[int] ,_a : Optional[Any]=None ,_a : Dict=None ,*_a : int ,**_a : str ): '''simple docstring''' super().__init__(*_a ,**_a ) if config is None: assert isinstance(self.model ,_a ), ( "If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is" F""" {self.model.__class__}""" ) _a : List[Any] = self.model.config else: _a : Optional[int] = config _a : List[str] = data_args _a : List[Any] = self.config.tgt_vocab_size if isinstance(self.config ,_a ) else self.config.vocab_size if self.args.label_smoothing != 0 or (self.data_args is not None and self.data_args.ignore_pad_token_for_loss): assert self.config.pad_token_id is not None, ( "Make sure that `config.pad_token_id` is correcly defined when ignoring `pad_token` for loss" " calculation or doing label smoothing." ) if self.config.pad_token_id is None and self.config.eos_token_id is not None: logger.warning( F"""The `config.pad_token_id` is `None`. Using `config.eos_token_id` = {self.config.eos_token_id} for""" ' padding..' ) if self.args.label_smoothing == 0: _a : List[str] = torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id ) else: # dynamically import label_smoothed_nll_loss from utils import label_smoothed_nll_loss _a : Tuple = label_smoothed_nll_loss def __lowercase ( self : List[str] ,_a : int ): '''simple docstring''' if self.optimizer is None: _a : Union[str, Any] = ['bias', 'LayerNorm.weight'] _a : Tuple = [ { 'params': [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay )], 'weight_decay': self.args.weight_decay, }, { 'params': [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay )], 'weight_decay': 0.0, }, ] _a : Optional[int] = Adafactor if self.args.adafactor else AdamW if self.args.adafactor: _a : Any = Adafactor _a : Dict = {'scale_parameter': False, 'relative_step': False} else: _a : Union[str, Any] = AdamW _a : str = { 'betas': (self.args.adam_betaa, self.args.adam_betaa), 'eps': self.args.adam_epsilon, } _a : Union[str, Any] = self.args.learning_rate if self.sharded_ddp: _a : str = OSS( params=_a ,optim=_a ,**_a ,) else: _a : Tuple = optimizer_cls(_a ,**_a ) if self.lr_scheduler is None: _a : List[Any] = self._get_lr_scheduler(_a ) else: # ignoring --lr_scheduler logger.warning('scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored.' ) def __lowercase ( self : List[Any] ,_a : List[Any] ): '''simple docstring''' _a : str = arg_to_scheduler[self.args.lr_scheduler] if self.args.lr_scheduler == "constant": _a : int = schedule_func(self.optimizer ) elif self.args.lr_scheduler == "constant_w_warmup": _a : List[str] = schedule_func(self.optimizer ,num_warmup_steps=self.args.warmup_steps ) else: _a : Optional[int] = schedule_func( self.optimizer ,num_warmup_steps=self.args.warmup_steps ,num_training_steps=_a ) return scheduler def __lowercase ( self : Tuple ): '''simple docstring''' if isinstance(self.train_dataset ,torch.utils.data.IterableDataset ): return None elif is_torch_tpu_available(): return get_tpu_sampler(self.train_dataset ) else: if self.args.sortish_sampler: self.train_dataset.make_sortish_sampler( self.args.per_device_train_batch_size ,distributed=(self.args.parallel_mode == ParallelMode.DISTRIBUTED) ,) return ( RandomSampler(self.train_dataset ) if self.args.local_rank == -1 else DistributedSampler(self.train_dataset ) ) def __lowercase ( self : Dict ,_a : Dict ,_a : Any ,_a : Dict ): '''simple docstring''' if self.args.label_smoothing == 0: if self.data_args is not None and self.data_args.ignore_pad_token_for_loss: # force training to ignore pad token _a : List[Any] = model(**_a ,use_cache=_a )[0] _a : Union[str, Any] = self.loss_fn(logits.view(-1 ,logits.shape[-1] ) ,labels.view(-1 ) ) else: # compute usual loss via models _a, _a : Union[str, Any] = model(**_a ,labels=_a ,use_cache=_a )[:2] else: # compute label smoothed loss _a : List[Any] = model(**_a ,use_cache=_a )[0] _a : Any = torch.nn.functional.log_softmax(_a ,dim=-1 ) _a, _a : List[str] = self.loss_fn(_a ,_a ,self.args.label_smoothing ,ignore_index=self.config.pad_token_id ) return loss, logits def __lowercase ( self : Optional[int] ,_a : Union[str, Any] ,_a : List[Any] ): '''simple docstring''' _a : Optional[int] = inputs.pop('labels' ) _a, _a : int = self._compute_loss(_a ,_a ,_a ) return loss def __lowercase ( self : Optional[Any] ,_a : nn.Module ,_a : Dict[str, Union[torch.Tensor, Any]] ,_a : bool ,_a : Optional[List[str]] = None ,): '''simple docstring''' _a : int = self._prepare_inputs(_a ) _a : Any = { 'max_length': self.data_args.val_max_target_length if self.data_args is not None else self.config.max_length, 'num_beams': self.data_args.eval_beams if self.data_args is not None else self.config.num_beams, } if self.args.predict_with_generate and not self.args.prediction_loss_only: _a : int = self.model.generate( inputs['input_ids'] ,attention_mask=inputs['attention_mask'] ,**_a ,) # in case the batch is shorter than max length, the output should be padded if generated_tokens.shape[-1] < gen_kwargs["max_length"]: _a : int = self._pad_tensors_to_max_len(_a ,gen_kwargs['max_length'] ) _a : Union[str, Any] = inputs.pop('labels' ) with torch.no_grad(): # compute loss on predict data _a, _a : Optional[int] = self._compute_loss(_a ,_a ,_a ) _a : Optional[Any] = loss.mean().detach() if self.args.prediction_loss_only: return (loss, None, None) _a : Optional[Any] = generated_tokens if self.args.predict_with_generate else logits if labels.shape[-1] < gen_kwargs["max_length"]: _a : Dict = self._pad_tensors_to_max_len(_a ,gen_kwargs['max_length'] ) return (loss, logits, labels) def __lowercase ( self : str ,_a : Tuple ,_a : Tuple ): '''simple docstring''' _a : List[Any] = self.config.pad_token_id if self.config.pad_token_id is not None else self.config.eos_token_id if pad_token_id is None: raise ValueError( 'Make sure that either `config.pad_token_id` or `config.eos_token_id` is defined if tensor has to be' F""" padded to `max_length`={max_length}""" ) _a : int = pad_token_id * torch.ones( (tensor.shape[0], max_length) ,dtype=tensor.dtype ,device=tensor.device ) _a : Union[str, Any] = tensor return padded_tensor
271
'''simple docstring''' from __future__ import annotations from random import choice def UpperCAmelCase_ (__a : str ): """simple docstring""" return choice(__a ) def UpperCAmelCase_ (__a : list[int] , __a : int ): """simple docstring""" _a : Dict = random_pivot(__a ) # partition based on pivot # linear time _a : Optional[int] = [e for e in lst if e < pivot] _a : List[str] = [e for e in lst if e > pivot] # if we get lucky, pivot might be the element we want. # we can easily see this: # small (elements smaller than k) # + pivot (kth element) # + big (elements larger than k) if len(__a ) == k - 1: return pivot # pivot is in elements bigger than k elif len(__a ) < k - 1: return kth_number(__a , k - len(__a ) - 1 ) # pivot is in elements smaller than k else: return kth_number(__a , __a ) if __name__ == "__main__": import doctest doctest.testmod()
271
1
'''simple docstring''' from sklearn.metrics import fa_score import datasets __lowerCAmelCase = """ The F1 score is the harmonic mean of the precision and recall. It can be computed with the equation: F1 = 2 * (precision * recall) / (precision + recall) """ __lowerCAmelCase = """ Args: predictions (`list` of `int`): Predicted labels. references (`list` of `int`): Ground truth labels. labels (`list` of `int`): The set of labels to include when `average` is not set to `'binary'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None. pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1. average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`. - 'binary': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary. - 'micro': Calculate metrics globally by counting the total true positives, false negatives and false positives. - 'macro': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. - 'weighted': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. This option can result in an F-score that is not between precision and recall. - 'samples': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification). sample_weight (`list` of `float`): Sample weights Defaults to None. Returns: f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better. Examples: Example 1-A simple binary example >>> f1_metric = datasets.load_metric(\"f1\") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0]) >>> print(results) {'f1': 0.5} Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`. >>> f1_metric = datasets.load_metric(\"f1\") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0) >>> print(round(results['f1'], 2)) 0.67 Example 3-The same simple binary example as in Example 1, but with `sample_weight` included. >>> f1_metric = datasets.load_metric(\"f1\") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3]) >>> print(round(results['f1'], 2)) 0.35 Example 4-A multiclass example, with different values for the `average` input. >>> predictions = [0, 2, 1, 0, 0, 1] >>> references = [0, 1, 2, 0, 1, 2] >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"macro\") >>> print(round(results['f1'], 2)) 0.27 >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"micro\") >>> print(round(results['f1'], 2)) 0.33 >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"weighted\") >>> print(round(results['f1'], 2)) 0.27 >>> results = f1_metric.compute(predictions=predictions, references=references, average=None) >>> print(results) {'f1': array([0.8, 0. , 0. ])} """ __lowerCAmelCase = """ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase__ ( datasets.Metric ): """simple docstring""" def __lowercase ( self : Dict ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('int32' ) ), 'references': datasets.Sequence(datasets.Value('int32' ) ), } if self.config_name == 'multilabel' else { 'predictions': datasets.Value('int32' ), 'references': datasets.Value('int32' ), } ) ,reference_urls=['https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html'] ,) def __lowercase ( self : Any ,_a : int ,_a : Optional[Any] ,_a : List[str]=None ,_a : Any=1 ,_a : int="binary" ,_a : int=None ): '''simple docstring''' _a : List[str] = fa_score( _a ,_a ,labels=_a ,pos_label=_a ,average=_a ,sample_weight=_a ) return {"f1": float(_a ) if score.size == 1 else score}
271
'''simple docstring''' class UpperCAmelCase__ : """simple docstring""" def __init__( self : Dict ): '''simple docstring''' _a : Dict = {} def __lowercase ( self : Union[str, Any] ): '''simple docstring''' print(self.vertex ) for i in self.vertex: print(_a ,' -> ' ,' -> '.join([str(_a ) for j in self.vertex[i]] ) ) def __lowercase ( self : Dict ,_a : int ,_a : int ): '''simple docstring''' if from_vertex in self.vertex: self.vertex[from_vertex].append(_a ) else: # else make a new vertex _a : int = [to_vertex] def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : Tuple = [False] * len(self.vertex ) # call the recursive helper function for i in range(len(self.vertex ) ): if not visited[i]: self.dfs_recursive(_a ,_a ) def __lowercase ( self : Union[str, Any] ,_a : int ,_a : list ): '''simple docstring''' _a : List[Any] = True print(_a ,end=' ' ) # Recur for all the vertices that are adjacent to this node for i in self.vertex: if not visited[i]: self.dfs_recursive(_a ,_a ) if __name__ == "__main__": __lowerCAmelCase = Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) g.print_graph() print("""DFS:""") g.dfs() # OUTPUT: # 0 -> 1 -> 2 # 1 -> 2 # 2 -> 0 -> 3 # 3 -> 3 # DFS: # 0 1 2 3
271
1
'''simple docstring''' import unittest from dataclasses import dataclass import pytest from accelerate.commands.config.config_args import SageMakerConfig from accelerate.utils import ComputeEnvironment from accelerate.utils.launch import _convert_nargs_to_dict @dataclass class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : int = ComputeEnvironment.AMAZON_SAGEMAKER __UpperCAmelCase : List[Any] = True __UpperCAmelCase : List[Any] = '''ml.p3.2xlarge''' __UpperCAmelCase : Optional[int] = '''accelerate_sagemaker_execution_role''' __UpperCAmelCase : List[str] = '''hf-sm''' __UpperCAmelCase : Dict = '''us-east-1''' __UpperCAmelCase : List[str] = 1 __UpperCAmelCase : int = '''accelerate-sagemaker-1''' __UpperCAmelCase : Optional[int] = '''1.6''' __UpperCAmelCase : List[str] = '''4.4''' __UpperCAmelCase : List[Any] = '''train.py''' __UpperCAmelCase : List[Any] = [ '''--model_name_or_path''', '''bert''', '''--do_train''', '''False''', '''--epochs''', '''3''', '''--learning_rate''', '''5e-5''', '''--max_steps''', '''50.5''', ] __UpperCAmelCase : Dict = [ '''--model_name_or_path''', '''bert''', '''--do_train''', '''--do_test''', '''False''', '''--do_predict''', '''--epochs''', '''3''', '''--learning_rate''', '''5e-5''', '''--max_steps''', '''50.5''', ] class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self : str ): '''simple docstring''' _a : Dict = _convert_nargs_to_dict(MockLaunchConfig.success_training_script_args ) assert isinstance(converted_args['model_name_or_path'] ,_a ) assert isinstance(converted_args['do_train'] ,_a ) assert isinstance(converted_args['epochs'] ,_a ) assert isinstance(converted_args['learning_rate'] ,_a ) assert isinstance(converted_args['max_steps'] ,_a ) with pytest.raises(_a ): _convert_nargs_to_dict(MockLaunchConfig.fail_training_script_args )
271
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = """▁""" __lowerCAmelCase = {"""vocab_file""": """sentencepiece.bpe.model""", """monolingual_vocab_file""": """dict.txt"""} __lowerCAmelCase = { """vocab_file""": { """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model""", }, """monolingual_vocab_file""": { """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt""", }, } __lowerCAmelCase = {"""vinai/bartpho-syllable""": 1_0_2_4} class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : Optional[Any] = VOCAB_FILES_NAMES __UpperCAmelCase : Dict = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Dict = ['''input_ids''', '''attention_mask'''] def __init__( self : str ,_a : str ,_a : Any ,_a : Any="<s>" ,_a : Dict="</s>" ,_a : int="</s>" ,_a : Union[str, Any]="<s>" ,_a : List[Any]="<unk>" ,_a : Optional[Any]="<pad>" ,_a : List[str]="<mask>" ,_a : Optional[Dict[str, Any]] = None ,**_a : int ,): '''simple docstring''' _a : Any = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else mask_token _a : Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_a ,eos_token=_a ,unk_token=_a ,sep_token=_a ,cls_token=_a ,pad_token=_a ,mask_token=_a ,sp_model_kwargs=self.sp_model_kwargs ,**_a ,) _a : Optional[int] = vocab_file _a : Union[str, Any] = monolingual_vocab_file _a : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_a ) ) # Load the reduced vocab # Keep order of special tokens for backward compatibility _a : Union[str, Any] = {} _a : int = 0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(_a ) not in self.fairseq_tokens_to_ids: _a : int = cnt cnt += 1 with open(_a ,'r' ,encoding='utf-8' ) as f: for line in f.readlines(): _a : str = line.strip().split()[0] _a : Tuple = len(self.fairseq_tokens_to_ids ) if str(_a ) not in self.fairseq_tokens_to_ids: _a : List[str] = len(self.fairseq_tokens_to_ids ) _a : Tuple = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : Union[str, Any] ): '''simple docstring''' _a : int = self.__dict__.copy() _a : str = None _a : Optional[Any] = self.sp_model.serialized_model_proto() return state def __setstate__( self : Tuple ,_a : Tuple ): '''simple docstring''' _a : Tuple = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs' ): _a : List[str] = {} _a : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def __lowercase ( self : Dict ,_a : List[int] ,_a : Optional[List[int]] = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _a : Dict = [self.cls_token_id] _a : int = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def __lowercase ( self : int ,_a : List[int] ,_a : Optional[List[int]] = None ,_a : bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a ,token_ids_a=_a ,already_has_special_tokens=_a ) if token_ids_a is None: return [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1, 1] + ([0] * len(_a )) + [1] def __lowercase ( self : Tuple ,_a : List[int] ,_a : Optional[List[int]] = None ): '''simple docstring''' _a : List[str] = [self.sep_token_id] _a : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def __lowercase ( self : Dict ): '''simple docstring''' return len(self.fairseq_ids_to_tokens ) def __lowercase ( self : Dict ): '''simple docstring''' _a : List[str] = {self.convert_ids_to_tokens(_a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __lowercase ( self : Tuple ,_a : str ): '''simple docstring''' return self.sp_model.encode(_a ,out_type=_a ) def __lowercase ( self : Union[str, Any] ,_a : Union[str, Any] ): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def __lowercase ( self : Any ,_a : int ): '''simple docstring''' return self.fairseq_ids_to_tokens[index] def __lowercase ( self : Tuple ,_a : Union[str, Any] ): '''simple docstring''' _a : str = ''.join(_a ).replace(_a ,' ' ).strip() return out_string def __lowercase ( self : Union[str, Any] ,_a : str ,_a : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(_a ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _a : int = os.path.join( _a ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) _a : int = os.path.join( _a ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['monolingual_vocab_file'] ,) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,_a ) elif not os.path.isfile(self.vocab_file ): with open(_a ,'wb' ) as fi: _a : List[Any] = self.sp_model.serialized_model_proto() fi.write(_a ) if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath( _a ) and os.path.isfile(self.monolingual_vocab_file ): copyfile(self.monolingual_vocab_file ,_a ) elif not os.path.isfile(self.monolingual_vocab_file ): with open(_a ,'w' ,encoding='utf-8' ) as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(F"""{str(_a )} \n""" ) return out_vocab_file, out_monolingual_vocab_file
271
1
'''simple docstring''' import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def UpperCAmelCase_ (__a : str , __a : Union[str, Any] , __a : int , __a : int , __a : Union[str, Any] ): """simple docstring""" _a : str = TapasConfig.from_json_file(__a ) # set absolute/relative position embeddings parameter _a : str = reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": _a : int = TapasForQuestionAnswering(config=__a ) elif task == "WTQ": # run_task_main.py hparams _a : Dict = 4 _a : List[Any] = True # hparam_utils.py hparams _a : Optional[int] = 0.664694 _a : Any = 0.207951 _a : str = 0.121194 _a : Optional[int] = True _a : Optional[int] = True _a : int = False _a : Tuple = 0.0352513 _a : Optional[Any] = TapasForQuestionAnswering(config=__a ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams _a : int = 4 _a : Optional[Any] = False # hparam_utils.py hparams _a : Dict = 36.4519 _a : Union[str, Any] = 0.903421 _a : Tuple = 222.088 _a : Optional[Any] = True _a : Dict = True _a : Any = True _a : Any = 0.763141 _a : Dict = TapasForQuestionAnswering(config=__a ) elif task == "TABFACT": _a : List[str] = TapasForSequenceClassification(config=__a ) elif task == "MLM": _a : List[Any] = TapasForMaskedLM(config=__a ) elif task == "INTERMEDIATE_PRETRAINING": _a : List[Any] = TapasModel(config=__a ) else: raise ValueError(f"""Task {task} not supported.""" ) print(f"""Building PyTorch model from configuration: {config}""" ) # Load weights from tf checkpoint load_tf_weights_in_tapas(__a , __a , __a ) # Save pytorch-model (weights and configuration) print(f"""Save PyTorch model to {pytorch_dump_path}""" ) model.save_pretrained(__a ) # Save tokenizer files print(f"""Save tokenizer files to {pytorch_dump_path}""" ) _a : Optional[Any] = TapasTokenizer(vocab_file=tf_checkpoint_path[:-1_0] + 'vocab.txt' , model_max_length=5_1_2 ) tokenizer.save_pretrained(__a ) print('Used relative position embeddings:' , model.config.reset_position_index_per_cell ) if __name__ == "__main__": __lowerCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--task""", default="""SQA""", type=str, help="""Model task for which to convert a checkpoint. Defaults to SQA.""" ) parser.add_argument( """--reset_position_index_per_cell""", default=False, action="""store_true""", help="""Whether to use relative position embeddings or not. Defaults to True.""", ) parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--tapas_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained TAPAS model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) __lowerCAmelCase = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
271
'''simple docstring''' import numpy as np from transformers import BatchFeature from transformers.testing_utils import require_tf, require_torch from .test_feature_extraction_common import FeatureExtractionSavingTestMixin class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = None __UpperCAmelCase : List[Any] = None @property def __lowercase ( self : Dict ): '''simple docstring''' return self.feat_extract_tester.prepare_feat_extract_dict() def __lowercase ( self : str ): '''simple docstring''' _a : Dict = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(_a ,'feature_size' ) ) self.assertTrue(hasattr(_a ,'sampling_rate' ) ) self.assertTrue(hasattr(_a ,'padding_value' ) ) def __lowercase ( self : int ): '''simple docstring''' _a : Any = self.feat_extract_tester.prepare_inputs_for_common() _a : str = self.feature_extraction_class(**self.feat_extract_dict ) _a : int = feat_extract.model_input_names[0] _a : List[Any] = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(_a ) == len(_a ) for x, y in zip(_a ,processed_features[input_name] ) ) ) _a : Any = self.feat_extract_tester.prepare_inputs_for_common(equal_length=_a ) _a : Union[str, Any] = BatchFeature({input_name: speech_inputs} ,tensor_type='np' ) _a : Union[str, Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: _a : Optional[int] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_torch def __lowercase ( self : Any ): '''simple docstring''' _a : List[Any] = self.feat_extract_tester.prepare_inputs_for_common(equal_length=_a ) _a : Dict = self.feature_extraction_class(**self.feat_extract_dict ) _a : int = feat_extract.model_input_names[0] _a : str = BatchFeature({input_name: speech_inputs} ,tensor_type='pt' ) _a : str = processed_features[input_name] if len(batch_features_input.shape ) < 3: _a : str = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_tf def __lowercase ( self : int ): '''simple docstring''' _a : int = self.feat_extract_tester.prepare_inputs_for_common(equal_length=_a ) _a : Dict = self.feature_extraction_class(**self.feat_extract_dict ) _a : Tuple = feat_extract.model_input_names[0] _a : int = BatchFeature({input_name: speech_inputs} ,tensor_type='tf' ) _a : Optional[int] = processed_features[input_name] if len(batch_features_input.shape ) < 3: _a : Optional[Any] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) def __lowercase ( self : Dict ,_a : Any=False ): '''simple docstring''' def _inputs_have_equal_length(_a : Tuple ): _a : Tuple = len(input[0] ) for input_slice in input[1:]: if len(_a ) != length: return False return True def _inputs_are_equal(_a : Optional[Any] ,_a : Union[str, Any] ): if len(_a ) != len(_a ): return False for input_slice_a, input_slice_a in zip(_a ,_a ): if not np.allclose(np.asarray(_a ) ,np.asarray(_a ) ,atol=1E-3 ): return False return True _a : int = self.feature_extraction_class(**self.feat_extract_dict ) _a : Tuple = self.feat_extract_tester.prepare_inputs_for_common(numpify=_a ) _a : Union[str, Any] = feat_extract.model_input_names[0] _a : Tuple = BatchFeature({input_name: speech_inputs} ) _a : str = self.feat_extract_tester.seq_length_diff _a : Dict = self.feat_extract_tester.max_seq_length + pad_diff _a : Dict = self.feat_extract_tester.min_seq_length _a : Optional[Any] = self.feat_extract_tester.batch_size _a : Tuple = self.feat_extract_tester.feature_size # test padding for List[int] + numpy _a : int = feat_extract.pad(_a ,padding=_a ) _a : List[Any] = input_a[input_name] _a : Tuple = feat_extract.pad(_a ,padding='longest' ) _a : Any = input_a[input_name] _a : Optional[Any] = feat_extract.pad(_a ,padding='max_length' ,max_length=len(speech_inputs[-1] ) ) _a : List[str] = input_a[input_name] _a : List[str] = feat_extract.pad(_a ,padding='longest' ,return_tensors='np' ) _a : str = input_a[input_name] # max_length parameter has to be provided when setting `padding="max_length"` with self.assertRaises(_a ): feat_extract.pad(_a ,padding='max_length' )[input_name] _a : int = feat_extract.pad( _a ,padding='max_length' ,max_length=_a ,return_tensors='np' ) _a : Optional[int] = input_a[input_name] self.assertFalse(_inputs_have_equal_length(_a ) ) self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertTrue(_inputs_are_equal(_a ,_a ) ) self.assertTrue(len(input_a[0] ) == pad_min_length ) self.assertTrue(len(input_a[1] ) == pad_min_length + pad_diff ) self.assertTrue(input_a.shape[:2] == (batch_size, len(input_a[0] )) ) self.assertTrue(input_a.shape[:2] == (batch_size, pad_max_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == input_a.shape[2] == feature_size ) # test padding for `pad_to_multiple_of` for List[int] + numpy _a : Tuple = feat_extract.pad(_a ,pad_to_multiple_of=10 ) _a : List[str] = input_a[input_name] _a : str = feat_extract.pad(_a ,padding='longest' ,pad_to_multiple_of=10 ) _a : Tuple = input_a[input_name] _a : Optional[int] = feat_extract.pad( _a ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=_a ) _a : Any = input_a[input_name] _a : Optional[int] = feat_extract.pad( _a ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=_a ,return_tensors='np' ,) _a : Dict = input_a[input_name] self.assertTrue(all(len(_a ) % 10 == 0 for x in input_a ) ) self.assertTrue(_inputs_are_equal(_a ,_a ) ) _a : List[str] = pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10 self.assertTrue(all(len(_a ) == expected_mult_pad_length for x in input_a ) ) self.assertEqual(input_a.shape[:2] ,(batch_size, expected_mult_pad_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == feature_size ) # Check padding value is correct _a : Any = (np.ones(self.feat_extract_tester.feature_size ) * feat_extract.padding_value).sum() self.assertTrue( abs(np.asarray(input_a[0] )[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1E-3 ) self.assertTrue( abs( np.asarray(input_a[1] )[pad_min_length + pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff) ) < 1E-3 ) self.assertTrue( abs( np.asarray(input_a[2] )[pad_min_length + 2 * pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff) ) < 1E-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1E-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length) ) < 1E-3 ) def __lowercase ( self : List[Any] ,_a : Optional[int]=False ): '''simple docstring''' def _inputs_have_equal_length(_a : List[str] ): _a : Union[str, Any] = len(input[0] ) for input_slice in input[1:]: if len(_a ) != length: return False return True def _inputs_are_equal(_a : List[str] ,_a : List[str] ): if len(_a ) != len(_a ): return False for input_slice_a, input_slice_a in zip(_a ,_a ): if not np.allclose(np.asarray(_a ) ,np.asarray(_a ) ,atol=1E-3 ): return False return True _a : Dict = self.feature_extraction_class(**self.feat_extract_dict ) _a : str = self.feat_extract_tester.prepare_inputs_for_common(numpify=_a ) _a : Any = feat_extract.model_input_names[0] _a : List[Any] = BatchFeature({input_name: speech_inputs} ) # truncate to smallest _a : Union[str, Any] = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,truncation=_a ) _a : str = input_a[input_name] _a : List[str] = feat_extract.pad(_a ,padding='max_length' ,max_length=len(speech_inputs[0] ) ) _a : Tuple = input_a[input_name] self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertFalse(_inputs_have_equal_length(_a ) ) # truncate to smallest with np _a : Dict = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ,truncation=_a ,) _a : Any = input_a[input_name] _a : List[Any] = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ) _a : int = input_a[input_name] self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertTrue(input_a.shape[1] == len(speech_inputs[0] ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(_a ) ) # truncate to middle _a : Dict = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=_a ,return_tensors='np' ,) _a : List[Any] = input_a[input_name] _a : Tuple = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=_a ) _a : Tuple = input_a[input_name] _a : Tuple = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,return_tensors='np' ) _a : Dict = input_a[input_name] self.assertTrue(input_a.shape[1] == len(speech_inputs[1] ) ) self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertTrue(_inputs_are_equal(_a ,_a ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(_a ) ) self.assertTrue(len(input_a[-1] ) == len(speech_inputs[-1] ) ) # padding has to be max_length when setting `truncation=True` with self.assertRaises(_a ): feat_extract.pad(_a ,truncation=_a )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(_a ): feat_extract.pad(_a ,padding='longest' ,truncation=_a )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(_a ): feat_extract.pad(_a ,padding='longest' ,truncation=_a )[input_name] # max_length parameter has to be provided when setting `truncation=True` and padding="max_length" with self.assertRaises(_a ): feat_extract.pad(_a ,padding='max_length' ,truncation=_a )[input_name] # test truncation for `pad_to_multiple_of` for List[int] + numpy _a : Optional[Any] = 12 _a : List[Any] = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=_a ,truncation=_a ,) _a : Tuple = input_a[input_name] _a : str = feat_extract.pad( _a ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=_a ,) _a : List[Any] = input_a[input_name] # retrieve expected_length as multiple of pad_to_multiple_of _a : List[Any] = len(speech_inputs[0] ) if expected_length % pad_to_multiple_of != 0: _a : Union[str, Any] = ((len(speech_inputs[0] ) // pad_to_multiple_of) + 1) * pad_to_multiple_of self.assertTrue(len(input_a[0] ) == expected_length ) self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertFalse(_inputs_have_equal_length(_a ) ) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' self._check_padding(numpify=_a ) def __lowercase ( self : Tuple ): '''simple docstring''' self._check_padding(numpify=_a ) def __lowercase ( self : Dict ): '''simple docstring''' self._check_truncation(numpify=_a ) def __lowercase ( self : str ): '''simple docstring''' self._check_truncation(numpify=_a ) @require_torch def __lowercase ( self : Dict ): '''simple docstring''' _a : Any = self.feature_extraction_class(**self.feat_extract_dict ) _a : List[Any] = self.feat_extract_tester.prepare_inputs_for_common() _a : Union[str, Any] = feat_extract.model_input_names[0] _a : Optional[int] = BatchFeature({input_name: speech_inputs} ) _a : List[Any] = feat_extract.pad(_a ,padding='longest' ,return_tensors='np' )[input_name] _a : List[str] = feat_extract.pad(_a ,padding='longest' ,return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1E-2 ) @require_tf def __lowercase ( self : int ): '''simple docstring''' _a : List[str] = self.feature_extraction_class(**self.feat_extract_dict ) _a : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_common() _a : Dict = feat_extract.model_input_names[0] _a : Optional[Any] = BatchFeature({input_name: speech_inputs} ) _a : Dict = feat_extract.pad(_a ,padding='longest' ,return_tensors='np' )[input_name] _a : Any = feat_extract.pad(_a ,padding='longest' ,return_tensors='tf' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_tf.numpy().astype(np.floataa ).sum() ) < 1E-2 ) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : str = self.feat_extract_dict _a : List[Any] = True _a : Optional[int] = self.feature_extraction_class(**_a ) _a : List[Any] = self.feat_extract_tester.prepare_inputs_for_common() _a : Tuple = [len(_a ) for x in speech_inputs] _a : int = feat_extract.model_input_names[0] _a : Optional[Any] = BatchFeature({input_name: speech_inputs} ) _a : str = feat_extract.pad(_a ,padding='longest' ,return_tensors='np' ) self.assertIn('attention_mask' ,_a ) self.assertListEqual(list(processed.attention_mask.shape ) ,list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() ,_a ) def __lowercase ( self : int ): '''simple docstring''' _a : Any = self.feat_extract_dict _a : Tuple = True _a : Optional[int] = self.feature_extraction_class(**_a ) _a : Dict = self.feat_extract_tester.prepare_inputs_for_common() _a : Dict = [len(_a ) for x in speech_inputs] _a : Union[str, Any] = feat_extract.model_input_names[0] _a : Any = BatchFeature({input_name: speech_inputs} ) _a : List[Any] = min(_a ) _a : Dict = feat_extract.pad( _a ,padding='max_length' ,max_length=_a ,truncation=_a ,return_tensors='np' ) self.assertIn('attention_mask' ,_a ) self.assertListEqual( list(processed_pad.attention_mask.shape ) ,[processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() ,[max_length for x in speech_inputs] )
271
1
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import KarrasVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : UNetaDModel __UpperCAmelCase : KarrasVeScheduler def __init__( self : Union[str, Any] ,_a : UNetaDModel ,_a : KarrasVeScheduler ): '''simple docstring''' super().__init__() self.register_modules(unet=_a ,scheduler=_a ) @torch.no_grad() def __call__( self : List[Any] ,_a : int = 1 ,_a : int = 50 ,_a : Optional[Union[torch.Generator, List[torch.Generator]]] = None ,_a : Optional[str] = "pil" ,_a : bool = True ,**_a : List[Any] ,): '''simple docstring''' _a : Any = self.unet.config.sample_size _a : Optional[int] = (batch_size, 3, img_size, img_size) _a : Dict = self.unet # sample x_0 ~ N(0, sigma_0^2 * I) _a : Dict = randn_tensor(_a ,generator=_a ,device=self.device ) * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(_a ) for t in self.progress_bar(self.scheduler.timesteps ): # here sigma_t == t_i from the paper _a : Optional[int] = self.scheduler.schedule[t] _a : List[str] = self.scheduler.schedule[t - 1] if t > 0 else 0 # 1. Select temporarily increased noise level sigma_hat # 2. Add new noise to move from sample_i to sample_hat _a, _a : List[Any] = self.scheduler.add_noise_to_input(_a ,_a ,generator=_a ) # 3. Predict the noise residual given the noise magnitude `sigma_hat` # The model inputs and output are adjusted by following eq. (213) in [1]. _a : Optional[int] = (sigma_hat / 2) * model((sample_hat + 1) / 2 ,sigma_hat / 2 ).sample # 4. Evaluate dx/dt at sigma_hat # 5. Take Euler step from sigma to sigma_prev _a : Tuple = self.scheduler.step(_a ,_a ,_a ,_a ) if sigma_prev != 0: # 6. Apply 2nd order correction # The model inputs and output are adjusted by following eq. (213) in [1]. _a : Optional[int] = (sigma_prev / 2) * model((step_output.prev_sample + 1) / 2 ,sigma_prev / 2 ).sample _a : Optional[Any] = self.scheduler.step_correct( _a ,_a ,_a ,_a ,step_output.prev_sample ,step_output['derivative'] ,) _a : Dict = step_output.prev_sample _a : Tuple = (sample / 2 + 0.5).clamp(0 ,1 ) _a : Optional[Any] = sample.cpu().permute(0 ,2 ,3 ,1 ).numpy() if output_type == "pil": _a : List[str] = self.numpy_to_pil(_a ) if not return_dict: return (image,) return ImagePipelineOutput(images=_a )
271
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import KarrasVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : UNetaDModel __UpperCAmelCase : KarrasVeScheduler def __init__( self : Union[str, Any] ,_a : UNetaDModel ,_a : KarrasVeScheduler ): '''simple docstring''' super().__init__() self.register_modules(unet=_a ,scheduler=_a ) @torch.no_grad() def __call__( self : List[Any] ,_a : int = 1 ,_a : int = 50 ,_a : Optional[Union[torch.Generator, List[torch.Generator]]] = None ,_a : Optional[str] = "pil" ,_a : bool = True ,**_a : List[Any] ,): '''simple docstring''' _a : Any = self.unet.config.sample_size _a : Optional[int] = (batch_size, 3, img_size, img_size) _a : Dict = self.unet # sample x_0 ~ N(0, sigma_0^2 * I) _a : Dict = randn_tensor(_a ,generator=_a ,device=self.device ) * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(_a ) for t in self.progress_bar(self.scheduler.timesteps ): # here sigma_t == t_i from the paper _a : Optional[int] = self.scheduler.schedule[t] _a : List[str] = self.scheduler.schedule[t - 1] if t > 0 else 0 # 1. Select temporarily increased noise level sigma_hat # 2. Add new noise to move from sample_i to sample_hat _a, _a : List[Any] = self.scheduler.add_noise_to_input(_a ,_a ,generator=_a ) # 3. Predict the noise residual given the noise magnitude `sigma_hat` # The model inputs and output are adjusted by following eq. (213) in [1]. _a : Optional[int] = (sigma_hat / 2) * model((sample_hat + 1) / 2 ,sigma_hat / 2 ).sample # 4. Evaluate dx/dt at sigma_hat # 5. Take Euler step from sigma to sigma_prev _a : Tuple = self.scheduler.step(_a ,_a ,_a ,_a ) if sigma_prev != 0: # 6. Apply 2nd order correction # The model inputs and output are adjusted by following eq. (213) in [1]. _a : Optional[int] = (sigma_prev / 2) * model((step_output.prev_sample + 1) / 2 ,sigma_prev / 2 ).sample _a : Optional[Any] = self.scheduler.step_correct( _a ,_a ,_a ,_a ,step_output.prev_sample ,step_output['derivative'] ,) _a : Dict = step_output.prev_sample _a : Tuple = (sample / 2 + 0.5).clamp(0 ,1 ) _a : Optional[Any] = sample.cpu().permute(0 ,2 ,3 ,1 ).numpy() if output_type == "pil": _a : List[str] = self.numpy_to_pil(_a ) if not return_dict: return (image,) return ImagePipelineOutput(images=_a )
271
1
'''simple docstring''' from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor __lowerCAmelCase = transforms.Compose( [ transforms.Resize((2_5_6, 2_5_6)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) def UpperCAmelCase_ (__a : Union[str, Any] ): """simple docstring""" if isinstance(__a , torch.Tensor ): return image elif isinstance(__a , PIL.Image.Image ): _a : List[Any] = [image] _a : Optional[int] = [trans(img.convert('RGB' ) ) for img in image] _a : Dict = torch.stack(__a ) return image class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" def __init__( self : Optional[int] ,_a : Optional[Any] ,_a : List[Any] ): '''simple docstring''' super().__init__() # make sure scheduler can always be converted to DDIM _a : Any = DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=_a ,scheduler=_a ) def __lowercase ( self : int ,_a : int ): '''simple docstring''' if strength < 0 or strength > 1: raise ValueError(F"""The value of strength should in [0.0, 1.0] but is {strength}""" ) def __lowercase ( self : Optional[int] ,_a : Dict ,_a : Tuple ,_a : Dict ): '''simple docstring''' _a : Optional[Any] = min(int(num_inference_steps * strength ) ,_a ) _a : Union[str, Any] = max(num_inference_steps - init_timestep ,0 ) _a : Any = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def __lowercase ( self : int ,_a : List[str] ,_a : Optional[Any] ,_a : Union[str, Any] ,_a : List[str] ,_a : List[Any] ,_a : Optional[Any]=None ): '''simple docstring''' if not isinstance(_a ,(torch.Tensor, PIL.Image.Image, list) ): raise ValueError( F"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(_a )}""" ) _a : Dict = image.to(device=_a ,dtype=_a ) if isinstance(_a ,_a ) and len(_a ) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(_a )}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" ) _a : str = init_latents.shape _a : int = randn_tensor(_a ,generator=_a ,device=_a ,dtype=_a ) # get latents print('add noise to latents at timestep' ,_a ) _a : int = self.scheduler.add_noise(_a ,_a ,_a ) _a : List[Any] = init_latents return latents @torch.no_grad() def __call__( self : List[Any] ,_a : Union[torch.FloatTensor, PIL.Image.Image] = None ,_a : float = 0.8 ,_a : int = 1 ,_a : Optional[Union[torch.Generator, List[torch.Generator]]] = None ,_a : float = 0.0 ,_a : int = 50 ,_a : Optional[bool] = None ,_a : Optional[str] = "pil" ,_a : bool = True ,): '''simple docstring''' self.check_inputs(_a ) # 2. Preprocess image _a : Dict = preprocess(_a ) # 3. set timesteps self.scheduler.set_timesteps(_a ,device=self.device ) _a, _a : str = self.get_timesteps(_a ,_a ,self.device ) _a : List[str] = timesteps[:1].repeat(_a ) # 4. Prepare latent variables _a : str = self.prepare_latents(_a ,_a ,_a ,self.unet.dtype ,self.device ,_a ) _a : Any = latents # 5. Denoising loop for t in self.progress_bar(_a ): # 1. predict noise model_output _a : List[Any] = self.unet(_a ,_a ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 _a : List[str] = self.scheduler.step( _a ,_a ,_a ,eta=_a ,use_clipped_model_output=_a ,generator=_a ,).prev_sample _a : str = (image / 2 + 0.5).clamp(0 ,1 ) _a : List[str] = image.cpu().permute(0 ,2 ,3 ,1 ).numpy() if output_type == "pil": _a : str = self.numpy_to_pil(_a ) if not return_dict: return (image, latent_timestep.item()) return ImagePipelineOutput(images=_a )
271
'''simple docstring''' import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version from .. import __version__ from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging __lowerCAmelCase = ( """https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py""" ) __lowerCAmelCase = logging.get_logger(__name__) # pylint: disable=invalid-name def UpperCAmelCase_ (): """simple docstring""" _a : Optional[int] = 'https://pypi.org/pypi/diffusers/json' _a : int = json.loads(request.urlopen(__a ).read() )['releases'].keys() return sorted(__a , key=lambda __a : version.Version(__a ) ) def UpperCAmelCase_ (): """simple docstring""" if HF_MODULES_CACHE in sys.path: return sys.path.append(__a ) os.makedirs(__a , exist_ok=__a ) _a : str = Path(__a ) / '__init__.py' if not init_path.exists(): init_path.touch() def UpperCAmelCase_ (__a : Union[str, os.PathLike] ): """simple docstring""" init_hf_modules() _a : Dict = Path(__a ) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent ) os.makedirs(__a , exist_ok=__a ) _a : Optional[int] = dynamic_module_path / '__init__.py' if not init_path.exists(): init_path.touch() def UpperCAmelCase_ (__a : str ): """simple docstring""" with open(__a , 'r' , encoding='utf-8' ) as f: _a : int = f.read() # Imports of the form `import .xxx` _a : Tuple = re.findall('^\s*import\s+\.(\S+)\s*$' , __a , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall('^\s*from\s+\.(\S+)\s+import' , __a , flags=re.MULTILINE ) # Unique-ify return list(set(__a ) ) def UpperCAmelCase_ (__a : Any ): """simple docstring""" _a : Optional[int] = False _a : Optional[int] = [module_file] _a : List[str] = [] # Let's recurse through all relative imports while not no_change: _a : str = [] for f in files_to_check: new_imports.extend(get_relative_imports(__a ) ) _a : Union[str, Any] = Path(__a ).parent _a : str = [str(module_path / m ) for m in new_imports] _a : Tuple = [f for f in new_import_files if f not in all_relative_imports] _a : Dict = [f"""{f}.py""" for f in new_import_files] _a : List[str] = len(__a ) == 0 all_relative_imports.extend(__a ) return all_relative_imports def UpperCAmelCase_ (__a : Tuple ): """simple docstring""" with open(__a , 'r' , encoding='utf-8' ) as f: _a : Dict = f.read() # Imports of the form `import xxx` _a : Optional[int] = re.findall('^\s*import\s+(\S+)\s*$' , __a , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall('^\s*from\s+(\S+)\s+import' , __a , flags=re.MULTILINE ) # Only keep the top-level module _a : List[str] = [imp.split('.' )[0] for imp in imports if not imp.startswith('.' )] # Unique-ify and test we got them all _a : Optional[int] = list(set(__a ) ) _a : List[str] = [] for imp in imports: try: importlib.import_module(__a ) except ImportError: missing_packages.append(__a ) if len(__a ) > 0: raise ImportError( 'This modeling file requires the following packages that were not found in your environment: ' f"""{', '.join(__a )}. Run `pip install {' '.join(__a )}`""" ) return get_relative_imports(__a ) def UpperCAmelCase_ (__a : Any , __a : str ): """simple docstring""" _a : Any = module_path.replace(os.path.sep , '.' ) _a : Union[str, Any] = importlib.import_module(__a ) if class_name is None: return find_pipeline_class(__a ) return getattr(__a , __a ) def UpperCAmelCase_ (__a : Optional[int] ): """simple docstring""" from ..pipelines import DiffusionPipeline _a : List[str] = dict(inspect.getmembers(__a , inspect.isclass ) ) _a : str = None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , __a ) and cls.__module__.split('.' )[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( f"""Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:""" f""" {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in""" f""" {loaded_module}.""" ) _a : Any = cls return pipeline_class def UpperCAmelCase_ (__a : Union[str, os.PathLike] , __a : str , __a : Optional[Union[str, os.PathLike]] = None , __a : bool = False , __a : bool = False , __a : Optional[Dict[str, str]] = None , __a : Optional[Union[bool, str]] = None , __a : Optional[str] = None , __a : bool = False , ): """simple docstring""" _a : str = str(__a ) _a : Optional[Any] = os.path.join(__a , __a ) if os.path.isfile(__a ): _a : Tuple = module_file_or_url _a : Optional[Any] = 'local' elif pretrained_model_name_or_path.count('/' ) == 0: _a : int = get_diffusers_versions() # cut ".dev0" _a : Any = 'v' + '.'.join(__version__.split('.' )[:3] ) # retrieve github version that matches if revision is None: _a : Any = latest_version if latest_version[1:] in available_versions else 'main' logger.info(f"""Defaulting to latest_version: {revision}.""" ) elif revision in available_versions: _a : Any = f"""v{revision}""" elif revision == "main": _a : Optional[int] = revision else: raise ValueError( f"""`custom_revision`: {revision} does not exist. Please make sure to choose one of""" f""" {', '.join(available_versions + ['main'] )}.""" ) # community pipeline on GitHub _a : Tuple = COMMUNITY_PIPELINES_URL.format(revision=__a , pipeline=__a ) try: _a : Any = cached_download( __a , cache_dir=__a , force_download=__a , proxies=__a , resume_download=__a , local_files_only=__a , use_auth_token=__a , ) _a : List[Any] = 'git' _a : Any = pretrained_model_name_or_path + '.py' except EnvironmentError: logger.error(f"""Could not locate the {module_file} inside {pretrained_model_name_or_path}.""" ) raise else: try: # Load from URL or cache if already cached _a : Optional[Any] = hf_hub_download( __a , __a , cache_dir=__a , force_download=__a , proxies=__a , resume_download=__a , local_files_only=__a , use_auth_token=__a , ) _a : List[Any] = os.path.join('local' , '--'.join(pretrained_model_name_or_path.split('/' ) ) ) except EnvironmentError: logger.error(f"""Could not locate the {module_file} inside {pretrained_model_name_or_path}.""" ) raise # Check we have all the requirements in our environment _a : Optional[int] = check_imports(__a ) # Now we move the module inside our cached dynamic modules. _a : Optional[Any] = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(__a ) _a : Any = Path(__a ) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copy(__a , submodule_path / module_file ) for module_needed in modules_needed: _a : Dict = f"""{module_needed}.py""" shutil.copy(os.path.join(__a , __a ) , submodule_path / module_needed ) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. if isinstance(__a , __a ): _a : Optional[Any] = use_auth_token elif use_auth_token is True: _a : List[Any] = HfFolder.get_token() else: _a : Dict = None _a : int = model_info(__a , revision=__a , token=__a ).sha # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. _a : Optional[int] = submodule_path / commit_hash _a : str = full_submodule + os.path.sep + commit_hash create_dynamic_module(__a ) if not (submodule_path / module_file).exists(): shutil.copy(__a , submodule_path / module_file ) # Make sure we also have every file with relative for module_needed in modules_needed: if not (submodule_path / module_needed).exists(): get_cached_module_file( __a , f"""{module_needed}.py""" , cache_dir=__a , force_download=__a , resume_download=__a , proxies=__a , use_auth_token=__a , revision=__a , local_files_only=__a , ) return os.path.join(__a , __a ) def UpperCAmelCase_ (__a : Union[str, os.PathLike] , __a : str , __a : Optional[str] = None , __a : Optional[Union[str, os.PathLike]] = None , __a : bool = False , __a : bool = False , __a : Optional[Dict[str, str]] = None , __a : Optional[Union[bool, str]] = None , __a : Optional[str] = None , __a : bool = False , **__a : str , ): """simple docstring""" _a : Dict = get_cached_module_file( __a , __a , cache_dir=__a , force_download=__a , resume_download=__a , proxies=__a , use_auth_token=__a , revision=__a , local_files_only=__a , ) return get_class_in_module(__a , final_module.replace('.py' , '' ) )
271
1
'''simple docstring''' import inspect import unittest from math import floor from transformers import CvtConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import CvtForImageClassification, CvtModel from transformers.models.cvt.modeling_cvt import CVT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a : Tuple = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(_a ,'embed_dim' ) ) self.parent.assertTrue(hasattr(_a ,'num_heads' ) ) class UpperCAmelCase__ : """simple docstring""" def __init__( self : Any ,_a : List[Any] ,_a : Union[str, Any]=13 ,_a : Union[str, Any]=64 ,_a : List[str]=3 ,_a : List[Any]=[16, 48, 96] ,_a : Dict=[1, 3, 6] ,_a : Union[str, Any]=[1, 2, 10] ,_a : Dict=[7, 3, 3] ,_a : Any=[4, 2, 2] ,_a : List[Any]=[2, 1, 1] ,_a : int=[2, 2, 2] ,_a : int=[False, False, True] ,_a : Union[str, Any]=[0.0, 0.0, 0.0] ,_a : int=0.02 ,_a : List[str]=1E-12 ,_a : Dict=True ,_a : List[str]=True ,_a : Optional[int]=2 ,): '''simple docstring''' _a : List[Any] = parent _a : List[Any] = batch_size _a : Union[str, Any] = image_size _a : int = patch_sizes _a : List[str] = patch_stride _a : str = patch_padding _a : List[Any] = is_training _a : Optional[int] = use_labels _a : int = num_labels _a : Tuple = num_channels _a : int = embed_dim _a : Optional[int] = num_heads _a : List[str] = stride_kv _a : Union[str, Any] = depth _a : List[str] = cls_token _a : List[str] = attention_drop_rate _a : Dict = initializer_range _a : Optional[int] = layer_norm_eps def __lowercase ( self : int ): '''simple docstring''' _a : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _a : Tuple = None if self.use_labels: _a : Optional[int] = ids_tensor([self.batch_size] ,self.num_labels ) _a : int = self.get_config() return config, pixel_values, labels def __lowercase ( self : Any ): '''simple docstring''' return CvtConfig( image_size=self.image_size ,num_labels=self.num_labels ,num_channels=self.num_channels ,embed_dim=self.embed_dim ,num_heads=self.num_heads ,patch_sizes=self.patch_sizes ,patch_padding=self.patch_padding ,patch_stride=self.patch_stride ,stride_kv=self.stride_kv ,depth=self.depth ,cls_token=self.cls_token ,attention_drop_rate=self.attention_drop_rate ,initializer_range=self.initializer_range ,) def __lowercase ( self : Optional[Any] ,_a : Optional[Any] ,_a : str ,_a : Dict ): '''simple docstring''' _a : Optional[int] = CvtModel(config=_a ) model.to(_a ) model.eval() _a : Optional[int] = model(_a ) _a : Optional[int] = (self.image_size, self.image_size) _a, _a : Tuple = image_size[0], image_size[1] for i in range(len(self.depth ) ): _a : int = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) _a : List[str] = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.embed_dim[-1], height, width) ) def __lowercase ( self : Union[str, Any] ,_a : Optional[int] ,_a : Optional[int] ,_a : List[str] ): '''simple docstring''' _a : str = self.num_labels _a : Tuple = CvtForImageClassification(_a ) model.to(_a ) model.eval() _a : int = model(_a ,labels=_a ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def __lowercase ( self : List[str] ): '''simple docstring''' _a : List[Any] = self.prepare_config_and_inputs() _a, _a, _a : Optional[Any] = config_and_inputs _a : List[Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase__ ( lowercase__ , lowercase__ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : str = (CvtModel, CvtForImageClassification) if is_torch_available() else () __UpperCAmelCase : Tuple = ( {'''feature-extraction''': CvtModel, '''image-classification''': CvtForImageClassification} if is_torch_available() else {} ) __UpperCAmelCase : List[str] = False __UpperCAmelCase : Dict = False __UpperCAmelCase : Tuple = False __UpperCAmelCase : Union[str, Any] = False __UpperCAmelCase : List[str] = False def __lowercase ( self : List[Any] ): '''simple docstring''' _a : Optional[Any] = CvtModelTester(self ) _a : Optional[Any] = ConfigTester(self ,config_class=_a ,has_text_modality=_a ,hidden_size=37 ) def __lowercase ( self : Any ): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __lowercase ( self : List[Any] ): '''simple docstring''' return @unittest.skip(reason='Cvt does not output attentions' ) def __lowercase ( self : int ): '''simple docstring''' pass @unittest.skip(reason='Cvt does not use inputs_embeds' ) def __lowercase ( self : Optional[int] ): '''simple docstring''' pass @unittest.skip(reason='Cvt does not support input and output embeddings' ) def __lowercase ( self : str ): '''simple docstring''' pass def __lowercase ( self : Optional[int] ): '''simple docstring''' _a, _a : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : Optional[int] = model_class(_a ) _a : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _a : Any = [*signature.parameters.keys()] _a : Optional[int] = ['pixel_values'] self.assertListEqual(arg_names[:1] ,_a ) def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' def check_hidden_states_output(_a : str ,_a : List[str] ,_a : Optional[int] ): _a : Any = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): _a : Optional[Any] = model(**self._prepare_for_class(_a ,_a ) ) _a : Tuple = outputs.hidden_states _a : str = len(self.model_tester.depth ) self.assertEqual(len(_a ) ,_a ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) ,[ self.model_tester.embed_dim[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] ,) _a, _a : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : str = True check_hidden_states_output(_a ,_a ,_a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _a : str = True check_hidden_states_output(_a ,_a ,_a ) def __lowercase ( self : Tuple ): '''simple docstring''' _a : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_a ) @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def __lowercase ( self : Optional[int] ): '''simple docstring''' pass @slow def __lowercase ( self : Optional[Any] ): '''simple docstring''' for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Any = CvtModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def UpperCAmelCase_ (): """simple docstring""" _a : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" @cached_property def __lowercase ( self : Dict ): '''simple docstring''' return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def __lowercase ( self : str ): '''simple docstring''' _a : Optional[Any] = CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(_a ) _a : List[Any] = self.default_image_processor _a : Optional[Any] = prepare_img() _a : List[str] = image_processor(images=_a ,return_tensors='pt' ).to(_a ) # forward pass with torch.no_grad(): _a : int = model(**_a ) # verify the logits _a : Any = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape ,_a ) _a : List[str] = torch.tensor([0.9285, 0.9015, -0.3150] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,_a ,atol=1E-4 ) )
271
'''simple docstring''' def UpperCAmelCase_ (__a : list , __a : list , __a : int ): """simple docstring""" _a : Optional[Any] = len(__a ) _a : int = [[0] * n for i in range(__a )] for i in range(__a ): _a : Tuple = y_points[i] for i in range(2 , __a ): for j in range(__a , __a ): _a : Tuple = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
271
1
'''simple docstring''' import re from filelock import FileLock try: import nltk __lowerCAmelCase = True except (ImportError, ModuleNotFoundError): __lowerCAmelCase = False if NLTK_AVAILABLE: with FileLock(""".lock""") as lock: nltk.download("""punkt""", quiet=True) def UpperCAmelCase_ (__a : str ): """simple docstring""" re.sub('<n>' , '' , __a ) # 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(__a ) )
271
'''simple docstring''' import inspect import os import unittest from pathlib import Path import torch import accelerate from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils.testing import run_command class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Optional[Any] = inspect.getfile(accelerate.test_utils ) __UpperCAmelCase : List[str] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_cli.py'''] ) __UpperCAmelCase : Dict = ['''accelerate''', '''launch'''] __UpperCAmelCase : Dict = Path.home() / '''.cache/huggingface/accelerate''' __UpperCAmelCase : Dict = '''default_config.yaml''' __UpperCAmelCase : Optional[Any] = config_folder / config_file __UpperCAmelCase : Dict = config_folder / '''_default_config.yaml''' __UpperCAmelCase : Any = Path('''tests/test_configs''' ) @classmethod def __lowercase ( cls : int ): '''simple docstring''' if cls.config_path.is_file(): cls.config_path.rename(cls.changed_path ) @classmethod def __lowercase ( cls : List[Any] ): '''simple docstring''' if cls.changed_path.is_file(): cls.changed_path.rename(cls.config_path ) def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : Dict = self.base_cmd if torch.cuda.is_available() and (torch.cuda.device_count() > 1): cmd += ["--multi_gpu"] execute_subprocess_async(cmd + [self.test_file_path] ,env=os.environ.copy() ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' for config in sorted(self.test_config_path.glob('**/*.yaml' ) ): with self.subTest(config_file=_a ): execute_subprocess_async( self.base_cmd + ['--config_file', str(_a ), self.test_file_path] ,env=os.environ.copy() ) def __lowercase ( self : Optional[int] ): '''simple docstring''' execute_subprocess_async(['accelerate', 'test'] ,env=os.environ.copy() ) class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Optional[Any] = '''test-tpu''' __UpperCAmelCase : Any = '''us-central1-a''' __UpperCAmelCase : List[Any] = '''ls''' __UpperCAmelCase : Any = ['''accelerate''', '''tpu-config'''] __UpperCAmelCase : Dict = '''cd /usr/share''' __UpperCAmelCase : Any = '''tests/test_samples/test_command_file.sh''' __UpperCAmelCase : List[Any] = '''Running gcloud compute tpus tpu-vm ssh''' def __lowercase ( self : Dict ): '''simple docstring''' _a : Optional[Any] = run_command( self.cmd + ['--command', self.command, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug'] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" ,_a ,) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Any = run_command( self.cmd + [ '--config_file', 'tests/test_configs/0_12_0.yaml', '--command', self.command, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug', ] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" ,_a ,) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Optional[int] = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--debug'] ,return_stdout=_a ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_a ,) def __lowercase ( self : int ): '''simple docstring''' _a : Optional[Any] = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--command', self.command, '--debug'] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" ,_a ,) def __lowercase ( self : str ): '''simple docstring''' _a : List[str] = run_command( self.cmd + [ '--config_file', 'tests/test_configs/latest.yaml', '--command', self.command, '--command', 'echo "Hello World"', '--debug', ] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo \"Hello World\" --worker all""" ,_a ,) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : Any = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--command_file', self.command_file, '--debug'] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_a ,) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : Union[str, Any] = run_command( self.cmd + [ '--config_file', 'tests/test_configs/0_12_0.yaml', '--command_file', self.command_file, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug', ] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_a ,) def __lowercase ( self : Any ): '''simple docstring''' _a : Optional[int] = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--install_accelerate', '--debug'] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_a ,) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Optional[int] = run_command( self.cmd + [ '--config_file', 'tests/test_configs/latest.yaml', '--install_accelerate', '--accelerate_version', '12.0.0', '--debug', ] ,return_stdout=_a ,) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo \"hello world\"; echo \"this is a second command\" --worker all""" ,_a ,)
271
1
'''simple docstring''' # flake8: noqa # Lint as: python3 __lowerCAmelCase = [ """VerificationMode""", """Version""", """disable_progress_bar""", """enable_progress_bar""", """is_progress_bar_enabled""", """experimental""", ] from .info_utils import VerificationMode from .logging import disable_progress_bar, enable_progress_bar, is_progress_bar_enabled from .version import Version from .experimental import experimental
271
'''simple docstring''' from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar __lowerCAmelCase = TypeVar("""T""") class UpperCAmelCase__ ( Generic[T] ): """simple docstring""" def __init__( self : Tuple ,_a : T ): '''simple docstring''' _a : List[str] = data _a : Node[T] | None = None def __str__( self : Dict ): '''simple docstring''' return F"""{self.data}""" class UpperCAmelCase__ ( Generic[T] ): """simple docstring""" def __init__( self : Optional[int] ): '''simple docstring''' _a : Node[T] | None = None def __iter__( self : str ): '''simple docstring''' _a : Tuple = self.top while node: yield node.data _a : int = node.next def __str__( self : str ): '''simple docstring''' return "->".join([str(_a ) for item in self] ) def __len__( self : Optional[Any] ): '''simple docstring''' return len(tuple(iter(self ) ) ) def __lowercase ( self : str ): '''simple docstring''' return self.top is None def __lowercase ( self : List[Any] ,_a : T ): '''simple docstring''' _a : int = Node(_a ) if not self.is_empty(): _a : Optional[Any] = self.top _a : List[str] = node def __lowercase ( self : Tuple ): '''simple docstring''' if self.is_empty(): raise IndexError('pop from empty stack' ) assert isinstance(self.top ,_a ) _a : List[Any] = self.top _a : int = self.top.next return pop_node.data def __lowercase ( self : List[str] ): '''simple docstring''' if self.is_empty(): raise IndexError('peek from empty stack' ) assert self.top is not None return self.top.data def __lowercase ( self : List[str] ): '''simple docstring''' _a : Optional[int] = None if __name__ == "__main__": from doctest import testmod testmod()
271
1
'''simple docstring''' import argparse import os import torch from transformers import ( XLNetConfig, XLNetForQuestionAnswering, XLNetForSequenceClassification, XLNetLMHeadModel, load_tf_weights_in_xlnet, ) from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging __lowerCAmelCase = { """cola""": 2, """mnli""": 3, """mrpc""": 2, """sst-2""": 2, """sts-b""": 1, """qqp""": 2, """qnli""": 2, """rte""": 2, """wnli""": 2, } logging.set_verbosity_info() def UpperCAmelCase_ (__a : str , __a : Dict , __a : Union[str, Any] , __a : Optional[Any]=None ): """simple docstring""" _a : str = XLNetConfig.from_json_file(__a ) _a : str = finetuning_task.lower() if finetuning_task is not None else '' if finetuning_task in GLUE_TASKS_NUM_LABELS: print(f"""Building PyTorch XLNetForSequenceClassification model from configuration: {config}""" ) _a : int = finetuning_task _a : Dict = GLUE_TASKS_NUM_LABELS[finetuning_task] _a : Optional[Any] = XLNetForSequenceClassification(__a ) elif "squad" in finetuning_task: _a : Dict = finetuning_task _a : List[str] = XLNetForQuestionAnswering(__a ) else: _a : Dict = XLNetLMHeadModel(__a ) # Load weights from tf checkpoint load_tf_weights_in_xlnet(__a , __a , __a ) # Save pytorch-model _a : List[str] = os.path.join(__a , __a ) _a : List[str] = os.path.join(__a , __a ) print(f"""Save PyTorch model to {os.path.abspath(__a )}""" ) torch.save(model.state_dict() , __a ) print(f"""Save configuration file to {os.path.abspath(__a )}""" ) with open(__a , 'w' , encoding='utf-8' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __lowerCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--xlnet_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained XLNet model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the folder to store the PyTorch model or dataset/vocab.""", ) parser.add_argument( """--finetuning_task""", default=None, type=str, help="""Name of a task on which the XLNet TensorFlow model was fine-tuned""", ) __lowerCAmelCase = parser.parse_args() print(args) convert_xlnet_checkpoint_to_pytorch( args.tf_checkpoint_path, args.xlnet_config_file, args.pytorch_dump_folder_path, args.finetuning_task )
271
'''simple docstring''' import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" @property def __lowercase ( self : List[str] ): '''simple docstring''' torch.manual_seed(0 ) _a : int = UNetaDModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=3 ,out_channels=3 ,down_block_types=('DownBlock2D', 'AttnDownBlock2D') ,up_block_types=('AttnUpBlock2D', 'UpBlock2D') ,) return model def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a : str = self.dummy_uncond_unet _a : int = PNDMScheduler() _a : str = PNDMPipeline(unet=_a ,scheduler=_a ) pndm.to(_a ) pndm.set_progress_bar_config(disable=_a ) _a : Optional[int] = torch.manual_seed(0 ) _a : Optional[Any] = pndm(generator=_a ,num_inference_steps=20 ,output_type='numpy' ).images _a : List[str] = torch.manual_seed(0 ) _a : Any = pndm(generator=_a ,num_inference_steps=20 ,output_type='numpy' ,return_dict=_a )[0] _a : List[Any] = image[0, -3:, -3:, -1] _a : Any = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _a : List[Any] = np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self : Tuple ): '''simple docstring''' _a : List[str] = 'google/ddpm-cifar10-32' _a : str = UNetaDModel.from_pretrained(_a ) _a : Union[str, Any] = PNDMScheduler() _a : Tuple = PNDMPipeline(unet=_a ,scheduler=_a ) pndm.to(_a ) pndm.set_progress_bar_config(disable=_a ) _a : str = torch.manual_seed(0 ) _a : Optional[Any] = pndm(generator=_a ,output_type='numpy' ).images _a : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _a : Tuple = np.array([0.1564, 0.1_4645, 0.1406, 0.1_4715, 0.1_2425, 0.1_4045, 0.1_3115, 0.1_2175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
271
1
'''simple docstring''' import argparse import collections import os import re import tempfile import pandas as pd from datasets import Dataset from huggingface_hub import hf_hub_download, upload_folder 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/update_metadata.py __lowerCAmelCase = """src/transformers""" # This is to make sure the transformers module imported is the one in the repo. __lowerCAmelCase = direct_transformers_import(TRANSFORMERS_PATH) # Regexes that match TF/Flax/PT model names. __lowerCAmelCase = re.compile(r"""TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") __lowerCAmelCase = 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. __lowerCAmelCase = re.compile(r"""(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") # Fill this with tuples (pipeline_tag, model_mapping, auto_model) __lowerCAmelCase = [ ("""pretraining""", """MODEL_FOR_PRETRAINING_MAPPING_NAMES""", """AutoModelForPreTraining"""), ("""feature-extraction""", """MODEL_MAPPING_NAMES""", """AutoModel"""), ("""audio-classification""", """MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForAudioClassification"""), ("""text-generation""", """MODEL_FOR_CAUSAL_LM_MAPPING_NAMES""", """AutoModelForCausalLM"""), ("""automatic-speech-recognition""", """MODEL_FOR_CTC_MAPPING_NAMES""", """AutoModelForCTC"""), ("""image-classification""", """MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForImageClassification"""), ("""image-segmentation""", """MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES""", """AutoModelForImageSegmentation"""), ("""fill-mask""", """MODEL_FOR_MASKED_LM_MAPPING_NAMES""", """AutoModelForMaskedLM"""), ("""object-detection""", """MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES""", """AutoModelForObjectDetection"""), ( """zero-shot-object-detection""", """MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES""", """AutoModelForZeroShotObjectDetection""", ), ("""question-answering""", """MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES""", """AutoModelForQuestionAnswering"""), ("""text2text-generation""", """MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES""", """AutoModelForSeq2SeqLM"""), ("""text-classification""", """MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForSequenceClassification"""), ("""automatic-speech-recognition""", """MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES""", """AutoModelForSpeechSeq2Seq"""), ( """table-question-answering""", """MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES""", """AutoModelForTableQuestionAnswering""", ), ("""token-classification""", """MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForTokenClassification"""), ("""multiple-choice""", """MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES""", """AutoModelForMultipleChoice"""), ( """next-sentence-prediction""", """MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES""", """AutoModelForNextSentencePrediction""", ), ( """audio-frame-classification""", """MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForAudioFrameClassification""", ), ("""audio-xvector""", """MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES""", """AutoModelForAudioXVector"""), ( """document-question-answering""", """MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES""", """AutoModelForDocumentQuestionAnswering""", ), ( """visual-question-answering""", """MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES""", """AutoModelForVisualQuestionAnswering""", ), ("""image-to-text""", """MODEL_FOR_FOR_VISION_2_SEQ_MAPPING_NAMES""", """AutoModelForVision2Seq"""), ( """zero-shot-image-classification""", """MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForZeroShotImageClassification""", ), ("""depth-estimation""", """MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES""", """AutoModelForDepthEstimation"""), ("""video-classification""", """MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForVideoClassification"""), ("""mask-generation""", """MODEL_FOR_MASK_GENERATION_MAPPING_NAMES""", """AutoModelForMaskGeneration"""), ] def UpperCAmelCase_ (__a : Union[str, Any] ): """simple docstring""" _a : Optional[Any] = re.finditer('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)' , __a ) return [m.group(0 ) for m in matches] def UpperCAmelCase_ (): """simple docstring""" _a : Tuple = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES _a : Optional[Any] = { config.replace('Config' , '' ): model_type for model_type, config in config_maping_names.items() } # Dictionaries flagging if each model prefix has a backend in PT/TF/Flax. _a : int = collections.defaultdict(__a ) _a : Tuple = collections.defaultdict(__a ) _a : Any = collections.defaultdict(__a ) # Let's lookup through all transformers object (once) and find if models are supported by a given backend. for attr_name in dir(__a ): _a : List[str] = None if _re_tf_models.match(__a ) is not None: _a : Tuple = tf_models _a : str = _re_tf_models.match(__a ).groups()[0] elif _re_flax_models.match(__a ) is not None: _a : Optional[Any] = flax_models _a : Union[str, Any] = _re_flax_models.match(__a ).groups()[0] elif _re_pt_models.match(__a ) is not None: _a : int = pt_models _a : Any = _re_pt_models.match(__a ).groups()[0] if lookup_dict is not None: while len(__a ) > 0: if attr_name in model_prefix_to_model_type: _a : int = True break # Try again after removing the last word in the name _a : Optional[int] = ''.join(camel_case_split(__a )[:-1] ) _a : Tuple = set(list(pt_models.keys() ) + list(tf_models.keys() ) + list(flax_models.keys() ) ) _a : Union[str, Any] = list(__a ) all_models.sort() _a : str = {'model_type': all_models} _a : Tuple = [pt_models[t] for t in all_models] _a : Tuple = [tf_models[t] for t in all_models] _a : Dict = [flax_models[t] for t in all_models] # Now let's use the auto-mapping names to make sure _a : List[str] = {} for t in all_models: if t in transformers_module.models.auto.processing_auto.PROCESSOR_MAPPING_NAMES: _a : Union[str, Any] = 'AutoProcessor' elif t in transformers_module.models.auto.tokenization_auto.TOKENIZER_MAPPING_NAMES: _a : Dict = 'AutoTokenizer' elif t in transformers_module.models.auto.feature_extraction_auto.FEATURE_EXTRACTOR_MAPPING_NAMES: _a : Union[str, Any] = 'AutoFeatureExtractor' else: # Default to AutoTokenizer if a model has nothing, for backward compatibility. _a : Optional[Any] = 'AutoTokenizer' _a : Optional[Any] = [processors[t] for t in all_models] return pd.DataFrame(__a ) def UpperCAmelCase_ (__a : Optional[Any] ): """simple docstring""" _a : List[Any] = [ transformers_module.models.auto.modeling_auto, transformers_module.models.auto.modeling_tf_auto, transformers_module.models.auto.modeling_flax_auto, ] for pipeline_tag, model_mapping, auto_class in PIPELINE_TAGS_AND_AUTO_MODELS: _a : Dict = [model_mapping, f"""TF_{model_mapping}""", f"""FLAX_{model_mapping}"""] _a : str = [auto_class, f"""TF_{auto_class}""", f"""Flax_{auto_class}"""] # Loop through all three frameworks for module, cls, mapping in zip(__a , __a , __a ): # The type of pipeline may not exist in this framework if not hasattr(__a , __a ): continue # First extract all model_names _a : int = [] for name in getattr(__a , __a ).values(): if isinstance(__a , __a ): model_names.append(__a ) else: model_names.extend(list(__a ) ) # Add pipeline tag and auto model class for those models table.update({model_name: (pipeline_tag, cls) for model_name in model_names} ) return table def UpperCAmelCase_ (__a : str , __a : Any ): """simple docstring""" _a : List[str] = get_frameworks_table() _a : Dict = Dataset.from_pandas(__a ) _a : List[str] = hf_hub_download( 'huggingface/transformers-metadata' , 'pipeline_tags.json' , repo_type='dataset' , token=__a ) _a : List[Any] = Dataset.from_json(__a ) _a : Optional[Any] = { tags_dataset[i]['model_class']: (tags_dataset[i]['pipeline_tag'], tags_dataset[i]['auto_class']) for i in range(len(__a ) ) } _a : Union[str, Any] = update_pipeline_and_auto_class_table(__a ) # Sort the model classes to avoid some nondeterministic updates to create false update commits. _a : List[str] = sorted(table.keys() ) _a : Any = pd.DataFrame( { 'model_class': model_classes, 'pipeline_tag': [table[m][0] for m in model_classes], 'auto_class': [table[m][1] for m in model_classes], } ) _a : List[str] = Dataset.from_pandas(__a ) with tempfile.TemporaryDirectory() as tmp_dir: frameworks_dataset.to_json(os.path.join(__a , 'frameworks.json' ) ) tags_dataset.to_json(os.path.join(__a , 'pipeline_tags.json' ) ) if commit_sha is not None: _a : str = ( f"""Update with commit {commit_sha}\n\nSee: """ f"""https://github.com/huggingface/transformers/commit/{commit_sha}""" ) else: _a : Optional[Any] = 'Update' upload_folder( repo_id='huggingface/transformers-metadata' , folder_path=__a , repo_type='dataset' , token=__a , commit_message=__a , ) def UpperCAmelCase_ (): """simple docstring""" _a : Tuple = {tag: cls for tag, _, cls in PIPELINE_TAGS_AND_AUTO_MODELS} _a : Optional[Any] = transformers_module.pipelines.SUPPORTED_TASKS _a : Optional[int] = [] for key in pipeline_tasks: if key not in in_table: _a : List[str] = pipeline_tasks[key]['pt'] if isinstance(__a , (list, tuple) ): _a : Any = model[0] _a : Union[str, Any] = model.__name__ if model not in in_table.values(): missing.append(__a ) if len(__a ) > 0: _a : Optional[Any] = ', '.join(__a ) raise ValueError( 'The following pipeline tags are not present in the `PIPELINE_TAGS_AND_AUTO_MODELS` constant inside ' f"""`utils/update_metadata.py`: {msg}. Please add them!""" ) if __name__ == "__main__": __lowerCAmelCase = argparse.ArgumentParser() parser.add_argument("""--token""", type=str, help="""The token to use to push to the transformers-metadata dataset.""") parser.add_argument("""--commit_sha""", type=str, help="""The sha of the commit going with this update.""") parser.add_argument("""--check-only""", action="""store_true""", help="""Activate to just check all pipelines are present.""") __lowerCAmelCase = parser.parse_args() if args.check_only: check_pipeline_tags() else: update_metadata(args.token, args.commit_sha)
271
'''simple docstring''' import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow __lowerCAmelCase = logging.getLogger() @unittest.skip('''Temporarily disable the doc tests.''' ) @require_torch @require_tf @slow class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self : str ,_a : Path ,_a : Union[str, None] = None ,_a : Union[List[str], None] = None ,_a : Union[str, List[str], None] = None ,_a : bool = True ,): '''simple docstring''' _a : Optional[int] = [file for file in os.listdir(_a ) if os.path.isfile(os.path.join(_a ,_a ) )] if identifier is not None: _a : List[str] = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(_a ,_a ): for n_ in n_identifier: _a : Tuple = [file for file in files if n_ not in file] else: _a : Optional[Any] = [file for file in files if n_identifier not in file] _a : List[str] = ignore_files or [] ignore_files.append('__init__.py' ) _a : Tuple = [file for file in files if file not in ignore_files] for file in files: # Open all files print('Testing' ,_a ) if only_modules: _a : Any = file.split('.' )[0] try: _a : List[str] = getattr(_a ,_a ) _a : int = doctest.DocTestSuite(_a ) _a : Any = unittest.TextTestRunner().run(_a ) self.assertIs(len(result.failures ) ,0 ) except AttributeError: logger.info(F"""{module_identifier} is not a module.""" ) else: _a : Union[str, Any] = doctest.testfile(str('..' / directory / file ) ,optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed ,0 ) def __lowercase ( self : Any ): '''simple docstring''' _a : int = Path('src/transformers' ) _a : List[Any] = 'modeling' _a : Optional[Any] = [ 'modeling_ctrl.py', 'modeling_tf_ctrl.py', ] self.analyze_directory(_a ,identifier=_a ,ignore_files=_a ) def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : Optional[Any] = Path('src/transformers' ) _a : Optional[Any] = 'tokenization' self.analyze_directory(_a ,identifier=_a ) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Dict = Path('src/transformers' ) _a : str = 'configuration' self.analyze_directory(_a ,identifier=_a ) def __lowercase ( self : Any ): '''simple docstring''' _a : Tuple = Path('src/transformers' ) _a : List[Any] = ['configuration', 'modeling', 'tokenization'] self.analyze_directory(_a ,n_identifier=_a ) def __lowercase ( self : Tuple ): '''simple docstring''' _a : List[Any] = Path('docs/source' ) _a : List[str] = ['favicon.ico'] self.analyze_directory(_a ,ignore_files=_a ,only_modules=_a )
271
1
'''simple docstring''' # This model implementation is heavily inspired by https://github.com/haofanwang/ControlNet-for-Diffusers/ import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, ControlNetModel, DDIMScheduler, StableDiffusionControlNetImgaImgPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel from diffusers.utils import floats_tensor, load_image, load_numpy, randn_tensor, slow, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, ) enable_full_determinism() class UpperCAmelCase__ ( lowercase__ , lowercase__ , lowercase__ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : List[Any] = StableDiffusionControlNetImgaImgPipeline __UpperCAmelCase : Any = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} __UpperCAmelCase : str = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS __UpperCAmelCase : Tuple = IMAGE_TO_IMAGE_IMAGE_PARAMS.union({'''control_image'''} ) __UpperCAmelCase : Tuple = IMAGE_TO_IMAGE_IMAGE_PARAMS def __lowercase ( self : List[str] ): '''simple docstring''' torch.manual_seed(0 ) _a : Any = UNetaDConditionModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=4 ,out_channels=4 ,down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') ,up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') ,cross_attention_dim=32 ,) torch.manual_seed(0 ) _a : int = ControlNetModel( block_out_channels=(32, 64) ,layers_per_block=2 ,in_channels=4 ,down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') ,cross_attention_dim=32 ,conditioning_embedding_out_channels=(16, 32) ,) torch.manual_seed(0 ) _a : Any = DDIMScheduler( beta_start=0.0_0085 ,beta_end=0.012 ,beta_schedule='scaled_linear' ,clip_sample=_a ,set_alpha_to_one=_a ,) torch.manual_seed(0 ) _a : List[str] = AutoencoderKL( block_out_channels=[32, 64] ,in_channels=3 ,out_channels=3 ,down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] ,up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] ,latent_channels=4 ,) torch.manual_seed(0 ) _a : Tuple = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1E-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1000 ,) _a : int = CLIPTextModel(_a ) _a : Union[str, Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) _a : List[str] = { 'unet': unet, 'controlnet': controlnet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def __lowercase ( self : str ,_a : Optional[Any] ,_a : Union[str, Any]=0 ): '''simple docstring''' if str(_a ).startswith('mps' ): _a : Optional[Any] = torch.manual_seed(_a ) else: _a : Dict = torch.Generator(device=_a ).manual_seed(_a ) _a : str = 2 _a : Union[str, Any] = randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) ,generator=_a ,device=torch.device(_a ) ,) _a : Optional[Any] = floats_tensor(control_image.shape ,rng=random.Random(_a ) ).to(_a ) _a : Any = image.cpu().permute(0 ,2 ,3 ,1 )[0] _a : Dict = Image.fromarray(np.uinta(_a ) ).convert('RGB' ).resize((64, 64) ) _a : List[str] = { 'prompt': 'A painting of a squirrel eating a burger', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'numpy', 'image': image, 'control_image': control_image, } return inputs def __lowercase ( self : str ): '''simple docstring''' return self._test_attention_slicing_forward_pass(expected_max_diff=2E-3 ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() ,reason='XFormers attention is only available with CUDA and `xformers` installed' ,) def __lowercase ( self : Tuple ): '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 ) def __lowercase ( self : List[Any] ): '''simple docstring''' self._test_inference_batch_single_identical(expected_max_diff=2E-3 ) class UpperCAmelCase__ ( lowercase__ , lowercase__ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Optional[int] = StableDiffusionControlNetImgaImgPipeline __UpperCAmelCase : Union[str, Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} __UpperCAmelCase : Dict = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS __UpperCAmelCase : List[Any] = frozenset([] ) # TO_DO: add image_params once refactored VaeImageProcessor.preprocess def __lowercase ( self : Tuple ): '''simple docstring''' torch.manual_seed(0 ) _a : Union[str, Any] = UNetaDConditionModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=4 ,out_channels=4 ,down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') ,up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') ,cross_attention_dim=32 ,) torch.manual_seed(0 ) def init_weights(_a : Any ): if isinstance(_a ,torch.nn.Convad ): torch.nn.init.normal(m.weight ) m.bias.data.fill_(1.0 ) _a : List[str] = ControlNetModel( block_out_channels=(32, 64) ,layers_per_block=2 ,in_channels=4 ,down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') ,cross_attention_dim=32 ,conditioning_embedding_out_channels=(16, 32) ,) controlneta.controlnet_down_blocks.apply(_a ) torch.manual_seed(0 ) _a : Optional[Any] = ControlNetModel( block_out_channels=(32, 64) ,layers_per_block=2 ,in_channels=4 ,down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') ,cross_attention_dim=32 ,conditioning_embedding_out_channels=(16, 32) ,) controlneta.controlnet_down_blocks.apply(_a ) torch.manual_seed(0 ) _a : int = DDIMScheduler( beta_start=0.0_0085 ,beta_end=0.012 ,beta_schedule='scaled_linear' ,clip_sample=_a ,set_alpha_to_one=_a ,) torch.manual_seed(0 ) _a : Tuple = AutoencoderKL( block_out_channels=[32, 64] ,in_channels=3 ,out_channels=3 ,down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] ,up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] ,latent_channels=4 ,) torch.manual_seed(0 ) _a : Dict = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1E-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1000 ,) _a : int = CLIPTextModel(_a ) _a : str = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) _a : Optional[int] = MultiControlNetModel([controlneta, controlneta] ) _a : List[Any] = { 'unet': unet, 'controlnet': controlnet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def __lowercase ( self : Any ,_a : Optional[Any] ,_a : str=0 ): '''simple docstring''' if str(_a ).startswith('mps' ): _a : Dict = torch.manual_seed(_a ) else: _a : Optional[Any] = torch.Generator(device=_a ).manual_seed(_a ) _a : Dict = 2 _a : List[str] = [ randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) ,generator=_a ,device=torch.device(_a ) ,), randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) ,generator=_a ,device=torch.device(_a ) ,), ] _a : List[Any] = floats_tensor(control_image[0].shape ,rng=random.Random(_a ) ).to(_a ) _a : Dict = image.cpu().permute(0 ,2 ,3 ,1 )[0] _a : Any = Image.fromarray(np.uinta(_a ) ).convert('RGB' ).resize((64, 64) ) _a : List[Any] = { 'prompt': 'A painting of a squirrel eating a burger', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'numpy', 'image': image, 'control_image': control_image, } return inputs def __lowercase ( self : List[Any] ): '''simple docstring''' _a : Any = self.get_dummy_components() _a : Tuple = self.pipeline_class(**_a ) pipe.to(_a ) _a : str = 10.0 _a : List[str] = 4 _a : int = self.get_dummy_inputs(_a ) _a : Tuple = steps _a : Optional[int] = scale _a : Dict = pipe(**_a )[0] _a : Tuple = self.get_dummy_inputs(_a ) _a : Tuple = steps _a : Dict = scale _a : List[Any] = pipe(**_a ,control_guidance_start=0.1 ,control_guidance_end=0.2 )[0] _a : Optional[Any] = self.get_dummy_inputs(_a ) _a : int = steps _a : List[str] = scale _a : Any = pipe(**_a ,control_guidance_start=[0.1, 0.3] ,control_guidance_end=[0.2, 0.7] )[0] _a : Union[str, Any] = self.get_dummy_inputs(_a ) _a : List[str] = steps _a : List[Any] = scale _a : Union[str, Any] = pipe(**_a ,control_guidance_start=0.4 ,control_guidance_end=[0.5, 0.8] )[0] # make sure that all outputs are different assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 def __lowercase ( self : List[str] ): '''simple docstring''' return self._test_attention_slicing_forward_pass(expected_max_diff=2E-3 ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() ,reason='XFormers attention is only available with CUDA and `xformers` installed' ,) def __lowercase ( self : Dict ): '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 ) def __lowercase ( self : List[Any] ): '''simple docstring''' self._test_inference_batch_single_identical(expected_max_diff=2E-3 ) def __lowercase ( self : Any ): '''simple docstring''' _a : str = self.get_dummy_components() _a : List[str] = self.pipeline_class(**_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) with tempfile.TemporaryDirectory() as tmpdir: try: # save_pretrained is not implemented for Multi-ControlNet pipe.save_pretrained(_a ) except NotImplementedError: pass @slow @require_torch_gpu class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self : Tuple ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowercase ( self : Any ): '''simple docstring''' _a : Dict = ControlNetModel.from_pretrained('lllyasviel/sd-controlnet-canny' ) _a : Any = StableDiffusionControlNetImgaImgPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' ,safety_checker=_a ,controlnet=_a ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=_a ) _a : Tuple = torch.Generator(device='cpu' ).manual_seed(0 ) _a : str = 'evil space-punk bird' _a : Optional[int] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png' ).resize((512, 512) ) _a : Union[str, Any] = load_image( 'https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png' ).resize((512, 512) ) _a : Any = pipe( _a ,_a ,control_image=_a ,generator=_a ,output_type='np' ,num_inference_steps=50 ,strength=0.6 ,) _a : int = output.images[0] assert image.shape == (512, 512, 3) _a : Dict = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/img2img.npy' ) assert np.abs(expected_image - image ).max() < 9E-2
271
'''simple docstring''' import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def UpperCAmelCase_ (__a : Optional[Any] , __a : str , __a : Optional[Any]=None ): """simple docstring""" assert torch_layer.weight.shape == weight.shape, f"""{torch_layer} layer.weight does not match""" _a : str = nn.Parameter(__a ) if bias is not None: assert torch_layer.bias.shape == bias.shape, f"""{torch_layer} layer.bias does not match""" _a : Any = nn.Parameter(__a ) def UpperCAmelCase_ (__a : int , __a : Optional[Any] , __a : int ): """simple docstring""" _a : Tuple = np.asarray(weights[0] ) _a : Union[str, Any] = np.asarray(weights[1] ) _a : Dict = np.asarray(weights[2] ) set_param( torch_layer.self_attention.query_key , torch.tensor(__a ).transpose(1 , 2 ).contiguous().view(-1 , __a ) , ) set_param( torch_layer.self_attention.value , torch.tensor(__a ).transpose(1 , 2 ).contiguous().view(-1 , __a ) , ) set_param( torch_layer.output.dense , torch.tensor(__a ).view(-1 , __a ).contiguous().transpose(0 , 1 ) , ) def UpperCAmelCase_ (__a : Optional[Any] , __a : Optional[int] , __a : List[str] ): """simple docstring""" _a : Dict = np.asarray(weights[0] ) _a : Union[str, Any] = np.asarray(weights[1] ) _a : str = np.asarray(weights[2] ) _a : int = np.asarray(weights[3] ) set_param( torch_layer.self_attention.query , torch.tensor(__a ).transpose(1 , 2 ).contiguous().view(-1 , __a ) , ) set_param( torch_layer.self_attention.key , torch.tensor(__a ).transpose(1 , 2 ).contiguous().view(-1 , __a ) , ) set_param( torch_layer.self_attention.value , torch.tensor(__a ).transpose(1 , 2 ).contiguous().view(-1 , __a ) , ) set_param( torch_layer.output.dense , torch.tensor(__a ).view(-1 , __a ).contiguous().transpose(0 , 1 ) , ) def UpperCAmelCase_ (__a : Any , __a : Any , __a : Optional[Any] ): """simple docstring""" _a : List[str] = weights[0][0][0] _a : List[Any] = np.asarray(layer_norm_a[0] ) _a : List[str] = np.asarray(layer_norm_a[1] ) set_param( torch_block.attention.layer_norm , torch.tensor(__a ) , torch.tensor(__a ) , ) # lsh weights + output _a : List[str] = weights[0][1] if len(__a ) < 4: set_layer_weights_in_torch_lsh(__a , torch_block.attention , __a ) else: set_layer_weights_in_torch_local(__a , torch_block.attention , __a ) # intermediate weighs _a : Optional[Any] = weights[2][0][1][2] # Chunked Feed Forward if len(__a ) == 4: _a : Union[str, Any] = intermediate_weights[2] # layernorm 2 _a : Any = np.asarray(intermediate_weights[0][0] ) _a : List[Any] = np.asarray(intermediate_weights[0][1] ) set_param( torch_block.feed_forward.layer_norm , torch.tensor(__a ) , torch.tensor(__a ) , ) # intermediate dense _a : Any = np.asarray(intermediate_weights[1][0] ) _a : Any = np.asarray(intermediate_weights[1][1] ) set_param( torch_block.feed_forward.dense.dense , torch.tensor(__a ).transpose(0 , 1 ).contiguous() , torch.tensor(__a ) , ) # intermediate out _a : Optional[int] = np.asarray(intermediate_weights[4][0] ) _a : int = np.asarray(intermediate_weights[4][1] ) set_param( torch_block.feed_forward.output.dense , torch.tensor(__a ).transpose(0 , 1 ).contiguous() , torch.tensor(__a ) , ) def UpperCAmelCase_ (__a : Dict , __a : Dict , __a : List[Any] ): """simple docstring""" _a : Optional[int] = torch_model.reformer # word embeds _a : Tuple = np.asarray(weights[1] ) set_param( torch_model_reformer.embeddings.word_embeddings , torch.tensor(__a ) , ) if isinstance(weights[3] , __a ): _a : Any = torch_model_reformer.embeddings.position_embeddings for emb_idx in range(len(position_embeddings.weights ) ): _a : List[Any] = np.asarray(weights[3][emb_idx][0] ) assert ( position_embeddings.weights[emb_idx].shape == emb_weights.shape ), f"""{position_embeddings[emb_idx]} emb does not match""" _a : Any = nn.Parameter(torch.tensor(__a ) ) _a : List[str] = weights[5] assert len(torch_model_reformer.encoder.layers ) * 4 == len( __a ), "HF and trax model do not have the same number of layers" for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ): _a : Tuple = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)] set_block_weights_in_torch(__a , __a , __a ) # output layer norm _a : Optional[Any] = np.asarray(weights[7][0] ) _a : int = np.asarray(weights[7][1] ) set_param( torch_model_reformer.encoder.layer_norm , torch.tensor(__a ) , torch.tensor(__a ) , ) # output embeddings _a : List[str] = np.asarray(weights[9][0] ) _a : int = np.asarray(weights[9][1] ) set_param( torch_model.lm_head.decoder , torch.tensor(__a ).transpose(0 , 1 ).contiguous() , torch.tensor(__a ) , ) def UpperCAmelCase_ (__a : Tuple , __a : Optional[Any] , __a : Dict ): """simple docstring""" _a : List[Any] = ReformerConfig.from_json_file(__a ) print(f"""Building PyTorch model from configuration: {config}""" ) _a : int = ReformerModelWithLMHead(__a ) with open(__a , 'rb' ) as f: _a : Optional[Any] = pickle.load(__a )['weights'] set_model_weights_in_torch(__a , __a , config.hidden_size ) # Save pytorch-model print(f"""Save PyTorch model to {pytorch_dump_path}""" ) torch.save(model.state_dict() , __a ) if __name__ == "__main__": __lowerCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--trax_model_pkl_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained Reformer model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) __lowerCAmelCase = parser.parse_args() convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
271
1
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_squeezebert import SqueezeBertTokenizer __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} __lowerCAmelCase = { """vocab_file""": { """squeezebert/squeezebert-uncased""": ( """https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt""" ), """squeezebert/squeezebert-mnli""": """https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt""", """squeezebert/squeezebert-mnli-headless""": ( """https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """squeezebert/squeezebert-uncased""": ( """https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/tokenizer.json""" ), """squeezebert/squeezebert-mnli""": ( """https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/tokenizer.json""" ), """squeezebert/squeezebert-mnli-headless""": ( """https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/tokenizer.json""" ), }, } __lowerCAmelCase = { """squeezebert/squeezebert-uncased""": 5_1_2, """squeezebert/squeezebert-mnli""": 5_1_2, """squeezebert/squeezebert-mnli-headless""": 5_1_2, } __lowerCAmelCase = { """squeezebert/squeezebert-uncased""": {"""do_lower_case""": True}, """squeezebert/squeezebert-mnli""": {"""do_lower_case""": True}, """squeezebert/squeezebert-mnli-headless""": {"""do_lower_case""": True}, } class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : Optional[int] = VOCAB_FILES_NAMES __UpperCAmelCase : List[str] = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Optional[int] = PRETRAINED_INIT_CONFIGURATION __UpperCAmelCase : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : List[str] = SqueezeBertTokenizer def __init__( self : List[str] ,_a : str=None ,_a : int=None ,_a : int=True ,_a : Any="[UNK]" ,_a : str="[SEP]" ,_a : Any="[PAD]" ,_a : List[str]="[CLS]" ,_a : int="[MASK]" ,_a : Any=True ,_a : Any=None ,**_a : Tuple ,): '''simple docstring''' super().__init__( _a ,tokenizer_file=_a ,do_lower_case=_a ,unk_token=_a ,sep_token=_a ,pad_token=_a ,cls_token=_a ,mask_token=_a ,tokenize_chinese_chars=_a ,strip_accents=_a ,**_a ,) _a : Any = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' ,_a ) != do_lower_case or normalizer_state.get('strip_accents' ,_a ) != strip_accents or normalizer_state.get('handle_chinese_chars' ,_a ) != tokenize_chinese_chars ): _a : List[str] = getattr(_a ,normalizer_state.pop('type' ) ) _a : Any = do_lower_case _a : Union[str, Any] = strip_accents _a : Any = tokenize_chinese_chars _a : Optional[int] = normalizer_class(**_a ) _a : List[str] = do_lower_case def __lowercase ( self : Tuple ,_a : Any ,_a : Dict=None ): '''simple docstring''' _a : Tuple = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowercase ( self : int ,_a : List[int] ,_a : Optional[List[int]] = None ): '''simple docstring''' _a : Optional[int] = [self.sep_token_id] _a : 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 ) * [0] + len(token_ids_a + sep ) * [1] def __lowercase ( self : Tuple ,_a : str ,_a : Optional[str] = None ): '''simple docstring''' _a : Optional[int] = self._tokenizer.model.save(_a ,name=_a ) return tuple(_a )
271
'''simple docstring''' import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" @property def __lowercase ( self : Union[str, Any] ): '''simple docstring''' torch.manual_seed(0 ) _a : Any = UNetaDModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=3 ,out_channels=3 ,down_block_types=('DownBlock2D', 'AttnDownBlock2D') ,up_block_types=('AttnUpBlock2D', 'UpBlock2D') ,) return model @property def __lowercase ( self : Optional[int] ): '''simple docstring''' torch.manual_seed(0 ) _a : Union[str, Any] = VQModel( block_out_channels=[32, 64] ,in_channels=3 ,out_channels=3 ,down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] ,up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] ,latent_channels=3 ,) return model @property def __lowercase ( self : Optional[int] ): '''simple docstring''' torch.manual_seed(0 ) _a : Any = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1E-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1000 ,) return CLIPTextModel(_a ) def __lowercase ( self : Tuple ): '''simple docstring''' _a : Dict = self.dummy_uncond_unet _a : List[Any] = DDIMScheduler() _a : List[Any] = self.dummy_vq_model _a : str = LDMPipeline(unet=_a ,vqvae=_a ,scheduler=_a ) ldm.to(_a ) ldm.set_progress_bar_config(disable=_a ) _a : List[str] = torch.manual_seed(0 ) _a : List[str] = ldm(generator=_a ,num_inference_steps=2 ,output_type='numpy' ).images _a : List[str] = torch.manual_seed(0 ) _a : Union[str, Any] = ldm(generator=_a ,num_inference_steps=2 ,output_type='numpy' ,return_dict=_a )[0] _a : Tuple = image[0, -3:, -3:, -1] _a : Optional[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _a : int = np.array([0.8512, 0.818, 0.6411, 0.6808, 0.4465, 0.5618, 0.46, 0.6231, 0.5172] ) _a : Any = 1E-2 if torch_device != 'mps' else 3E-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < tolerance @slow @require_torch class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a : List[str] = LDMPipeline.from_pretrained('CompVis/ldm-celebahq-256' ) ldm.to(_a ) ldm.set_progress_bar_config(disable=_a ) _a : Optional[int] = torch.manual_seed(0 ) _a : Dict = ldm(generator=_a ,num_inference_steps=5 ,output_type='numpy' ).images _a : str = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) _a : Optional[int] = np.array([0.4399, 0.4_4975, 0.4_6825, 0.474, 0.4359, 0.4581, 0.4_5095, 0.4341, 0.4447] ) _a : int = 1E-2 if torch_device != 'mps' else 3E-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance
271
1
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = """▁""" __lowerCAmelCase = {"""vocab_file""": """sentencepiece.bpe.model""", """monolingual_vocab_file""": """dict.txt"""} __lowerCAmelCase = { """vocab_file""": { """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model""", }, """monolingual_vocab_file""": { """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt""", }, } __lowerCAmelCase = {"""vinai/bartpho-syllable""": 1_0_2_4} class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : Optional[Any] = VOCAB_FILES_NAMES __UpperCAmelCase : Dict = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Dict = ['''input_ids''', '''attention_mask'''] def __init__( self : str ,_a : str ,_a : Any ,_a : Any="<s>" ,_a : Dict="</s>" ,_a : int="</s>" ,_a : Union[str, Any]="<s>" ,_a : List[Any]="<unk>" ,_a : Optional[Any]="<pad>" ,_a : List[str]="<mask>" ,_a : Optional[Dict[str, Any]] = None ,**_a : int ,): '''simple docstring''' _a : Any = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else mask_token _a : Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_a ,eos_token=_a ,unk_token=_a ,sep_token=_a ,cls_token=_a ,pad_token=_a ,mask_token=_a ,sp_model_kwargs=self.sp_model_kwargs ,**_a ,) _a : Optional[int] = vocab_file _a : Union[str, Any] = monolingual_vocab_file _a : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_a ) ) # Load the reduced vocab # Keep order of special tokens for backward compatibility _a : Union[str, Any] = {} _a : int = 0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(_a ) not in self.fairseq_tokens_to_ids: _a : int = cnt cnt += 1 with open(_a ,'r' ,encoding='utf-8' ) as f: for line in f.readlines(): _a : str = line.strip().split()[0] _a : Tuple = len(self.fairseq_tokens_to_ids ) if str(_a ) not in self.fairseq_tokens_to_ids: _a : List[str] = len(self.fairseq_tokens_to_ids ) _a : Tuple = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : Union[str, Any] ): '''simple docstring''' _a : int = self.__dict__.copy() _a : str = None _a : Optional[Any] = self.sp_model.serialized_model_proto() return state def __setstate__( self : Tuple ,_a : Tuple ): '''simple docstring''' _a : Tuple = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs' ): _a : List[str] = {} _a : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def __lowercase ( self : Dict ,_a : List[int] ,_a : Optional[List[int]] = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _a : Dict = [self.cls_token_id] _a : int = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def __lowercase ( self : int ,_a : List[int] ,_a : Optional[List[int]] = None ,_a : bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a ,token_ids_a=_a ,already_has_special_tokens=_a ) if token_ids_a is None: return [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1, 1] + ([0] * len(_a )) + [1] def __lowercase ( self : Tuple ,_a : List[int] ,_a : Optional[List[int]] = None ): '''simple docstring''' _a : List[str] = [self.sep_token_id] _a : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def __lowercase ( self : Dict ): '''simple docstring''' return len(self.fairseq_ids_to_tokens ) def __lowercase ( self : Dict ): '''simple docstring''' _a : List[str] = {self.convert_ids_to_tokens(_a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __lowercase ( self : Tuple ,_a : str ): '''simple docstring''' return self.sp_model.encode(_a ,out_type=_a ) def __lowercase ( self : Union[str, Any] ,_a : Union[str, Any] ): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def __lowercase ( self : Any ,_a : int ): '''simple docstring''' return self.fairseq_ids_to_tokens[index] def __lowercase ( self : Tuple ,_a : Union[str, Any] ): '''simple docstring''' _a : str = ''.join(_a ).replace(_a ,' ' ).strip() return out_string def __lowercase ( self : Union[str, Any] ,_a : str ,_a : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(_a ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _a : int = os.path.join( _a ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) _a : int = os.path.join( _a ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['monolingual_vocab_file'] ,) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,_a ) elif not os.path.isfile(self.vocab_file ): with open(_a ,'wb' ) as fi: _a : List[Any] = self.sp_model.serialized_model_proto() fi.write(_a ) if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath( _a ) and os.path.isfile(self.monolingual_vocab_file ): copyfile(self.monolingual_vocab_file ,_a ) elif not os.path.isfile(self.monolingual_vocab_file ): with open(_a ,'w' ,encoding='utf-8' ) as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(F"""{str(_a )} \n""" ) return out_vocab_file, out_monolingual_vocab_file
271
'''simple docstring''' import warnings from ...utils import logging from .image_processing_beit import BeitImageProcessor __lowerCAmelCase = logging.get_logger(__name__) class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" def __init__( self : int ,*_a : Optional[int] ,**_a : str ): '''simple docstring''' warnings.warn( 'The class BeitFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use BeitImageProcessor instead.' ,_a ,) super().__init__(*_a ,**_a )
271
1
'''simple docstring''' from collections import namedtuple __lowerCAmelCase = namedtuple("""from_to""", """from_ to""") __lowerCAmelCase = { """cubicmeter""": from_to(1, 1), """litre""": from_to(0.001, 1_0_0_0), """kilolitre""": from_to(1, 1), """gallon""": from_to(0.00_454, 264.172), """cubicyard""": from_to(0.76_455, 1.30_795), """cubicfoot""": from_to(0.028, 35.3_147), """cup""": from_to(0.000_236_588, 4_226.75), } def UpperCAmelCase_ (__a : float , __a : str , __a : str ): """simple docstring""" if from_type not in METRIC_CONVERSION: raise ValueError( f"""Invalid 'from_type' value: {from_type!r} Supported values are:\n""" + ', '.join(__a ) ) if to_type not in METRIC_CONVERSION: raise ValueError( f"""Invalid 'to_type' value: {to_type!r}. Supported values are:\n""" + ', '.join(__a ) ) return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to if __name__ == "__main__": import doctest doctest.testmod()
271
'''simple docstring''' from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.utils.data import DistributedSampler, RandomSampler from transformers import PreTrainedModel, Trainer, logging from transformers.integrations import is_fairscale_available from transformers.models.fsmt.configuration_fsmt import FSMTConfig from transformers.optimization 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_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.trainer_pt_utils import get_tpu_sampler from transformers.training_args import ParallelMode from transformers.utils import is_torch_tpu_available if is_fairscale_available(): from fairscale.optim import OSS __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = { """linear""": get_linear_schedule_with_warmup, """cosine""": get_cosine_schedule_with_warmup, """cosine_w_restarts""": get_cosine_with_hard_restarts_schedule_with_warmup, """polynomial""": get_polynomial_decay_schedule_with_warmup, """constant""": get_constant_schedule, """constant_w_warmup""": get_constant_schedule_with_warmup, } class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" def __init__( self : Optional[int] ,_a : Optional[Any]=None ,_a : Dict=None ,*_a : int ,**_a : str ): '''simple docstring''' super().__init__(*_a ,**_a ) if config is None: assert isinstance(self.model ,_a ), ( "If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is" F""" {self.model.__class__}""" ) _a : List[Any] = self.model.config else: _a : Optional[int] = config _a : List[str] = data_args _a : List[Any] = self.config.tgt_vocab_size if isinstance(self.config ,_a ) else self.config.vocab_size if self.args.label_smoothing != 0 or (self.data_args is not None and self.data_args.ignore_pad_token_for_loss): assert self.config.pad_token_id is not None, ( "Make sure that `config.pad_token_id` is correcly defined when ignoring `pad_token` for loss" " calculation or doing label smoothing." ) if self.config.pad_token_id is None and self.config.eos_token_id is not None: logger.warning( F"""The `config.pad_token_id` is `None`. Using `config.eos_token_id` = {self.config.eos_token_id} for""" ' padding..' ) if self.args.label_smoothing == 0: _a : List[str] = torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id ) else: # dynamically import label_smoothed_nll_loss from utils import label_smoothed_nll_loss _a : Tuple = label_smoothed_nll_loss def __lowercase ( self : List[str] ,_a : int ): '''simple docstring''' if self.optimizer is None: _a : Union[str, Any] = ['bias', 'LayerNorm.weight'] _a : Tuple = [ { 'params': [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay )], 'weight_decay': self.args.weight_decay, }, { 'params': [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay )], 'weight_decay': 0.0, }, ] _a : Optional[int] = Adafactor if self.args.adafactor else AdamW if self.args.adafactor: _a : Any = Adafactor _a : Dict = {'scale_parameter': False, 'relative_step': False} else: _a : Union[str, Any] = AdamW _a : str = { 'betas': (self.args.adam_betaa, self.args.adam_betaa), 'eps': self.args.adam_epsilon, } _a : Union[str, Any] = self.args.learning_rate if self.sharded_ddp: _a : str = OSS( params=_a ,optim=_a ,**_a ,) else: _a : Tuple = optimizer_cls(_a ,**_a ) if self.lr_scheduler is None: _a : List[Any] = self._get_lr_scheduler(_a ) else: # ignoring --lr_scheduler logger.warning('scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored.' ) def __lowercase ( self : List[Any] ,_a : List[Any] ): '''simple docstring''' _a : str = arg_to_scheduler[self.args.lr_scheduler] if self.args.lr_scheduler == "constant": _a : int = schedule_func(self.optimizer ) elif self.args.lr_scheduler == "constant_w_warmup": _a : List[str] = schedule_func(self.optimizer ,num_warmup_steps=self.args.warmup_steps ) else: _a : Optional[int] = schedule_func( self.optimizer ,num_warmup_steps=self.args.warmup_steps ,num_training_steps=_a ) return scheduler def __lowercase ( self : Tuple ): '''simple docstring''' if isinstance(self.train_dataset ,torch.utils.data.IterableDataset ): return None elif is_torch_tpu_available(): return get_tpu_sampler(self.train_dataset ) else: if self.args.sortish_sampler: self.train_dataset.make_sortish_sampler( self.args.per_device_train_batch_size ,distributed=(self.args.parallel_mode == ParallelMode.DISTRIBUTED) ,) return ( RandomSampler(self.train_dataset ) if self.args.local_rank == -1 else DistributedSampler(self.train_dataset ) ) def __lowercase ( self : Dict ,_a : Dict ,_a : Any ,_a : Dict ): '''simple docstring''' if self.args.label_smoothing == 0: if self.data_args is not None and self.data_args.ignore_pad_token_for_loss: # force training to ignore pad token _a : List[Any] = model(**_a ,use_cache=_a )[0] _a : Union[str, Any] = self.loss_fn(logits.view(-1 ,logits.shape[-1] ) ,labels.view(-1 ) ) else: # compute usual loss via models _a, _a : Union[str, Any] = model(**_a ,labels=_a ,use_cache=_a )[:2] else: # compute label smoothed loss _a : List[Any] = model(**_a ,use_cache=_a )[0] _a : Any = torch.nn.functional.log_softmax(_a ,dim=-1 ) _a, _a : List[str] = self.loss_fn(_a ,_a ,self.args.label_smoothing ,ignore_index=self.config.pad_token_id ) return loss, logits def __lowercase ( self : Optional[int] ,_a : Union[str, Any] ,_a : List[Any] ): '''simple docstring''' _a : Optional[int] = inputs.pop('labels' ) _a, _a : int = self._compute_loss(_a ,_a ,_a ) return loss def __lowercase ( self : Optional[Any] ,_a : nn.Module ,_a : Dict[str, Union[torch.Tensor, Any]] ,_a : bool ,_a : Optional[List[str]] = None ,): '''simple docstring''' _a : int = self._prepare_inputs(_a ) _a : Any = { 'max_length': self.data_args.val_max_target_length if self.data_args is not None else self.config.max_length, 'num_beams': self.data_args.eval_beams if self.data_args is not None else self.config.num_beams, } if self.args.predict_with_generate and not self.args.prediction_loss_only: _a : int = self.model.generate( inputs['input_ids'] ,attention_mask=inputs['attention_mask'] ,**_a ,) # in case the batch is shorter than max length, the output should be padded if generated_tokens.shape[-1] < gen_kwargs["max_length"]: _a : int = self._pad_tensors_to_max_len(_a ,gen_kwargs['max_length'] ) _a : Union[str, Any] = inputs.pop('labels' ) with torch.no_grad(): # compute loss on predict data _a, _a : Optional[int] = self._compute_loss(_a ,_a ,_a ) _a : Optional[Any] = loss.mean().detach() if self.args.prediction_loss_only: return (loss, None, None) _a : Optional[Any] = generated_tokens if self.args.predict_with_generate else logits if labels.shape[-1] < gen_kwargs["max_length"]: _a : Dict = self._pad_tensors_to_max_len(_a ,gen_kwargs['max_length'] ) return (loss, logits, labels) def __lowercase ( self : str ,_a : Tuple ,_a : Tuple ): '''simple docstring''' _a : List[Any] = self.config.pad_token_id if self.config.pad_token_id is not None else self.config.eos_token_id if pad_token_id is None: raise ValueError( 'Make sure that either `config.pad_token_id` or `config.eos_token_id` is defined if tensor has to be' F""" padded to `max_length`={max_length}""" ) _a : int = pad_token_id * torch.ones( (tensor.shape[0], max_length) ,dtype=tensor.dtype ,device=tensor.device ) _a : Union[str, Any] = tensor return padded_tensor
271
1
'''simple docstring''' import math import os import unittest from transformers import MegatronBertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, ) class UpperCAmelCase__ : """simple docstring""" def __init__( self : Optional[Any] ,_a : List[str] ,_a : str=13 ,_a : List[Any]=7 ,_a : List[str]=True ,_a : Optional[int]=True ,_a : List[str]=True ,_a : Dict=True ,_a : Optional[Any]=99 ,_a : Any=64 ,_a : Optional[int]=32 ,_a : List[str]=5 ,_a : str=4 ,_a : Union[str, Any]=37 ,_a : Union[str, Any]="gelu" ,_a : Dict=0.1 ,_a : Optional[Any]=0.1 ,_a : Dict=512 ,_a : Union[str, Any]=16 ,_a : Optional[int]=2 ,_a : str=0.02 ,_a : Dict=3 ,_a : str=4 ,_a : Tuple=None ,): '''simple docstring''' _a : Optional[int] = parent _a : List[Any] = batch_size _a : Dict = seq_length _a : Any = is_training _a : Union[str, Any] = use_input_mask _a : Optional[int] = use_token_type_ids _a : Tuple = use_labels _a : Union[str, Any] = vocab_size _a : Dict = hidden_size _a : Union[str, Any] = embedding_size _a : List[Any] = num_hidden_layers _a : List[Any] = num_attention_heads _a : Union[str, Any] = intermediate_size _a : List[str] = hidden_act _a : Tuple = hidden_dropout_prob _a : str = attention_probs_dropout_prob _a : List[Any] = max_position_embeddings _a : List[str] = type_vocab_size _a : int = type_sequence_label_size _a : Union[str, Any] = initializer_range _a : List[Any] = num_labels _a : Any = num_choices _a : Optional[Any] = scope def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : List[str] = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) _a : List[Any] = None if self.use_input_mask: _a : List[Any] = random_attention_mask([self.batch_size, self.seq_length] ) _a : Optional[int] = None if self.use_token_type_ids: _a : int = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) _a : int = None _a : str = None _a : Optional[int] = None if self.use_labels: _a : Dict = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) _a : int = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) _a : str = ids_tensor([self.batch_size] ,self.num_choices ) _a : Dict = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowercase ( self : List[Any] ): '''simple docstring''' return MegatronBertConfig( 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 ,embedding_size=self.embedding_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=_a ,initializer_range=self.initializer_range ,) def __lowercase ( self : Tuple ,_a : int ,_a : str ,_a : str ,_a : Union[str, Any] ,_a : str ,_a : int ,_a : Any ): '''simple docstring''' _a : Union[str, Any] = MegatronBertModel(config=_a ) model.to(_a ) model.eval() _a : str = model(_a ,attention_mask=_a ,token_type_ids=_a ) _a : str = model(_a ,token_type_ids=_a ) _a : int = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape ,(self.batch_size, self.hidden_size) ) def __lowercase ( self : Union[str, Any] ,_a : Dict ,_a : str ,_a : int ,_a : str ,_a : Dict ,_a : Optional[Any] ,_a : str ): '''simple docstring''' _a : List[Any] = MegatronBertForMaskedLM(config=_a ) model.to(_a ) model.eval() _a : Dict = model(_a ,attention_mask=_a ,token_type_ids=_a ,labels=_a ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def __lowercase ( self : Optional[Any] ,_a : Union[str, Any] ,_a : Any ,_a : Optional[Any] ,_a : int ,_a : str ,_a : str ,_a : List[Any] ): '''simple docstring''' _a : Optional[Any] = MegatronBertForCausalLM(config=_a ) model.to(_a ) model.eval() _a : str = model(_a ,attention_mask=_a ,token_type_ids=_a ,labels=_a ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def __lowercase ( self : Any ,_a : List[str] ,_a : List[str] ,_a : List[str] ,_a : List[str] ,_a : List[str] ,_a : List[Any] ,_a : Tuple ): '''simple docstring''' _a : List[Any] = MegatronBertForNextSentencePrediction(config=_a ) model.to(_a ) model.eval() _a : List[str] = model( _a ,attention_mask=_a ,token_type_ids=_a ,labels=_a ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, 2) ) def __lowercase ( self : Tuple ,_a : List[str] ,_a : List[Any] ,_a : Any ,_a : List[str] ,_a : str ,_a : List[str] ,_a : Any ): '''simple docstring''' _a : str = MegatronBertForPreTraining(config=_a ) model.to(_a ) model.eval() _a : Optional[Any] = model( _a ,attention_mask=_a ,token_type_ids=_a ,labels=_a ,next_sentence_label=_a ,) self.parent.assertEqual(result.prediction_logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape ,(self.batch_size, 2) ) def __lowercase ( self : str ,_a : str ,_a : int ,_a : str ,_a : Union[str, Any] ,_a : Union[str, Any] ,_a : Optional[int] ,_a : Dict ): '''simple docstring''' _a : int = MegatronBertForQuestionAnswering(config=_a ) model.to(_a ) model.eval() _a : List[str] = model( _a ,attention_mask=_a ,token_type_ids=_a ,start_positions=_a ,end_positions=_a ,) self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) ) def __lowercase ( self : str ,_a : int ,_a : Dict ,_a : List[str] ,_a : Union[str, Any] ,_a : Tuple ,_a : Union[str, Any] ,_a : List[str] ): '''simple docstring''' _a : Union[str, Any] = self.num_labels _a : List[Any] = MegatronBertForSequenceClassification(_a ) model.to(_a ) model.eval() _a : Tuple = model(_a ,attention_mask=_a ,token_type_ids=_a ,labels=_a ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def __lowercase ( self : Tuple ,_a : Union[str, Any] ,_a : Dict ,_a : List[str] ,_a : Tuple ,_a : List[str] ,_a : Any ,_a : Optional[int] ): '''simple docstring''' _a : str = self.num_labels _a : Any = MegatronBertForTokenClassification(config=_a ) model.to(_a ) model.eval() _a : List[Any] = model(_a ,attention_mask=_a ,token_type_ids=_a ,labels=_a ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def __lowercase ( self : Any ,_a : Optional[int] ,_a : Optional[Any] ,_a : Dict ,_a : int ,_a : str ,_a : List[str] ,_a : Dict ): '''simple docstring''' _a : Union[str, Any] = self.num_choices _a : str = MegatronBertForMultipleChoice(config=_a ) model.to(_a ) model.eval() _a : int = input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() _a : List[str] = token_type_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() _a : Dict = input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() _a : Optional[int] = model( _a ,attention_mask=_a ,token_type_ids=_a ,labels=_a ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def __lowercase ( self : Dict ): '''simple docstring''' _a : Dict = self.prepare_config_and_inputs() ( ( _a ), ( _a ), ( _a ), ( _a ), ( _a ), ( _a ), ( _a ), ) : Union[str, Any] = config_and_inputs _a : Union[str, Any] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class UpperCAmelCase__ ( lowercase__ , lowercase__ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : str = ( ( MegatronBertModel, MegatronBertForMaskedLM, MegatronBertForCausalLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, ) if is_torch_available() else () ) __UpperCAmelCase : Tuple = ( { '''feature-extraction''': MegatronBertModel, '''fill-mask''': MegatronBertForMaskedLM, '''question-answering''': MegatronBertForQuestionAnswering, '''text-classification''': MegatronBertForSequenceClassification, '''text-generation''': MegatronBertForCausalLM, '''token-classification''': MegatronBertForTokenClassification, '''zero-shot''': MegatronBertForSequenceClassification, } if is_torch_available() else {} ) __UpperCAmelCase : List[Any] = True # test_resize_embeddings = False __UpperCAmelCase : List[Any] = False def __lowercase ( self : Any ,_a : List[Any] ,_a : List[str] ,_a : List[str]=False ): '''simple docstring''' _a : Dict = super()._prepare_for_class(_a ,_a ,return_labels=_a ) if return_labels: if model_class in get_values(_a ): _a : Dict = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) ,dtype=torch.long ,device=_a ) _a : Dict = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=_a ) return inputs_dict def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : Dict = MegatronBertModelTester(self ) _a : Any = ConfigTester(self ,config_class=_a ,hidden_size=37 ) def __lowercase ( self : str ): '''simple docstring''' self.config_tester.run_common_tests() def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_model(*_a ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_masked_lm(*_a ) def __lowercase ( self : int ): '''simple docstring''' _a : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*_a ) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*_a ) def __lowercase ( self : List[Any] ): '''simple docstring''' _a : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_pretraining(*_a ) def __lowercase ( self : Any ): '''simple docstring''' _a : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_question_answering(*_a ) def __lowercase ( self : Any ): '''simple docstring''' _a : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*_a ) def __lowercase ( self : List[str] ): '''simple docstring''' _a : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_token_classification(*_a ) def UpperCAmelCase_ (__a : Tuple ): """simple docstring""" return torch.tensor( __a , dtype=torch.long , device=__a , ) __lowerCAmelCase = 1e-4 @require_torch @require_sentencepiece @require_tokenizers class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" @slow @unittest.skip('Model is not available.' ) def __lowercase ( self : str ): '''simple docstring''' _a : int = 'nvidia/megatron-bert-uncased-345m' if "MYDIR" in os.environ: _a : Optional[int] = os.path.join(os.environ['MYDIR'] ,_a ) _a : List[Any] = MegatronBertModel.from_pretrained(_a ) model.to(_a ) model.half() _a : List[str] = _long_tensor([[101, 7110, 1005, 1056, 2023, 1_1333, 1_7413, 1029, 102]] ) with torch.no_grad(): _a : str = model(_a )[0] _a : Tuple = torch.Size((1, 9, 1024) ) self.assertEqual(output.shape ,_a ) _a : str = [-0.6040, -0.2517, -0.1025, 0.3420, -0.6758, -0.0017, -0.1089, -0.1990, 0.5728] for ii in range(3 ): for jj in range(3 ): _a : Optional[Any] = output[0, ii, jj] _a : Optional[int] = expected[3 * ii + jj] _a : Optional[Any] = 'ii={} jj={} a={} b={}'.format(_a ,_a ,_a ,_a ) self.assertTrue(math.isclose(_a ,_a ,rel_tol=_a ,abs_tol=_a ) ,msg=_a )
271
'''simple docstring''' import gzip import hashlib import json import multiprocessing import os import re import shutil import time from pathlib import Path import numpy as np from arguments import PreprocessingArguments from datasets import load_dataset from minhash_deduplication import deduplicate_dataset from transformers import AutoTokenizer, HfArgumentParser __lowerCAmelCase = re.compile(r"""\s+""") def UpperCAmelCase_ (__a : Any ): """simple docstring""" return {"hash": hashlib.mda(re.sub(__a , '' , example['content'] ).encode('utf-8' ) ).hexdigest()} def UpperCAmelCase_ (__a : str ): """simple docstring""" _a : List[str] = [len(__a ) for line in example['content'].splitlines()] return {"line_mean": np.mean(__a ), "line_max": max(__a )} def UpperCAmelCase_ (__a : str ): """simple docstring""" _a : Union[str, Any] = np.mean([c.isalnum() for c in example['content']] ) return {"alpha_frac": alpha_frac} def UpperCAmelCase_ (__a : Optional[int] , __a : Any ): """simple docstring""" if example["hash"] in uniques: uniques.remove(example['hash'] ) return True else: return False def UpperCAmelCase_ (__a : int , __a : Union[str, Any]=5 ): """simple docstring""" _a : Optional[int] = ['auto-generated', 'autogenerated', 'automatically generated'] _a : List[str] = example['content'].splitlines() for _, line in zip(range(__a ) , __a ): for keyword in keywords: if keyword in line.lower(): return {"autogenerated": True} else: return {"autogenerated": False} def UpperCAmelCase_ (__a : List[str] , __a : Dict=5 , __a : Tuple=0.05 ): """simple docstring""" _a : Optional[int] = ['unit tests', 'test file', 'configuration file'] _a : int = example['content'].splitlines() _a : int = 0 _a : Dict = 0 # first test for _, line in zip(range(__a ) , __a ): for keyword in keywords: if keyword in line.lower(): return {"config_or_test": True} # second test _a : int = example['content'].count('\n' ) _a : int = int(coeff * nlines ) for line in lines: count_config += line.lower().count('config' ) count_test += line.lower().count('test' ) if count_config > threshold or count_test > threshold: return {"config_or_test": True} return {"config_or_test": False} def UpperCAmelCase_ (__a : Optional[int] ): """simple docstring""" _a : List[str] = ['def ', 'class ', 'for ', 'while '] _a : str = example['content'].splitlines() for line in lines: for keyword in keywords: if keyword in line.lower(): return {"has_no_keywords": False} return {"has_no_keywords": True} def UpperCAmelCase_ (__a : int , __a : Any=4 ): """simple docstring""" _a : List[str] = example['content'].splitlines() _a : Dict = 0 for line in lines: counter += line.lower().count('=' ) if counter > minimum: return {"has_few_assignments": False} return {"has_few_assignments": True} def UpperCAmelCase_ (__a : str ): """simple docstring""" _a : Optional[Any] = tokenizer(example['content'] , truncation=__a )['input_ids'] _a : Optional[int] = len(example['content'] ) / len(__a ) return {"ratio": ratio} def UpperCAmelCase_ (__a : str ): """simple docstring""" _a : Dict = {} results.update(get_hash(__a ) ) results.update(line_stats(__a ) ) results.update(alpha_stats(__a ) ) results.update(char_token_ratio(__a ) ) results.update(is_autogenerated(__a ) ) results.update(is_config_or_test(__a ) ) results.update(has_no_keywords(__a ) ) results.update(has_few_assignments(__a ) ) return results def UpperCAmelCase_ (__a : Any , __a : Any , __a : str ): """simple docstring""" if not check_uniques(__a , __a ): return False elif example["autogenerated"]: return False elif example["line_max"] > args.line_max: return False elif example["line_mean"] > args.line_mean: return False elif example["alpha_frac"] < args.alpha_frac: return False elif example["ratio"] < args.min_token_ratio: return False elif example["config_or_test"] and np.random.rand() <= args.filter_proba: return False elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba: return False elif example["has_few_assignments"]: return False else: return True def UpperCAmelCase_ (__a : Union[str, Any] ): """simple docstring""" with open(__a , 'rb' ) as f_in: with gzip.open(str(__a ) + '.gz' , 'wb' , compresslevel=6 ) as f_out: shutil.copyfileobj(__a , __a ) os.unlink(__a ) # Settings __lowerCAmelCase = HfArgumentParser(PreprocessingArguments) __lowerCAmelCase = parser.parse_args() if args.num_workers is None: __lowerCAmelCase = multiprocessing.cpu_count() __lowerCAmelCase = AutoTokenizer.from_pretrained(args.tokenizer_dir) # Load dataset __lowerCAmelCase = time.time() __lowerCAmelCase = load_dataset(args.dataset_name, split="""train""") print(f'''Time to load dataset: {time.time()-t_start:.2f}''') # Run preprocessing __lowerCAmelCase = time.time() __lowerCAmelCase = ds.map(preprocess, num_proc=args.num_workers) print(f'''Time to preprocess dataset: {time.time()-t_start:.2f}''') # Deduplicate hashes __lowerCAmelCase = set(ds.unique("""hash""")) __lowerCAmelCase = len(uniques) / len(ds) print(f'''Fraction of duplicates: {1-frac:.2%}''') # Deduplicate data and apply heuristics __lowerCAmelCase = time.time() __lowerCAmelCase = ds.filter(filter, fn_kwargs={"""uniques""": uniques, """args""": args}) print(f'''Time to filter dataset: {time.time()-t_start:.2f}''') print(f'''Size of filtered dataset: {len(ds_filter)}''') # Deduplicate with minhash and jaccard similarity if args.near_deduplication: __lowerCAmelCase = time.time() __lowerCAmelCase , __lowerCAmelCase = deduplicate_dataset(ds_filter, args.jaccard_threshold) print(f'''Time to deduplicate dataset: {time.time()-t_start:.2f}''') print(f'''Size of deduplicate dataset: {len(ds_filter)}''') # Save data in batches of samples_per_file __lowerCAmelCase = Path(args.output_dir) output_dir.mkdir(exist_ok=True) # save duplicate_clusters in the output_dir as artifacts # not sure it is the right place the save it if args.near_deduplication: with open(output_dir / """duplicate_clusters.json""", """w""") as f: json.dump(duplicate_clusters, f) __lowerCAmelCase = output_dir / """data""" data_dir.mkdir(exist_ok=True) __lowerCAmelCase = time.time() for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)): __lowerCAmelCase = str(data_dir / f'''file-{file_number+1:012}.json''') __lowerCAmelCase = min(len(ds_filter), index + args.samples_per_file) ds_filter.select(list(range(index, end_index))).to_json(file_path) compress_file(file_path) print(f'''Time to save dataset: {time.time()-t_start:.2f}''')
271
1