code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
"""simple docstring""" from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> list[float]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = coefficient_matrix.shape SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE__ : Tuple = F'''Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if colsa != 1: SCREAMING_SNAKE_CASE__ : str = F'''Constant matrix must be nx1 but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if rowsa != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Coefficient and constant matrices dimensions must be nxn and nx1 but """ F'''received {rowsa}x{colsa} and {rowsa}x{colsa}''' ) raise ValueError(__lowerCAmelCase ) if len(__lowerCAmelCase ) != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Number of initial values must be equal to number of rows in coefficient """ F'''matrix but received {len(__lowerCAmelCase )} and {rowsa}''' ) raise ValueError(__lowerCAmelCase ) if iterations <= 0: raise ValueError("""Iterations must be at least 1""" ) SCREAMING_SNAKE_CASE__ : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = table.shape strictly_diagonally_dominant(__lowerCAmelCase ) # Iterates the whole matrix for given number of times for _ in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = [] for row in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = 0 for col in range(__lowerCAmelCase ): if col == row: SCREAMING_SNAKE_CASE__ : int = table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE__ : Any = (temp + val) / denom new_val.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = new_val return [float(__lowerCAmelCase ) for i in new_val] def _lowercase ( __lowerCAmelCase ) -> bool: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = table.shape SCREAMING_SNAKE_CASE__ : str = True for i in range(0 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("""Coefficient matrix is not strictly diagonally dominant""" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
680
"""simple docstring""" from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> list[float]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = coefficient_matrix.shape SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE__ : Tuple = F'''Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if colsa != 1: SCREAMING_SNAKE_CASE__ : str = F'''Constant matrix must be nx1 but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if rowsa != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Coefficient and constant matrices dimensions must be nxn and nx1 but """ F'''received {rowsa}x{colsa} and {rowsa}x{colsa}''' ) raise ValueError(__lowerCAmelCase ) if len(__lowerCAmelCase ) != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Number of initial values must be equal to number of rows in coefficient """ F'''matrix but received {len(__lowerCAmelCase )} and {rowsa}''' ) raise ValueError(__lowerCAmelCase ) if iterations <= 0: raise ValueError("""Iterations must be at least 1""" ) SCREAMING_SNAKE_CASE__ : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = table.shape strictly_diagonally_dominant(__lowerCAmelCase ) # Iterates the whole matrix for given number of times for _ in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = [] for row in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = 0 for col in range(__lowerCAmelCase ): if col == row: SCREAMING_SNAKE_CASE__ : int = table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE__ : Any = (temp + val) / denom new_val.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = new_val return [float(__lowerCAmelCase ) for i in new_val] def _lowercase ( __lowerCAmelCase ) -> bool: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = table.shape SCREAMING_SNAKE_CASE__ : str = True for i in range(0 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("""Coefficient matrix is not strictly diagonally dominant""" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
680
1
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> int: if not grid or not grid[0]: raise TypeError("""The grid does not contain the appropriate information""" ) for cell_n in range(1 , len(grid[0] ) ): grid[0][cell_n] += grid[0][cell_n - 1] SCREAMING_SNAKE_CASE__ : List[Any] = grid[0] for row_n in range(1 , len(__lowerCAmelCase ) ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = grid[row_n] SCREAMING_SNAKE_CASE__ : int = fill_row(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = grid[row_n] return grid[-1][-1] def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> list: current_row[0] += row_above[0] for cell_n in range(1 , len(__lowerCAmelCase ) ): current_row[cell_n] += min(current_row[cell_n - 1] , row_above[cell_n] ) return current_row if __name__ == "__main__": import doctest doctest.testmod()
680
"""simple docstring""" import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Union[str, Path]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = True _SCREAMING_SNAKE_CASE :Optional[int] = None _SCREAMING_SNAKE_CASE :int = 1 _SCREAMING_SNAKE_CASE :Optional[Union[str, bool]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None def _a ( self ) -> "DownloadConfig": """simple docstring""" return self.__class__(**{k: copy.deepcopy(_a ) for k, v in self.__dict__.items()} )
680
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a :str = logging.get_logger(__name__) a :Union[str, Any] = { "bigcode/gpt_bigcode-santacoder": "https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json", } class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Dict = """gpt_bigcode""" _SCREAMING_SNAKE_CASE :Union[str, Any] = ["""past_key_values"""] _SCREAMING_SNAKE_CASE :Any = { """hidden_size""": """n_embd""", """max_position_embeddings""": """n_positions""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self , _a=50_257 , _a=1_024 , _a=768 , _a=12 , _a=12 , _a=None , _a="gelu_pytorch_tanh" , _a=0.1 , _a=0.1 , _a=0.1 , _a=1E-5 , _a=0.02 , _a=True , _a=True , _a=50_256 , _a=50_256 , _a=True , _a=True , _a=True , **_a , ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = vocab_size SCREAMING_SNAKE_CASE__ : Optional[Any] = n_positions SCREAMING_SNAKE_CASE__ : List[str] = n_embd SCREAMING_SNAKE_CASE__ : Dict = n_layer SCREAMING_SNAKE_CASE__ : int = n_head SCREAMING_SNAKE_CASE__ : List[str] = n_inner SCREAMING_SNAKE_CASE__ : Any = activation_function SCREAMING_SNAKE_CASE__ : List[Any] = resid_pdrop SCREAMING_SNAKE_CASE__ : Optional[int] = embd_pdrop SCREAMING_SNAKE_CASE__ : Optional[int] = attn_pdrop SCREAMING_SNAKE_CASE__ : Optional[int] = layer_norm_epsilon SCREAMING_SNAKE_CASE__ : int = initializer_range SCREAMING_SNAKE_CASE__ : Optional[int] = scale_attn_weights SCREAMING_SNAKE_CASE__ : Dict = use_cache SCREAMING_SNAKE_CASE__ : Optional[int] = attention_softmax_in_fpaa SCREAMING_SNAKE_CASE__ : str = scale_attention_softmax_in_fpaa SCREAMING_SNAKE_CASE__ : Optional[int] = multi_query SCREAMING_SNAKE_CASE__ : Optional[Any] = bos_token_id SCREAMING_SNAKE_CASE__ : int = eos_token_id super().__init__(bos_token_id=_a , eos_token_id=_a , **_a )
680
"""simple docstring""" import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger a :Optional[Any] = "<<<<<<< This should probably be modified because it mentions: " a :Tuple = "=======\n>>>>>>>\n" a :str = [ "TextEncoderConfig", "ByteTextEncoder", "SubwordTextEncoder", "encoder_config", "maybe_build_from_corpus", "manual_dir", ] a :Union[str, Any] = [ # (pattern, replacement) # Order is important here for some replacements (r"tfds\.core", r"datasets"), (r"tf\.io\.gfile\.GFile", r"open"), (r"tf\.([\w\d]+)", r"datasets.Value('\1')"), (r"tfds\.features\.Text\(\)", r"datasets.Value('string')"), (r"tfds\.features\.Text\(", r"datasets.Value('string'),"), (r"features\s*=\s*tfds.features.FeaturesDict\(", r"features=datasets.Features("), (r"tfds\.features\.FeaturesDict\(", r"dict("), (r"The TensorFlow Datasets Authors", r"The TensorFlow Datasets Authors and the HuggingFace Datasets Authors"), (r"tfds\.", r"datasets."), (r"dl_manager\.manual_dir", r"self.config.data_dir"), (r"self\.builder_config", r"self.config"), ] def _lowercase ( __lowerCAmelCase ) -> int: return ConvertCommand(args.tfds_path , args.datasets_directory ) class __a (UpperCamelCase_): '''simple docstring''' @staticmethod def _a ( _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.add_parser( """convert""" , help="""Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.""" , ) train_parser.add_argument( """--tfds_path""" , type=_a , required=_a , help="""Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.""" , ) train_parser.add_argument( """--datasets_directory""" , type=_a , required=_a , help="""Path to the HuggingFace Datasets folder.""" ) train_parser.set_defaults(func=_a ) def __init__( self , _a , _a , *_a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = get_logger("""datasets-cli/converting""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tfds_path SCREAMING_SNAKE_CASE__ : List[Any] = datasets_directory def _a ( self ) -> List[str]: """simple docstring""" if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.abspath(self._tfds_path ) elif os.path.isfile(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Tuple = os.path.dirname(self._tfds_path ) else: raise ValueError("""--tfds_path is neither a directory nor a file. Please check path.""" ) SCREAMING_SNAKE_CASE__ : Dict = os.path.abspath(self._datasets_directory ) self._logger.info(f'''Converting datasets from {abs_tfds_path} to {abs_datasets_path}''' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : List[Any] = {} if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.listdir(_a ) else: SCREAMING_SNAKE_CASE__ : List[Any] = [os.path.basename(self._tfds_path )] for f_name in file_names: self._logger.info(f'''Looking at file {f_name}''' ) SCREAMING_SNAKE_CASE__ : int = os.path.join(_a , _a ) SCREAMING_SNAKE_CASE__ : Dict = os.path.join(_a , _a ) if not os.path.isfile(_a ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info("""Skipping file""" ) continue with open(_a , encoding="""utf-8""" ) as f: SCREAMING_SNAKE_CASE__ : List[str] = f.readlines() SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = False SCREAMING_SNAKE_CASE__ : Optional[int] = False SCREAMING_SNAKE_CASE__ : Dict = [] for line in lines: SCREAMING_SNAKE_CASE__ : List[str] = line # Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: SCREAMING_SNAKE_CASE__ : List[Any] = """import datasets\n""" elif "import tensorflow" in out_line: # order is important here SCREAMING_SNAKE_CASE__ : Optional[Any] = """""" continue elif "from absl import logging" in out_line: SCREAMING_SNAKE_CASE__ : Any = """from datasets import logging\n""" elif "getLogger" in out_line: SCREAMING_SNAKE_CASE__ : Optional[int] = out_line.replace("""getLogger""" , """get_logger""" ) elif any(expression in out_line for expression in TO_HIGHLIGHT ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Tuple = list(filter(lambda _a : e in out_line , _a ) ) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(_a ) + """\n""" ) out_lines.append(_a ) out_lines.append(_a ) continue else: for pattern, replacement in TO_CONVERT: SCREAMING_SNAKE_CASE__ : int = re.sub(_a , _a , _a ) # Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: SCREAMING_SNAKE_CASE__ : Dict = re.match(r"""from\stensorflow_datasets.*import\s([^\.\r\n]+)""" , _a ) tfds_imports.extend(imp.strip() for imp in match.group(1 ).split(""",""" ) ) SCREAMING_SNAKE_CASE__ : Dict = """from . import """ + match.group(1 ) # Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(f'''Error converting {out_line.strip()}''' ) if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line: SCREAMING_SNAKE_CASE__ : Union[str, Any] = True out_lines.append(_a ) if is_builder or "wmt" in f_name: # We create a new directory for each dataset SCREAMING_SNAKE_CASE__ : Union[str, Any] = f_name.replace(""".py""" , """""" ) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(_a , _a ) SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(_a , _a ) os.makedirs(_a , exist_ok=_a ) self._logger.info(f'''Adding directory {output_dir}''' ) imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} ) else: # Utilities will be moved at the end utils_files.append(_a ) if needs_manual_update: with_manual_update.append(_a ) with open(_a , """w""" , encoding="""utf-8""" ) as f: f.writelines(_a ) self._logger.info(f'''Converted in {output_file}''' ) for utils_file in utils_files: try: SCREAMING_SNAKE_CASE__ : str = os.path.basename(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = imports_to_builder_map[f_name.replace(""".py""" , """""" )] self._logger.info(f'''Moving {dest_folder} to {utils_file}''' ) shutil.copy(_a , _a ) except KeyError: self._logger.error(f'''Cannot find destination folder for {utils_file}. Please copy manually.''' ) if with_manual_update: for file_path in with_manual_update: self._logger.warning( f'''You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.''' )
680
1
"""simple docstring""" import gc import unittest import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DDPMScheduler, PriorTransformer, StableUnCLIPPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.testing_utils import enable_full_determinism, load_numpy, require_torch_gpu, slow, torch_device 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, assert_mean_pixel_difference, ) enable_full_determinism() class __a (UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :int = StableUnCLIPPipeline _SCREAMING_SNAKE_CASE :Tuple = TEXT_TO_IMAGE_PARAMS _SCREAMING_SNAKE_CASE :int = TEXT_TO_IMAGE_BATCH_PARAMS _SCREAMING_SNAKE_CASE :Tuple = TEXT_TO_IMAGE_IMAGE_PARAMS _SCREAMING_SNAKE_CASE :List[Any] = TEXT_TO_IMAGE_IMAGE_PARAMS # TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false _SCREAMING_SNAKE_CASE :List[Any] = False def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = 32 SCREAMING_SNAKE_CASE__ : int = embedder_hidden_size # prior components torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Any = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Dict = CLIPTextModelWithProjection( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=_a , projection_dim=_a , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : int = PriorTransformer( num_attention_heads=2 , attention_head_dim=12 , embedding_dim=_a , num_layers=1 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Any = DDPMScheduler( variance_type="""fixed_small_log""" , prediction_type="""sample""" , num_train_timesteps=1_000 , clip_sample=_a , clip_sample_range=5.0 , beta_schedule="""squaredcos_cap_v2""" , ) # regular denoising components torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Tuple = StableUnCLIPImageNormalizer(embedding_dim=_a ) SCREAMING_SNAKE_CASE__ : List[str] = DDPMScheduler(beta_schedule="""squaredcos_cap_v2""" ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[str] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=_a , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = UNetaDConditionModel( sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""CrossAttnDownBlock2D""", """DownBlock2D""") , up_block_types=("""UpBlock2D""", """CrossAttnUpBlock2D""") , block_out_channels=(32, 64) , attention_head_dim=(2, 4) , class_embed_type="""projection""" , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=_a , layers_per_block=1 , upcast_attention=_a , use_linear_projection=_a , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : int = DDIMScheduler( beta_schedule="""scaled_linear""" , beta_start=0.00_085 , beta_end=0.012 , prediction_type="""v_prediction""" , set_alpha_to_one=_a , steps_offset=1 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Any = AutoencoderKL() SCREAMING_SNAKE_CASE__ : Any = { # prior components """prior_tokenizer""": prior_tokenizer, """prior_text_encoder""": prior_text_encoder, """prior""": prior, """prior_scheduler""": prior_scheduler, # image noising components """image_normalizer""": image_normalizer, """image_noising_scheduler""": image_noising_scheduler, # regular denoising components """tokenizer""": tokenizer, """text_encoder""": text_encoder, """unet""": unet, """scheduler""": scheduler, """vae""": vae, } return components def _a ( self , _a , _a=0 ) -> Optional[int]: """simple docstring""" if str(_a ).startswith("""mps""" ): SCREAMING_SNAKE_CASE__ : List[Any] = torch.manual_seed(_a ) else: SCREAMING_SNAKE_CASE__ : Dict = torch.Generator(device=_a ).manual_seed(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """prior_num_inference_steps""": 2, """output_type""": """numpy""", } return inputs def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = torch_device == """cpu""" self._test_attention_slicing_forward_pass(test_max_difference=_a ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = torch_device in ["""cpu""", """mps"""] self._test_inference_batch_single_identical(test_max_difference=_a ) @slow @require_torch_gpu class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> str: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy""" ) SCREAMING_SNAKE_CASE__ : Dict = StableUnCLIPPipeline.from_pretrained("""fusing/stable-unclip-2-1-l""" , torch_dtype=torch.floataa ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE__ : Dict = torch.Generator(device="""cpu""" ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Dict = pipe("""anime turle""" , generator=_a , output_type="""np""" ) SCREAMING_SNAKE_CASE__ : int = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(_a , _a ) def _a ( self ) -> Union[str, Any]: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE__ : List[Any] = StableUnCLIPPipeline.from_pretrained("""fusing/stable-unclip-2-1-l""" , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE__ : int = pipe( """anime turtle""" , prior_num_inference_steps=2 , num_inference_steps=2 , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Tuple = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
680
"""simple docstring""" from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance a :str = 637_8137.0 a :Optional[Any] = 635_6752.31_4245 a :List[Any] = 6_378_137 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> float: SCREAMING_SNAKE_CASE__ : Dict = (AXIS_A - AXIS_B) / AXIS_A # Parametric latitudes # https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) # Compute central angle between two points # using haversine theta. sigma = haversine_distance / equatorial radius SCREAMING_SNAKE_CASE__ : Tuple = haversine_distance(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) / EQUATORIAL_RADIUS # Intermediate P and Q values SCREAMING_SNAKE_CASE__ : List[str] = (b_lata + b_lata) / 2 SCREAMING_SNAKE_CASE__ : Dict = (b_lata - b_lata) / 2 # Intermediate X value # X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2) SCREAMING_SNAKE_CASE__ : Tuple = (sin(__lowerCAmelCase ) ** 2) * (cos(__lowerCAmelCase ) ** 2) SCREAMING_SNAKE_CASE__ : str = cos(sigma / 2 ) ** 2 SCREAMING_SNAKE_CASE__ : List[str] = (sigma - sin(__lowerCAmelCase )) * (x_numerator / x_demonimator) # Intermediate Y value # Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2) SCREAMING_SNAKE_CASE__ : int = (cos(__lowerCAmelCase ) ** 2) * (sin(__lowerCAmelCase ) ** 2) SCREAMING_SNAKE_CASE__ : int = sin(sigma / 2 ) ** 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = (sigma + sin(__lowerCAmelCase )) * (y_numerator / y_denominator) return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value))) if __name__ == "__main__": import doctest doctest.testmod()
680
1
"""simple docstring""" import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class __a (unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = JukeboxTokenizer _SCREAMING_SNAKE_CASE :Dict = { """artist""": """Zac Brown Band""", """genres""": """Country""", """lyrics""": """I met a traveller from an antique land, Who said \"Two vast and trunkless legs of stone Stand in the desert. . . . Near them, on the sand, Half sunk a shattered visage lies, whose frown, And wrinkled lip, and sneer of cold command, Tell that its sculptor well those passions read Which yet survive, stamped on these lifeless things, The hand that mocked them, and the heart that fed; And on the pedestal, these words appear: My name is Ozymandias, King of Kings; Look on my Works, ye Mighty, and despair! Nothing beside remains. Round the decay Of that colossal Wreck, boundless and bare The lone and level sands stretch far away """, } @require_torch def _a ( self ) -> Optional[Any]: """simple docstring""" import torch SCREAMING_SNAKE_CASE__ : Optional[int] = JukeboxTokenizer.from_pretrained("""openai/jukebox-1b-lyrics""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer(**self.metas )["""input_ids"""] # fmt: off SCREAMING_SNAKE_CASE__ : Any = [ torch.tensor([[ 0, 0, 0, 7_169, 507, 9, 76, 39, 31, 46, 76, 27, 76, 46, 44, 27, 48, 31, 38, 38, 31, 44, 76, 32, 44, 41, 39, 76, 27, 40, 76, 27, 40, 46, 35, 43, 47, 31, 76, 38, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 41, 76, 45, 27, 35, 30, 76, 71, 20, 49, 41, 76, 48, 27, 45, 46, 76, 27, 40, 30, 76, 46, 44, 47, 40, 37, 38, 31, 45, 45, 76, 38, 31, 33, 45, 76, 41, 32, 76, 45, 46, 41, 40, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 19, 46, 27, 40, 30, 76, 35, 40, 76, 46, 34, 31, 76, 30, 31, 45, 31, 44, 46, 63, 76, 63, 76, 63, 76, 63, 76, 14, 31, 27, 44, 76, 46, 34, 31, 39, 64, 76, 41, 40, 76, 46, 34, 31, 76, 45, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 8, 27, 38, 32, 76, 45, 47, 40, 37, 76, 27, 76, 45, 34, 27, 46, 46, 31, 44, 31, 30, 76, 48, 35, 45, 27, 33, 31, 76, 38, 35, 31, 45, 64, 76, 49, 34, 41, 45, 31, 76, 32, 44, 41, 49, 40, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 49, 44, 35, 40, 37, 38, 31, 30, 76, 38, 35, 42, 64, 76, 27, 40, 30, 76, 45, 40, 31, 31, 44, 76, 41, 32, 76, 29, 41, 38, 30, 76, 29, 41, 39, 39, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 31, 38, 38, 76, 46, 34, 27, 46, 76, 35, 46, 45, 76, 45, 29, 47, 38, 42, 46, 41, 44, 76, 49, 31, 38, 38, 76, 46, 34, 41, 45, 31, 76, 42, 27, 45, 45, 35, 41, 40, 45, 76, 44, 31, 27, 30, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 35, 29, 34, 76, 51, 31, 46, 76, 45, 47, 44, 48, 35, 48, 31, 64, 76, 45, 46, 27, 39, 42, 31, 30, 76, 41, 40, 76, 46, 34, 31, 45, 31, 76, 38, 35, 32, 31, 38, 31, 45, 45, 76, 46, 34, 35, 40, 33, 45, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 34, 27, 40, 30, 76, 46, 34, 27, 46, 76, 39, 41, 29, 37, 31, 30, 76, 46, 34, 31, 39, 64, 76, 27, 40, 30, 76, 46, 34, 31, 76, 34, 31, 27, 44, 46, 76, 46, 34, 27, 46, 76, 32, 31, 30, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 41, 40, 76, 46, 34, 31, 76, 42, 31, 30, 31, 45, 46, 27, 38, 64, 76, 46, 34, 31, 45, 31, 76, 49, 41, 44, 30, 45, 76, 27, 42, 42, 31, 27, 44, 65, 78, 76, 76, 76, 76, 76, 76, 76, 76, 13, 51, 76, 40, 27, 39, 31, 76, 35, 45, 76, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 76, 11, 35, 40, 33, 76, 41, 32, 76, 11, 35, 40, 33, 45, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 12, 41, 41, 37, 76, 41, 40, 76, 39, 51, 76, 23, 41, 44, 37, 45, 64, 76, 51, 31, 76, 13, 35, 33, 34, 46, 51, 64, 76, 27, 40, 30, 76, 30, 31, 45, 42, 27, 35, 44, 67, 78, 76, 76, 76, 76, 76, 76, 76, 76, 14, 41, 46, 34, 35, 40, 33, 76, 28, 31, 45, 35, 30, 31, 76, 44, 31, 39, 27, 35, 40, 45, 63, 76, 18, 41, 47, 40, 30, 76, 46, 34, 31, 76, 30, 31, 29, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76, 15, 32, 76, 46, 34, 27, 46, 76, 29, 41, 38, 41, 45, 45, 27, 38, 76, 23, 44, 31, 29, 37, 64, 76, 28, 41, 47, 40, 30, 38, 31, 45, 45, 76, 27, 40, 30, 76, 28, 27, 44, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 38, 41, 40, 31, 76, 27, 40, 30, 76, 38, 31, 48, 31, 38, 76, 45, 27, 40, 30, 45, 76, 45, 46, 44, 31, 46, 29, 34, 76, 32, 27, 44, 76, 27, 49, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76]] ), torch.tensor([[0, 0, 0, 1_069, 11]] ), torch.tensor([[0, 0, 0, 1_069, 11]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) ) @require_torch def _a ( self ) -> int: """simple docstring""" import torch SCREAMING_SNAKE_CASE__ : Optional[Any] = JukeboxTokenizer.from_pretrained("""openai/jukebox-5b-lyrics""" ) SCREAMING_SNAKE_CASE__ : Any = tokenizer(**self.metas )["""input_ids"""] # fmt: off SCREAMING_SNAKE_CASE__ : Tuple = [ torch.tensor([[ 0, 0, 0, 1_069, 11, -1, -1, -1, -1, 9, 77, 39, 31, 46, 77, 27, 77, 46, 44, 27, 48, 31, 38, 38, 31, 44, 77, 32, 44, 41, 39, 77, 27, 40, 77, 27, 40, 46, 35, 43, 47, 31, 77, 38, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 41, 77, 45, 27, 35, 30, 77, 72, 20, 49, 41, 77, 48, 27, 45, 46, 77, 27, 40, 30, 77, 46, 44, 47, 40, 37, 38, 31, 45, 45, 77, 38, 31, 33, 45, 77, 41, 32, 77, 45, 46, 41, 40, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 19, 46, 27, 40, 30, 77, 35, 40, 77, 46, 34, 31, 77, 30, 31, 45, 31, 44, 46, 63, 77, 63, 77, 63, 77, 63, 77, 14, 31, 27, 44, 77, 46, 34, 31, 39, 64, 77, 41, 40, 77, 46, 34, 31, 77, 45, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 8, 27, 38, 32, 77, 45, 47, 40, 37, 77, 27, 77, 45, 34, 27, 46, 46, 31, 44, 31, 30, 77, 48, 35, 45, 27, 33, 31, 77, 38, 35, 31, 45, 64, 77, 49, 34, 41, 45, 31, 77, 32, 44, 41, 49, 40, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 49, 44, 35, 40, 37, 38, 31, 30, 77, 38, 35, 42, 64, 77, 27, 40, 30, 77, 45, 40, 31, 31, 44, 77, 41, 32, 77, 29, 41, 38, 30, 77, 29, 41, 39, 39, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 31, 38, 38, 77, 46, 34, 27, 46, 77, 35, 46, 45, 77, 45, 29, 47, 38, 42, 46, 41, 44, 77, 49, 31, 38, 38, 77, 46, 34, 41, 45, 31, 77, 42, 27, 45, 45, 35, 41, 40, 45, 77, 44, 31, 27, 30, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 35, 29, 34, 77, 51, 31, 46, 77, 45, 47, 44, 48, 35, 48, 31, 64, 77, 45, 46, 27, 39, 42, 31, 30, 77, 41, 40, 77, 46, 34, 31, 45, 31, 77, 38, 35, 32, 31, 38, 31, 45, 45, 77, 46, 34, 35, 40, 33, 45, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 34, 27, 40, 30, 77, 46, 34, 27, 46, 77, 39, 41, 29, 37, 31, 30, 77, 46, 34, 31, 39, 64, 77, 27, 40, 30, 77, 46, 34, 31, 77, 34, 31, 27, 44, 46, 77, 46, 34, 27, 46, 77, 32, 31, 30, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 41, 40, 77, 46, 34, 31, 77, 42, 31, 30, 31, 45, 46, 27, 38, 64, 77, 46, 34, 31, 45, 31, 77, 49, 41, 44, 30, 45, 77, 27, 42, 42, 31, 27, 44, 65, 79, 77, 77, 77, 77, 77, 77, 77, 77, 13, 51, 77, 40, 27, 39, 31, 77, 35, 45, 77, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 77, 11, 35, 40, 33, 77, 41, 32, 77, 11, 35, 40, 33, 45, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 12, 41, 41, 37, 77, 41, 40, 77, 39, 51, 77, 23, 41, 44, 37, 45, 64, 77, 51, 31, 77, 13, 35, 33, 34, 46, 51, 64, 77, 27, 40, 30, 77, 30, 31, 45, 42, 27, 35, 44, 67, 79, 77, 77, 77, 77, 77, 77, 77, 77, 14, 41, 46, 34, 35, 40, 33, 77, 28, 31, 45, 35, 30, 31, 77, 44, 31, 39, 27, 35, 40, 45, 63, 77, 18, 41, 47, 40, 30, 77, 46, 34, 31, 77, 30, 31, 29, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77, 15, 32, 77, 46, 34, 27, 46, 77, 29, 41, 38, 41, 45, 45, 27, 38, 77, 23, 44, 31, 29, 37, 64, 77, 28, 41, 47, 40, 30, 38, 31, 45, 45, 77, 27, 40, 30, 77, 28, 27, 44, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 38, 41, 40, 31, 77, 27, 40, 30, 77, 38, 31, 48, 31, 38, 77, 45, 27, 40, 30, 45, 77, 45, 46, 44, 31, 46, 29, 34, 77, 32, 27, 44, 77, 27, 49, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77]] ), torch.tensor([[0, 0, 0, 1_069, 11, -1, -1, -1, -1]] ), torch.tensor([[0, 0, 0, 1_069, 11, -1, -1, -1, -1]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) )
680
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision.transforms import functional as F from transformers import DetrImageProcessor, TableTransformerConfig, TableTransformerForObjectDetection from transformers.utils import logging logging.set_verbosity_info() a :Any = logging.get_logger(__name__) # here we list all keys to be renamed (original name on the left, our name on the right) a :str = [] for i in range(6): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (f'transformer.encoder.layers.{i}.self_attn.out_proj.weight', f'encoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (f'transformer.encoder.layers.{i}.self_attn.out_proj.bias', f'encoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append((f'transformer.encoder.layers.{i}.linear1.weight', f'encoder.layers.{i}.fc1.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.linear1.bias', f'encoder.layers.{i}.fc1.bias')) rename_keys.append((f'transformer.encoder.layers.{i}.linear2.weight', f'encoder.layers.{i}.fc2.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.linear2.bias', f'encoder.layers.{i}.fc2.bias')) rename_keys.append( (f'transformer.encoder.layers.{i}.norm1.weight', f'encoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((f'transformer.encoder.layers.{i}.norm1.bias', f'encoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append((f'transformer.encoder.layers.{i}.norm2.weight', f'encoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.norm2.bias', f'encoder.layers.{i}.final_layer_norm.bias')) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( (f'transformer.decoder.layers.{i}.self_attn.out_proj.weight', f'decoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (f'transformer.decoder.layers.{i}.self_attn.out_proj.bias', f'decoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append( ( f'transformer.decoder.layers.{i}.multihead_attn.out_proj.weight', f'decoder.layers.{i}.encoder_attn.out_proj.weight', ) ) rename_keys.append( ( f'transformer.decoder.layers.{i}.multihead_attn.out_proj.bias', f'decoder.layers.{i}.encoder_attn.out_proj.bias', ) ) rename_keys.append((f'transformer.decoder.layers.{i}.linear1.weight', f'decoder.layers.{i}.fc1.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.linear1.bias', f'decoder.layers.{i}.fc1.bias')) rename_keys.append((f'transformer.decoder.layers.{i}.linear2.weight', f'decoder.layers.{i}.fc2.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.linear2.bias', f'decoder.layers.{i}.fc2.bias')) rename_keys.append( (f'transformer.decoder.layers.{i}.norm1.weight', f'decoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((f'transformer.decoder.layers.{i}.norm1.bias', f'decoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append( (f'transformer.decoder.layers.{i}.norm2.weight', f'decoder.layers.{i}.encoder_attn_layer_norm.weight') ) rename_keys.append( (f'transformer.decoder.layers.{i}.norm2.bias', f'decoder.layers.{i}.encoder_attn_layer_norm.bias') ) rename_keys.append((f'transformer.decoder.layers.{i}.norm3.weight', f'decoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.norm3.bias', f'decoder.layers.{i}.final_layer_norm.bias')) # convolutional projection + query embeddings + layernorm of encoder + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ("input_proj.weight", "input_projection.weight"), ("input_proj.bias", "input_projection.bias"), ("query_embed.weight", "query_position_embeddings.weight"), ("transformer.encoder.norm.weight", "encoder.layernorm.weight"), ("transformer.encoder.norm.bias", "encoder.layernorm.bias"), ("transformer.decoder.norm.weight", "decoder.layernorm.weight"), ("transformer.decoder.norm.bias", "decoder.layernorm.bias"), ("class_embed.weight", "class_labels_classifier.weight"), ("class_embed.bias", "class_labels_classifier.bias"), ("bbox_embed.layers.0.weight", "bbox_predictor.layers.0.weight"), ("bbox_embed.layers.0.bias", "bbox_predictor.layers.0.bias"), ("bbox_embed.layers.1.weight", "bbox_predictor.layers.1.weight"), ("bbox_embed.layers.1.bias", "bbox_predictor.layers.1.bias"), ("bbox_embed.layers.2.weight", "bbox_predictor.layers.2.weight"), ("bbox_embed.layers.2.bias", "bbox_predictor.layers.2.bias"), ] ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Tuple = state_dict.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = val def _lowercase ( __lowerCAmelCase ) -> Tuple: SCREAMING_SNAKE_CASE__ : str = OrderedDict() for key, value in state_dict.items(): if "backbone.0.body" in key: SCREAMING_SNAKE_CASE__ : List[Any] = key.replace("""backbone.0.body""" , """backbone.conv_encoder.model""" ) SCREAMING_SNAKE_CASE__ : Dict = value else: SCREAMING_SNAKE_CASE__ : Tuple = value return new_state_dict def _lowercase ( __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : str = """""" # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : int = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : int = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE__ : Any = in_proj_bias[:256] SCREAMING_SNAKE_CASE__ : Dict = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[256:512] SCREAMING_SNAKE_CASE__ : int = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[-256:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6 ): # read in weights + bias of input projection layer of self-attention SCREAMING_SNAKE_CASE__ : List[str] = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : Tuple = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Any = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[:256] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[256:512] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias[-256:] # read in weights + bias of input projection layer of cross-attention SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop( F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : List[Any] = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) of cross-attention to the state dict SCREAMING_SNAKE_CASE__ : int = in_proj_weight_cross_attn[:256, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias_cross_attn[:256] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight_cross_attn[256:512, :] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_bias_cross_attn[256:512] SCREAMING_SNAKE_CASE__ : int = in_proj_weight_cross_attn[-256:, :] SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias_cross_attn[-256:] def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = image.size SCREAMING_SNAKE_CASE__ : Optional[Any] = max(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = 800 if """detection""" in checkpoint_url else 1000 SCREAMING_SNAKE_CASE__ : List[str] = target_max_size / current_max_size SCREAMING_SNAKE_CASE__ : str = image.resize((int(round(scale * width ) ), int(round(scale * height ) )) ) return resized_image def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[int] = F.to_tensor(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = F.normalize(__lowerCAmelCase , mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ) return image @torch.no_grad() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Optional[Any]: logger.info("""Converting model...""" ) # load original state dict SCREAMING_SNAKE_CASE__ : str = torch.hub.load_state_dict_from_url(__lowerCAmelCase , map_location="""cpu""" ) # rename keys for src, dest in rename_keys: rename_key(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = rename_backbone_keys(__lowerCAmelCase ) # query, key and value matrices need special treatment read_in_q_k_v(__lowerCAmelCase ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them SCREAMING_SNAKE_CASE__ : Optional[int] = """model.""" for key in state_dict.copy().keys(): if not key.startswith("""class_labels_classifier""" ) and not key.startswith("""bbox_predictor""" ): SCREAMING_SNAKE_CASE__ : Optional[int] = state_dict.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = val # create HuggingFace model and load state dict SCREAMING_SNAKE_CASE__ : Tuple = TableTransformerConfig( backbone="""resnet18""" , mask_loss_coefficient=1 , dice_loss_coefficient=1 , ce_loss_coefficient=1 , bbox_loss_coefficient=5 , giou_loss_coefficient=2 , eos_coefficient=0.4 , class_cost=1 , bbox_cost=5 , giou_cost=2 , ) if "detection" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] = 15 SCREAMING_SNAKE_CASE__ : Any = 2 SCREAMING_SNAKE_CASE__ : str = {0: """table""", 1: """table rotated"""} SCREAMING_SNAKE_CASE__ : Union[str, Any] = idalabel SCREAMING_SNAKE_CASE__ : List[str] = {v: k for k, v in idalabel.items()} else: SCREAMING_SNAKE_CASE__ : Tuple = 125 SCREAMING_SNAKE_CASE__ : str = 6 SCREAMING_SNAKE_CASE__ : List[Any] = { 0: """table""", 1: """table column""", 2: """table row""", 3: """table column header""", 4: """table projected row header""", 5: """table spanning cell""", } SCREAMING_SNAKE_CASE__ : Any = idalabel SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Dict = DetrImageProcessor( format="""coco_detection""" , max_size=800 if """detection""" in checkpoint_url else 1000 ) SCREAMING_SNAKE_CASE__ : Tuple = TableTransformerForObjectDetection(__lowerCAmelCase ) model.load_state_dict(__lowerCAmelCase ) model.eval() # verify our conversion SCREAMING_SNAKE_CASE__ : Dict = """example_pdf.png""" if """detection""" in checkpoint_url else """example_table.png""" SCREAMING_SNAKE_CASE__ : Tuple = hf_hub_download(repo_id="""nielsr/example-pdf""" , repo_type="""dataset""" , filename=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = Image.open(__lowerCAmelCase ).convert("""RGB""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = normalize(resize(__lowerCAmelCase , __lowerCAmelCase ) ).unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : Dict = model(__lowerCAmelCase ) if "detection" in checkpoint_url: SCREAMING_SNAKE_CASE__ : List[Any] = (1, 15, 3) SCREAMING_SNAKE_CASE__ : str = torch.tensor( [[-6.7_897, -16.9_985, 6.7_937], [-8.0_186, -22.2_192, 6.9_677], [-7.3_117, -21.0_708, 7.4_055]] ) SCREAMING_SNAKE_CASE__ : str = torch.tensor([[0.4_867, 0.1_767, 0.6_732], [0.6_718, 0.4_479, 0.3_830], [0.4_716, 0.1_760, 0.6_364]] ) else: SCREAMING_SNAKE_CASE__ : Dict = (1, 125, 7) SCREAMING_SNAKE_CASE__ : Any = torch.tensor( [[-18.1_430, -8.3_214, 4.8_274], [-18.4_685, -7.1_361, -4.2_667], [-26.3_693, -9.3_429, -4.9_962]] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([[0.4_983, 0.5_595, 0.9_440], [0.4_916, 0.6_315, 0.5_954], [0.6_108, 0.8_637, 0.1_135]] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(F'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(__lowerCAmelCase ).mkdir(exist_ok=__lowerCAmelCase ) model.save_pretrained(__lowerCAmelCase ) image_processor.save_pretrained(__lowerCAmelCase ) if push_to_hub: # Push model to HF hub logger.info("""Pushing model to the hub...""" ) SCREAMING_SNAKE_CASE__ : List[Any] = ( """microsoft/table-transformer-detection""" if """detection""" in checkpoint_url else """microsoft/table-transformer-structure-recognition""" ) model.push_to_hub(__lowerCAmelCase ) image_processor.push_to_hub(__lowerCAmelCase ) if __name__ == "__main__": a :Any = argparse.ArgumentParser() parser.add_argument( "--checkpoint_url", default="https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth", type=str, choices=[ "https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth", "https://pubtables1m.blob.core.windows.net/model/pubtables1m_structure_detr_r18.pth", ], help="URL of the Table Transformer checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) a :int = parser.parse_args() convert_table_transformer_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
680
1
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING a :Tuple = logging.get_logger(__name__) a :List[str] = { "ut/deta": "https://huggingface.co/ut/deta/resolve/main/config.json", } class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = """deta""" _SCREAMING_SNAKE_CASE :Dict = { """hidden_size""": """d_model""", """num_attention_heads""": """encoder_attention_heads""", } def __init__( self , _a=None , _a=900 , _a=2_048 , _a=6 , _a=2_048 , _a=8 , _a=6 , _a=1_024 , _a=8 , _a=0.0 , _a=True , _a="relu" , _a=256 , _a=0.1 , _a=0.0 , _a=0.0 , _a=0.02 , _a=1.0 , _a=True , _a=False , _a="sine" , _a=5 , _a=4 , _a=4 , _a=True , _a=300 , _a=True , _a=True , _a=1 , _a=5 , _a=2 , _a=1 , _a=1 , _a=5 , _a=2 , _a=0.1 , _a=0.25 , **_a , ) -> Dict: """simple docstring""" if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = CONFIG_MAPPING["""resnet"""](out_features=["""stage2""", """stage3""", """stage4"""] ) else: if isinstance(_a , _a ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = backbone_config.pop("""model_type""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE__ : Dict = config_class.from_dict(_a ) SCREAMING_SNAKE_CASE__ : Dict = backbone_config SCREAMING_SNAKE_CASE__ : str = num_queries SCREAMING_SNAKE_CASE__ : str = max_position_embeddings SCREAMING_SNAKE_CASE__ : Optional[int] = d_model SCREAMING_SNAKE_CASE__ : List[Any] = encoder_ffn_dim SCREAMING_SNAKE_CASE__ : Any = encoder_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = encoder_attention_heads SCREAMING_SNAKE_CASE__ : str = decoder_ffn_dim SCREAMING_SNAKE_CASE__ : Optional[Any] = decoder_layers SCREAMING_SNAKE_CASE__ : Dict = decoder_attention_heads SCREAMING_SNAKE_CASE__ : int = dropout SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_dropout SCREAMING_SNAKE_CASE__ : Dict = activation_dropout SCREAMING_SNAKE_CASE__ : int = activation_function SCREAMING_SNAKE_CASE__ : Any = init_std SCREAMING_SNAKE_CASE__ : int = init_xavier_std SCREAMING_SNAKE_CASE__ : Union[str, Any] = encoder_layerdrop SCREAMING_SNAKE_CASE__ : Optional[int] = auxiliary_loss SCREAMING_SNAKE_CASE__ : Optional[int] = position_embedding_type # deformable attributes SCREAMING_SNAKE_CASE__ : Optional[int] = num_feature_levels SCREAMING_SNAKE_CASE__ : Union[str, Any] = encoder_n_points SCREAMING_SNAKE_CASE__ : int = decoder_n_points SCREAMING_SNAKE_CASE__ : int = two_stage SCREAMING_SNAKE_CASE__ : Optional[Any] = two_stage_num_proposals SCREAMING_SNAKE_CASE__ : Union[str, Any] = with_box_refine SCREAMING_SNAKE_CASE__ : List[Any] = assign_first_stage if two_stage is True and with_box_refine is False: raise ValueError("""If two_stage is True, with_box_refine must be True.""" ) # Hungarian matcher SCREAMING_SNAKE_CASE__ : Dict = class_cost SCREAMING_SNAKE_CASE__ : Dict = bbox_cost SCREAMING_SNAKE_CASE__ : Optional[Any] = giou_cost # Loss coefficients SCREAMING_SNAKE_CASE__ : Union[str, Any] = mask_loss_coefficient SCREAMING_SNAKE_CASE__ : Union[str, Any] = dice_loss_coefficient SCREAMING_SNAKE_CASE__ : Optional[Any] = bbox_loss_coefficient SCREAMING_SNAKE_CASE__ : List[str] = giou_loss_coefficient SCREAMING_SNAKE_CASE__ : int = eos_coefficient SCREAMING_SNAKE_CASE__ : int = focal_alpha super().__init__(is_encoder_decoder=_a , **_a ) @property def _a ( self ) -> int: """simple docstring""" return self.encoder_attention_heads @property def _a ( self ) -> int: """simple docstring""" return self.d_model def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE__ : List[Any] = self.__class__.model_type return output
680
"""simple docstring""" from __future__ import annotations import unittest from transformers import 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, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers import ( TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, BertConfig, DPRConfig, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) class __a : '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=2 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , _a=0 , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : str = seq_length SCREAMING_SNAKE_CASE__ : List[str] = is_training SCREAMING_SNAKE_CASE__ : List[str] = use_input_mask SCREAMING_SNAKE_CASE__ : Dict = use_token_type_ids SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE__ : Dict = hidden_size SCREAMING_SNAKE_CASE__ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE__ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : str = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Any = type_vocab_size SCREAMING_SNAKE_CASE__ : int = type_sequence_label_size SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : Any = num_labels SCREAMING_SNAKE_CASE__ : Dict = num_choices SCREAMING_SNAKE_CASE__ : Any = scope SCREAMING_SNAKE_CASE__ : int = projection_dim def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : str = None if self.use_input_mask: # follow test_modeling_tf_ctrl.py SCREAMING_SNAKE_CASE__ : str = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : Any = BertConfig( 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 , ) SCREAMING_SNAKE_CASE__ : str = DPRConfig(projection_dim=self.projection_dim , **config.to_dict() ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRContextEncoder(config=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , attention_mask=_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : str = model(_a ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = TFDPRQuestionEncoder(config=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_a , attention_mask=_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : List[str] = model(_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(_a ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = TFDPRReader(config=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , attention_mask=_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) ) self.parent.assertEqual(result.relevance_logits.shape , (self.batch_size,) ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE__ : int = {"""input_ids""": input_ids} return config, inputs_dict @require_tf class __a (UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = ( ( TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) if is_tf_available() else () ) _SCREAMING_SNAKE_CASE :int = {"""feature-extraction""": TFDPRQuestionEncoder} if is_tf_available() else {} _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = False _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :Dict = False def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFDPRModelTester(self ) SCREAMING_SNAKE_CASE__ : List[str] = ConfigTester(self , config_class=_a , hidden_size=37 ) def _a ( self ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_context_encoder(*_a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_question_encoder(*_a ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_reader(*_a ) @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRContextEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[int] = TFDPRContextEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = TFDPRQuestionEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRReader.from_pretrained(_a ) self.assertIsNotNone(_a ) @require_tf class __a (unittest.TestCase): '''simple docstring''' @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFDPRQuestionEncoder.from_pretrained("""facebook/dpr-question_encoder-single-nq-base""" ) SCREAMING_SNAKE_CASE__ : List[Any] = tf.constant( [[101, 7_592, 1_010, 2_003, 2_026, 3_899, 10_140, 1_029, 102]] ) # [CLS] hello, is my dog cute? [SEP] SCREAMING_SNAKE_CASE__ : Tuple = model(_a )[0] # embedding shape = (1, 768) # compare the actual values for a slice. SCREAMING_SNAKE_CASE__ : Any = tf.constant( [ [ 0.03_236_253, 0.12_753_335, 0.16_818_509, 0.00_279_786, 0.3_896_933, 0.24_264_945, 0.2_178_971, -0.02_335_227, -0.08_481_959, -0.14_324_117, ] ] ) self.assertTrue(numpy.allclose(output[:, :10].numpy() , expected_slice.numpy() , atol=1E-4 ) )
680
1
"""simple docstring""" import pprint import requests a :List[str] = "https://zenquotes.io/api" def _lowercase ( ) -> list: return requests.get(API_ENDPOINT_URL + """/today""" ).json() def _lowercase ( ) -> list: return requests.get(API_ENDPOINT_URL + """/random""" ).json() if __name__ == "__main__": a :Dict = random_quotes() pprint.pprint(response)
680
"""simple docstring""" # DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion # and https://github.com/hojonathanho/diffusion import math from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.schedulers.scheduling_utils import SchedulerMixin from diffusers.utils import BaseOutput, deprecate @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :torch.FloatTensor _SCREAMING_SNAKE_CASE :Optional[torch.FloatTensor] = None def _lowercase ( __lowerCAmelCase , __lowerCAmelCase=0.999 , __lowerCAmelCase="cosine" , ) -> Union[str, Any]: if alpha_transform_type == "cosine": def alpha_bar_fn(__lowerCAmelCase ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(__lowerCAmelCase ): return math.exp(t * -12.0 ) else: raise ValueError(F'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) SCREAMING_SNAKE_CASE__ : List[Any] = [] for i in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = i / num_diffusion_timesteps SCREAMING_SNAKE_CASE__ : int = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(__lowerCAmelCase ) / alpha_bar_fn(__lowerCAmelCase ) , __lowerCAmelCase ) ) return torch.tensor(__lowerCAmelCase , dtype=torch.floataa ) class __a (UpperCamelCase_ , UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = 1 @register_to_config def __init__( self , _a = 1_000 , _a = 0.0_001 , _a = 0.02 , _a = "linear" , _a = None , _a = True , _a = True , _a = 0 , _a = "epsilon" , _a = 1.0 , **_a , ) -> Dict: """simple docstring""" if kwargs.get("""set_alpha_to_one""" , _a ) is not None: SCREAMING_SNAKE_CASE__ : Tuple = ( """The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead.""" ) deprecate("""set_alpha_to_one""" , """1.0.0""" , _a , standard_warn=_a ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs["""set_alpha_to_one"""] if trained_betas is not None: SCREAMING_SNAKE_CASE__ : Dict = torch.tensor(_a , dtype=torch.floataa ) elif beta_schedule == "linear": SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.linspace(_a , _a , _a , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. SCREAMING_SNAKE_CASE__ : Optional[int] = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , _a , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule SCREAMING_SNAKE_CASE__ : Tuple = betas_for_alpha_bar(_a ) else: raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = 1.0 - self.betas SCREAMING_SNAKE_CASE__ : List[Any] = torch.cumprod(self.alphas , dim=0 ) # At every step in inverted ddim, we are looking into the next alphas_cumprod # For the final step, there is no next alphas_cumprod, and the index is out of bounds # `set_alpha_to_zero` decides whether we set this parameter simply to zero # in this case, self.step() just output the predicted noise # or whether we use the final alpha of the "non-previous" one. SCREAMING_SNAKE_CASE__ : Any = torch.tensor(0.0 ) if set_alpha_to_zero else self.alphas_cumprod[-1] # standard deviation of the initial noise distribution SCREAMING_SNAKE_CASE__ : Tuple = 1.0 # setable values SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : List[str] = torch.from_numpy(np.arange(0 , _a ).copy().astype(np.intaa ) ) def _a ( self , _a , _a = None ) -> torch.FloatTensor: """simple docstring""" return sample def _a ( self , _a , _a = None ) -> Optional[int]: """simple docstring""" if num_inference_steps > self.config.num_train_timesteps: raise ValueError( f'''`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:''' f''' {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle''' f''' maximal {self.config.num_train_timesteps} timesteps.''' ) SCREAMING_SNAKE_CASE__ : List[str] = num_inference_steps SCREAMING_SNAKE_CASE__ : Optional[Any] = self.config.num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 SCREAMING_SNAKE_CASE__ : str = (np.arange(0 , _a ) * step_ratio).round().copy().astype(np.intaa ) SCREAMING_SNAKE_CASE__ : Tuple = torch.from_numpy(_a ).to(_a ) self.timesteps += self.config.steps_offset def _a ( self , _a , _a , _a , _a = 0.0 , _a = False , _a = None , _a = True , ) -> Union[DDIMSchedulerOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = timestep + self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas # change original implementation to exactly match noise levels for analogous forward process SCREAMING_SNAKE_CASE__ : Optional[int] = self.alphas_cumprod[timestep] SCREAMING_SNAKE_CASE__ : Optional[int] = ( self.alphas_cumprod[prev_timestep] if prev_timestep < self.config.num_train_timesteps else self.final_alpha_cumprod ) SCREAMING_SNAKE_CASE__ : Any = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf if self.config.prediction_type == "epsilon": SCREAMING_SNAKE_CASE__ : int = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 SCREAMING_SNAKE_CASE__ : List[Any] = model_output elif self.config.prediction_type == "sample": SCREAMING_SNAKE_CASE__ : Dict = model_output SCREAMING_SNAKE_CASE__ : int = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 elif self.config.prediction_type == "v_prediction": SCREAMING_SNAKE_CASE__ : Dict = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output SCREAMING_SNAKE_CASE__ : str = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or''' """ `v_prediction`""" ) # 4. Clip or threshold "predicted x_0" if self.config.clip_sample: SCREAMING_SNAKE_CASE__ : Tuple = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : Any = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : Dict = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if not return_dict: return (prev_sample, pred_original_sample) return DDIMSchedulerOutput(prev_sample=_a , pred_original_sample=_a ) def __len__( self ) -> Dict: """simple docstring""" return self.config.num_train_timesteps
680
1
"""simple docstring""" def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> list[int]: SCREAMING_SNAKE_CASE__ : str = int(__lowerCAmelCase ) # Initialize Result SCREAMING_SNAKE_CASE__ : int = [] # Traverse through all denomination for denomination in reversed(__lowerCAmelCase ): # Find denominations while int(__lowerCAmelCase ) >= int(__lowerCAmelCase ): total_value -= int(__lowerCAmelCase ) answer.append(__lowerCAmelCase ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": a :Any = [] a :str = "0" if ( input("Do you want to enter your denominations ? (yY/n): ").strip().lower() == "y" ): a :str = int(input("Enter the number of denominations you want to add: ").strip()) for i in range(0, n): denominations.append(int(input(f'Denomination {i}: ').strip())) a :str = input("Enter the change you want to make in Indian Currency: ").strip() else: # All denominations of Indian Currency if user does not enter a :int = [1, 2, 5, 10, 20, 50, 100, 500, 2_000] a :List[Any] = input("Enter the change you want to make: ").strip() if int(value) == 0 or int(value) < 0: print("The total value cannot be zero or negative.") else: print(f'Following is minimal change for {value}: ') a :Optional[Any] = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=" ")
680
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) a :Union[str, Any] = { "configuration_speecht5": [ "SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP", "SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP", "SpeechT5Config", "SpeechT5HifiGanConfig", ], "feature_extraction_speecht5": ["SpeechT5FeatureExtractor"], "processing_speecht5": ["SpeechT5Processor"], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = ["SpeechT5Tokenizer"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST", "SpeechT5ForSpeechToText", "SpeechT5ForSpeechToSpeech", "SpeechT5ForTextToSpeech", "SpeechT5Model", "SpeechT5PreTrainedModel", "SpeechT5HifiGan", ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys a :Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
1
"""simple docstring""" import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand if not is_tf_available() and not is_torch_available(): raise RuntimeError("At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training") # TF training parameters a :Dict = False a :Optional[int] = False def _lowercase ( __lowerCAmelCase ) -> str: return TrainCommand(__lowerCAmelCase ) class __a (UpperCamelCase_): '''simple docstring''' @staticmethod def _a ( _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = parser.add_parser("""train""" , help="""CLI tool to train a model on a task.""" ) train_parser.add_argument( """--train_data""" , type=_a , required=_a , help="""path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences.""" , ) train_parser.add_argument( """--column_label""" , type=_a , default=0 , help="""Column of the dataset csv file with example labels.""" ) train_parser.add_argument( """--column_text""" , type=_a , default=1 , help="""Column of the dataset csv file with example texts.""" ) train_parser.add_argument( """--column_id""" , type=_a , default=2 , help="""Column of the dataset csv file with example ids.""" ) train_parser.add_argument( """--skip_first_row""" , action="""store_true""" , help="""Skip the first row of the csv file (headers).""" ) train_parser.add_argument("""--validation_data""" , type=_a , default="""""" , help="""path to validation dataset.""" ) train_parser.add_argument( """--validation_split""" , type=_a , default=0.1 , help="""if validation dataset is not provided, fraction of train dataset to use as validation dataset.""" , ) train_parser.add_argument("""--output""" , type=_a , default="""./""" , help="""path to saved the trained model.""" ) train_parser.add_argument( """--task""" , type=_a , default="""text_classification""" , help="""Task to train the model on.""" ) train_parser.add_argument( """--model""" , type=_a , default="""bert-base-uncased""" , help="""Model's name or path to stored model.""" ) train_parser.add_argument("""--train_batch_size""" , type=_a , default=32 , help="""Batch size for training.""" ) train_parser.add_argument("""--valid_batch_size""" , type=_a , default=64 , help="""Batch size for validation.""" ) train_parser.add_argument("""--learning_rate""" , type=_a , default=3E-5 , help="""Learning rate.""" ) train_parser.add_argument("""--adam_epsilon""" , type=_a , default=1E-0_8 , help="""Epsilon for Adam optimizer.""" ) train_parser.set_defaults(func=_a ) def __init__( self , _a ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = logging.get_logger("""transformers-cli/training""" ) SCREAMING_SNAKE_CASE__ : List[str] = """tf""" if is_tf_available() else """torch""" os.makedirs(args.output , exist_ok=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = args.output SCREAMING_SNAKE_CASE__ : Tuple = args.column_label SCREAMING_SNAKE_CASE__ : int = args.column_text SCREAMING_SNAKE_CASE__ : List[Any] = args.column_id self.logger.info(f'''Loading {args.task} pipeline for {args.model}''' ) if args.task == "text_classification": SCREAMING_SNAKE_CASE__ : int = TextClassificationPipeline.from_pretrained(args.model ) elif args.task == "token_classification": raise NotImplementedError elif args.task == "question_answering": raise NotImplementedError self.logger.info(f'''Loading dataset from {args.train_data}''' ) SCREAMING_SNAKE_CASE__ : List[Any] = Processor.create_from_csv( args.train_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) SCREAMING_SNAKE_CASE__ : List[Any] = None if args.validation_data: self.logger.info(f'''Loading validation dataset from {args.validation_data}''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = Processor.create_from_csv( args.validation_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = args.validation_split SCREAMING_SNAKE_CASE__ : Union[str, Any] = args.train_batch_size SCREAMING_SNAKE_CASE__ : List[str] = args.valid_batch_size SCREAMING_SNAKE_CASE__ : Optional[Any] = args.learning_rate SCREAMING_SNAKE_CASE__ : Optional[int] = args.adam_epsilon def _a ( self ) -> Any: """simple docstring""" if self.framework == "tf": return self.run_tf() return self.run_torch() def _a ( self ) -> Dict: """simple docstring""" raise NotImplementedError def _a ( self ) -> Any: """simple docstring""" self.pipeline.fit( self.train_dataset , validation_data=self.valid_dataset , validation_split=self.validation_split , learning_rate=self.learning_rate , adam_epsilon=self.adam_epsilon , train_batch_size=self.train_batch_size , valid_batch_size=self.valid_batch_size , ) # Save trained pipeline self.pipeline.save_pretrained(self.output )
680
"""simple docstring""" import math import os import sys def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Union[str, Any] = """""" try: with open(__lowerCAmelCase , """rb""" ) as binary_file: SCREAMING_SNAKE_CASE__ : Optional[int] = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Dict = F'''{dat:08b}''' result += curr_byte return result except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> None: lexicon.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = last_match_id if math.loga(__lowerCAmelCase ).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE__ : Dict = """0""" + lexicon[curr_key] SCREAMING_SNAKE_CASE__ : str = bin(__lowerCAmelCase )[2:] def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Dict = {"""0""": """0""", """1""": """1"""} SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = """""", """""" SCREAMING_SNAKE_CASE__ : Any = len(__lowerCAmelCase ) for i in range(len(__lowerCAmelCase ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon[curr_string] result += last_match_id add_key_to_lexicon(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) index += 1 SCREAMING_SNAKE_CASE__ : List[str] = """""" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE__ : List[Any] = lexicon[curr_string] result += last_match_id return result def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Any = os.path.getsize(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = bin(__lowerCAmelCase )[2:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = len(__lowerCAmelCase ) return "0" * (length_length - 1) + file_length_binary + compressed def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Optional[int] = 8 try: with open(__lowerCAmelCase , """wb""" ) as opened_file: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ to_write[i : i + byte_length] for i in range(0 , len(__lowerCAmelCase ) , __lowerCAmelCase ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("""10000000""" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(__lowerCAmelCase , 2 ).to_bytes(1 , byteorder="""big""" ) ) except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Dict = read_file_binary(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = compress_data(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = add_file_length(__lowerCAmelCase , __lowerCAmelCase ) write_file_binary(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
680
1
"""simple docstring""" import pytest import datasets.config from datasets.utils.info_utils import is_small_dataset @pytest.mark.parametrize("""dataset_size""" , [None, 400 * 2**20, 600 * 2**20] ) @pytest.mark.parametrize("""input_in_memory_max_size""" , ["""default""", 0, 100 * 2**20, 900 * 2**20] ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Dict: if input_in_memory_max_size != "default": monkeypatch.setattr(datasets.config , """IN_MEMORY_MAX_SIZE""" , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = datasets.config.IN_MEMORY_MAX_SIZE if input_in_memory_max_size == "default": assert in_memory_max_size == 0 else: assert in_memory_max_size == input_in_memory_max_size if dataset_size and in_memory_max_size: SCREAMING_SNAKE_CASE__ : Tuple = dataset_size < in_memory_max_size else: SCREAMING_SNAKE_CASE__ : str = False SCREAMING_SNAKE_CASE__ : str = is_small_dataset(__lowerCAmelCase ) assert result == expected
680
"""simple docstring""" import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Tuple = SamImageProcessor() SCREAMING_SNAKE_CASE__ : List[str] = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> Union[str, Any]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> Tuple: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Tuple = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Dict = processor(images=_a , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_torch def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [torch.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : str = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : List[Any] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : Any = processor.post_process_masks(_a , _a , _a ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Dict = processor.post_process_masks( _a , torch.tensor(_a ) , torch.tensor(_a ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np SCREAMING_SNAKE_CASE__ : Dict = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks(_a , np.array(_a ) , np.array(_a ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Dict = [[1, 0], [0, 1]] with self.assertRaises(_a ): SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks(_a , np.array(_a ) , np.array(_a ) ) @require_vision @require_tf class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Optional[int] = SamImageProcessor() SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> List[str]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> int: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Any = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : int = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Tuple = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Any = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Any = processor(images=_a , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_tf def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Union[str, Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [tf.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Optional[int] = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks(_a , _a , _a , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks( _a , tf.convert_to_tensor(_a ) , tf.convert_to_tensor(_a ) , return_tensors="""tf""" , ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np SCREAMING_SNAKE_CASE__ : Optional[int] = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks( _a , np.array(_a ) , np.array(_a ) , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Any = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): SCREAMING_SNAKE_CASE__ : str = processor.post_process_masks( _a , np.array(_a ) , np.array(_a ) , return_tensors="""tf""" ) @require_vision @require_torchvision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Dict = SamImageProcessor() SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> Any: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> Union[str, Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : int = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : List[Any] = [tf.convert_to_tensor(_a )] SCREAMING_SNAKE_CASE__ : Dict = [torch.tensor(_a )] SCREAMING_SNAKE_CASE__ : Optional[int] = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : List[str] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : List[Any] = processor.post_process_masks( _a , _a , _a , return_tensors="""tf""" ) SCREAMING_SNAKE_CASE__ : List[str] = processor.post_process_masks( _a , _a , _a , return_tensors="""pt""" ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : str = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : int = image_processor(_a , return_tensors="""pt""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : Any = processor(images=_a , return_tensors="""pt""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor(_a , return_tensors="""tf""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : str = processor(images=_a , return_tensors="""tf""" )["""pixel_values"""].numpy() self.assertTrue(np.allclose(_a , _a ) ) self.assertTrue(np.allclose(_a , _a ) ) self.assertTrue(np.allclose(_a , _a ) )
680
1
"""simple docstring""" from typing import Callable, List, Optional, Tuple, Union import torch from transformers import CLIPTextModel, CLIPTokenizer from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin, TransformeraDModel, VQModel from ...schedulers import VQDiffusionScheduler from ...utils import logging from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput a :int = logging.get_logger(__name__) # pylint: disable=invalid-name class __a (UpperCamelCase_ , UpperCamelCase_): '''simple docstring''' @register_to_config def __init__( self , _a , _a = None , _a = None ) -> Union[str, Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Any = learnable if self.learnable: assert hidden_size is not None, "learnable=True requires `hidden_size` to be set" assert length is not None, "learnable=True requires `length` to be set" SCREAMING_SNAKE_CASE__ : int = torch.zeros(_a , _a ) else: SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : Tuple = torch.nn.Parameter(_a ) class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :VQModel _SCREAMING_SNAKE_CASE :CLIPTextModel _SCREAMING_SNAKE_CASE :CLIPTokenizer _SCREAMING_SNAKE_CASE :TransformeraDModel _SCREAMING_SNAKE_CASE :LearnedClassifierFreeSamplingEmbeddings _SCREAMING_SNAKE_CASE :VQDiffusionScheduler def __init__( self , _a , _a , _a , _a , _a , _a , ) -> Dict: """simple docstring""" super().__init__() self.register_modules( vqvae=_a , transformer=_a , text_encoder=_a , tokenizer=_a , scheduler=_a , learned_classifier_free_sampling_embeddings=_a , ) def _a ( self , _a , _a , _a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = len(_a ) if isinstance(_a , _a ) else 1 # get prompt text embeddings SCREAMING_SNAKE_CASE__ : str = self.tokenizer( _a , padding="""max_length""" , max_length=self.tokenizer.model_max_length , return_tensors="""pt""" , ) SCREAMING_SNAKE_CASE__ : Optional[int] = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: SCREAMING_SNAKE_CASE__ : List[Any] = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( """The following part of your input was truncated because CLIP can only handle sequences up to""" f''' {self.tokenizer.model_max_length} tokens: {removed_text}''' ) SCREAMING_SNAKE_CASE__ : Dict = text_input_ids[:, : self.tokenizer.model_max_length] SCREAMING_SNAKE_CASE__ : Tuple = self.text_encoder(text_input_ids.to(self.device ) )[0] # NOTE: This additional step of normalizing the text embeddings is from VQ-Diffusion. # While CLIP does normalize the pooled output of the text transformer when combining # the image and text embeddings, CLIP does not directly normalize the last hidden state. # # CLIP normalizing the pooled output. # https://github.com/huggingface/transformers/blob/d92e22d1f28324f513f3080e5c47c071a3916721/src/transformers/models/clip/modeling_clip.py#L1052-L1053 SCREAMING_SNAKE_CASE__ : List[str] = prompt_embeds / prompt_embeds.norm(dim=-1 , keepdim=_a ) # duplicate text embeddings for each generation per prompt SCREAMING_SNAKE_CASE__ : Dict = prompt_embeds.repeat_interleave(_a , dim=0 ) if do_classifier_free_guidance: if self.learned_classifier_free_sampling_embeddings.learnable: SCREAMING_SNAKE_CASE__ : str = self.learned_classifier_free_sampling_embeddings.embeddings SCREAMING_SNAKE_CASE__ : str = negative_prompt_embeds.unsqueeze(0 ).repeat(_a , 1 , 1 ) else: SCREAMING_SNAKE_CASE__ : List[Any] = [""""""] * batch_size SCREAMING_SNAKE_CASE__ : Dict = text_input_ids.shape[-1] SCREAMING_SNAKE_CASE__ : List[Any] = self.tokenizer( _a , padding="""max_length""" , max_length=_a , truncation=_a , return_tensors="""pt""" , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # See comment for normalizing text embeddings SCREAMING_SNAKE_CASE__ : Any = negative_prompt_embeds / negative_prompt_embeds.norm(dim=-1 , keepdim=_a ) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method SCREAMING_SNAKE_CASE__ : int = negative_prompt_embeds.shape[1] SCREAMING_SNAKE_CASE__ : int = negative_prompt_embeds.repeat(1 , _a , 1 ) SCREAMING_SNAKE_CASE__ : Any = negative_prompt_embeds.view(batch_size * num_images_per_prompt , _a , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([negative_prompt_embeds, prompt_embeds] ) return prompt_embeds @torch.no_grad() def __call__( self , _a , _a = 100 , _a = 5.0 , _a = 1.0 , _a = 1 , _a = None , _a = None , _a = "pil" , _a = True , _a = None , _a = 1 , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" if isinstance(_a , _a ): SCREAMING_SNAKE_CASE__ : Optional[int] = 1 elif isinstance(_a , _a ): SCREAMING_SNAKE_CASE__ : Optional[Any] = len(_a ) else: raise ValueError(f'''`prompt` has to be of type `str` or `list` but is {type(_a )}''' ) SCREAMING_SNAKE_CASE__ : Any = batch_size * num_images_per_prompt SCREAMING_SNAKE_CASE__ : Optional[Any] = guidance_scale > 1.0 SCREAMING_SNAKE_CASE__ : Any = self._encode_prompt(_a , _a , _a ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(_a , _a ) or callback_steps <= 0) ): raise ValueError( f'''`callback_steps` has to be a positive integer but is {callback_steps} of type''' f''' {type(_a )}.''' ) # get the initial completely masked latents unless the user supplied it SCREAMING_SNAKE_CASE__ : Optional[int] = (batch_size, self.transformer.num_latent_pixels) if latents is None: SCREAMING_SNAKE_CASE__ : List[Any] = self.transformer.num_vector_embeds - 1 SCREAMING_SNAKE_CASE__ : Tuple = torch.full(_a , _a ).to(self.device ) else: if latents.shape != latents_shape: raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''' ) if (latents < 0).any() or (latents >= self.transformer.num_vector_embeds).any(): raise ValueError( """Unexpected latents value(s). All latents be valid embedding indices i.e. in the range 0,""" f''' {self.transformer.num_vector_embeds - 1} (inclusive).''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = latents.to(self.device ) # set timesteps self.scheduler.set_timesteps(_a , device=self.device ) SCREAMING_SNAKE_CASE__ : Dict = self.scheduler.timesteps.to(self.device ) SCREAMING_SNAKE_CASE__ : Optional[int] = latents for i, t in enumerate(self.progress_bar(_a ) ): # expand the sample if we are doing classifier free guidance SCREAMING_SNAKE_CASE__ : List[str] = torch.cat([sample] * 2 ) if do_classifier_free_guidance else sample # predict the un-noised image # model_output == `log_p_x_0` SCREAMING_SNAKE_CASE__ : str = self.transformer(_a , encoder_hidden_states=_a , timestep=_a ).sample if do_classifier_free_guidance: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = model_output.chunk(2 ) SCREAMING_SNAKE_CASE__ : Tuple = model_output_uncond + guidance_scale * (model_output_text - model_output_uncond) model_output -= torch.logsumexp(_a , dim=1 , keepdim=_a ) SCREAMING_SNAKE_CASE__ : str = self.truncate(_a , _a ) # remove `log(0)`'s (`-inf`s) SCREAMING_SNAKE_CASE__ : Any = model_output.clamp(-70 ) # compute the previous noisy sample x_t -> x_t-1 SCREAMING_SNAKE_CASE__ : List[str] = self.scheduler.step(_a , timestep=_a , sample=_a , generator=_a ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(_a , _a , _a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.vqvae.config.vq_embed_dim SCREAMING_SNAKE_CASE__ : List[str] = (batch_size, self.transformer.height, self.transformer.width, embedding_channels) SCREAMING_SNAKE_CASE__ : Dict = self.vqvae.quantize.get_codebook_entry(_a , shape=_a ) SCREAMING_SNAKE_CASE__ : int = self.vqvae.decode(_a , force_not_quantize=_a ).sample SCREAMING_SNAKE_CASE__ : Any = (image / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE__ : List[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.numpy_to_pil(_a ) if not return_dict: return (image,) return ImagePipelineOutput(images=_a ) def _a ( self , _a , _a ) -> torch.FloatTensor: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.sort(_a , 1 , descending=_a ) SCREAMING_SNAKE_CASE__ : List[str] = torch.exp(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = sorted_p_x_0.cumsum(dim=1 ) < truncation_rate # Ensure that at least the largest probability is not zeroed out SCREAMING_SNAKE_CASE__ : List[str] = torch.full_like(keep_mask[:, 0:1, :] , _a ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.cat((all_true, keep_mask) , dim=1 ) SCREAMING_SNAKE_CASE__ : Dict = keep_mask[:, :-1, :] SCREAMING_SNAKE_CASE__ : Optional[int] = keep_mask.gather(1 , indices.argsort(1 ) ) SCREAMING_SNAKE_CASE__ : Dict = log_p_x_0.clone() SCREAMING_SNAKE_CASE__ : Optional[Any] = -torch.inf # -inf = log(0) return rv
680
"""simple docstring""" import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __a (UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = LayoutLMTokenizer _SCREAMING_SNAKE_CASE :Optional[int] = LayoutLMTokenizerFast _SCREAMING_SNAKE_CASE :str = True _SCREAMING_SNAKE_CASE :Optional[int] = True def _a ( self ) -> Tuple: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : List[str] = [ """[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] SCREAMING_SNAKE_CASE__ : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def _a ( self , **_a ) -> Optional[int]: """simple docstring""" return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **_a ) def _a ( self , _a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = """UNwant\u00E9d,running""" SCREAMING_SNAKE_CASE__ : Optional[Any] = """unwanted, running""" return input_text, output_text def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(_a , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_a ) , [7, 4, 5, 10, 8, 9] ) def _a ( self ) -> Optional[int]: """simple docstring""" pass
680
1
"""simple docstring""" from itertools import product from cva import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import dot, exp, mgrid, pi, ravel, square, uinta, zeros def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> List[str]: SCREAMING_SNAKE_CASE__ : Union[str, Any] = k_size // 2 SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = mgrid[0 - center : k_size - center, 0 - center : k_size - center] SCREAMING_SNAKE_CASE__ : Optional[int] = 1 / (2 * pi * sigma) * exp(-(square(__lowerCAmelCase ) + square(__lowerCAmelCase )) / (2 * square(__lowerCAmelCase )) ) return g def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = image.shape[0], image.shape[1] # dst image height and width SCREAMING_SNAKE_CASE__ : Union[str, Any] = height - k_size + 1 SCREAMING_SNAKE_CASE__ : Optional[Any] = width - k_size + 1 # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows SCREAMING_SNAKE_CASE__ : Union[str, Any] = zeros((dst_height * dst_width, k_size * k_size) ) SCREAMING_SNAKE_CASE__ : Optional[int] = 0 for i, j in product(range(__lowerCAmelCase ) , range(__lowerCAmelCase ) ): SCREAMING_SNAKE_CASE__ : str = ravel(image[i : i + k_size, j : j + k_size] ) SCREAMING_SNAKE_CASE__ : int = window row += 1 # turn the kernel into shape(k*k, 1) SCREAMING_SNAKE_CASE__ : Tuple = gen_gaussian_kernel(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ravel(__lowerCAmelCase ) # reshape and get the dst image SCREAMING_SNAKE_CASE__ : str = dot(__lowerCAmelCase , __lowerCAmelCase ).reshape(__lowerCAmelCase , __lowerCAmelCase ).astype(__lowerCAmelCase ) return dst if __name__ == "__main__": # read original image a :List[str] = imread(r"../image_data/lena.jpg") # turn image in gray scale value a :Optional[int] = cvtColor(img, COLOR_BGR2GRAY) # get values with two different mask size a :Optional[int] = gaussian_filter(gray, 3, sigma=1) a :Any = gaussian_filter(gray, 5, sigma=0.8) # show result images imshow("gaussian filter with 3x3 mask", gaussianaxa) imshow("gaussian filter with 5x5 mask", gaussianaxa) waitKey()
680
"""simple docstring""" import argparse import os import evaluate import torch from datasets import load_dataset 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 # and perform gradient accumulation # # 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 run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a :str = 16 a :Union[str, Any] = 32 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase = 16 ) -> Tuple: SCREAMING_SNAKE_CASE__ : int = AutoTokenizer.from_pretrained("""bert-base-cased""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__lowerCAmelCase ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__lowerCAmelCase , max_length=__lowerCAmelCase ) 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(): SCREAMING_SNAKE_CASE__ : List[str] = datasets.map( __lowerCAmelCase , batched=__lowerCAmelCase , 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 SCREAMING_SNAKE_CASE__ : Any = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__lowerCAmelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE__ : int = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE__ : str = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE__ : Dict = 8 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = None return tokenizer.pad( __lowerCAmelCase , padding="""longest""" , max_length=__lowerCAmelCase , pad_to_multiple_of=__lowerCAmelCase , return_tensors="""pt""" , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE__ : int = DataLoader( tokenized_datasets["""train"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = DataLoader( tokenized_datasets["""validation"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": from accelerate.test_utils.training import mocked_dataloaders a :Dict = mocked_dataloaders # noqa: F811 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , __lowerCAmelCase ) == "1": SCREAMING_SNAKE_CASE__ : Optional[int] = 2 # New Code # SCREAMING_SNAKE_CASE__ : Optional[int] = int(args.gradient_accumulation_steps ) # Initialize accelerator SCREAMING_SNAKE_CASE__ : Optional[Any] = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=__lowerCAmelCase ) if accelerator.distributed_type == DistributedType.TPU and gradient_accumulation_steps > 1: raise NotImplementedError( """Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE__ : Any = config["""lr"""] SCREAMING_SNAKE_CASE__ : str = int(config["""num_epochs"""] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = int(config["""seed"""] ) SCREAMING_SNAKE_CASE__ : List[str] = int(config["""batch_size"""] ) SCREAMING_SNAKE_CASE__ : Any = evaluate.load("""glue""" , """mrpc""" ) set_seed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = get_dataloaders(__lowerCAmelCase , __lowerCAmelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE__ : int = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=__lowerCAmelCase ) # 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). SCREAMING_SNAKE_CASE__ : int = model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE__ : Union[str, Any] = AdamW(params=model.parameters() , lr=__lowerCAmelCase ) # Instantiate scheduler SCREAMING_SNAKE_CASE__ : Any = get_linear_schedule_with_warmup( optimizer=__lowerCAmelCase , num_warmup_steps=100 , num_training_steps=(len(__lowerCAmelCase ) * num_epochs) , ) # 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. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = accelerator.prepare( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Now we train the model for epoch in range(__lowerCAmelCase ): model.train() for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = output.loss accelerator.backward(__lowerCAmelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=__lowerCAmelCase , references=__lowerCAmelCase , ) SCREAMING_SNAKE_CASE__ : List[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , __lowerCAmelCase ) def _lowercase ( ) -> Any: SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=__lowerCAmelCase , default=__lowerCAmelCase , 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.""" , ) # New Code # parser.add_argument( """--gradient_accumulation_steps""" , type=__lowerCAmelCase , default=1 , help="""The number of minibatches to be ran before gradients are accumulated.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : int = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": main()
680
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a :Dict = logging.get_logger(__name__) a :Optional[int] = { "facebook/xglm-564M": "https://huggingface.co/facebook/xglm-564M/resolve/main/config.json", # See all XGLM models at https://huggingface.co/models?filter=xglm } class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = """xglm""" _SCREAMING_SNAKE_CASE :List[Any] = ["""past_key_values"""] _SCREAMING_SNAKE_CASE :Optional[Any] = { """num_attention_heads""": """attention_heads""", """hidden_size""": """d_model""", """num_hidden_layers""": """num_layers""", } def __init__( self , _a=256_008 , _a=2_048 , _a=1_024 , _a=4_096 , _a=24 , _a=16 , _a="gelu" , _a=0.1 , _a=0.1 , _a=0.0 , _a=0.0 , _a=0.02 , _a=True , _a=True , _a=2 , _a=1 , _a=0 , _a=2 , **_a , ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = vocab_size SCREAMING_SNAKE_CASE__ : Optional[int] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Union[str, Any] = d_model SCREAMING_SNAKE_CASE__ : List[str] = ffn_dim SCREAMING_SNAKE_CASE__ : Tuple = num_layers SCREAMING_SNAKE_CASE__ : str = attention_heads SCREAMING_SNAKE_CASE__ : Any = activation_function SCREAMING_SNAKE_CASE__ : List[Any] = dropout SCREAMING_SNAKE_CASE__ : Tuple = attention_dropout SCREAMING_SNAKE_CASE__ : int = activation_dropout SCREAMING_SNAKE_CASE__ : int = layerdrop SCREAMING_SNAKE_CASE__ : List[str] = init_std SCREAMING_SNAKE_CASE__ : Optional[Any] = scale_embedding # scale factor will be sqrt(d_model) if True SCREAMING_SNAKE_CASE__ : str = use_cache super().__init__( pad_token_id=_a , bos_token_id=_a , eos_token_id=_a , decoder_start_token_id=_a , **_a , )
680
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available a :str = { "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST", "ErnieForCausalLM", "ErnieForMaskedLM", "ErnieForMultipleChoice", "ErnieForNextSentencePrediction", "ErnieForPreTraining", "ErnieForQuestionAnswering", "ErnieForSequenceClassification", "ErnieForTokenClassification", "ErnieModel", "ErniePreTrainedModel", ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys a :Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices a :int = logging.get_logger(__name__) a :List[str] = { "microsoft/resnet-50": "https://huggingface.co/microsoft/resnet-50/blob/main/config.json", } class __a (UpperCamelCase_ , UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[int] = """resnet""" _SCREAMING_SNAKE_CASE :Optional[int] = ["""basic""", """bottleneck"""] def __init__( self , _a=3 , _a=64 , _a=[256, 512, 1_024, 2_048] , _a=[3, 4, 6, 3] , _a="bottleneck" , _a="relu" , _a=False , _a=None , _a=None , **_a , ) -> Optional[Any]: """simple docstring""" super().__init__(**_a ) if layer_type not in self.layer_types: raise ValueError(f'''layer_type={layer_type} is not one of {','.join(self.layer_types )}''' ) SCREAMING_SNAKE_CASE__ : Dict = num_channels SCREAMING_SNAKE_CASE__ : List[Any] = embedding_size SCREAMING_SNAKE_CASE__ : List[Any] = hidden_sizes SCREAMING_SNAKE_CASE__ : List[str] = depths SCREAMING_SNAKE_CASE__ : int = layer_type SCREAMING_SNAKE_CASE__ : Dict = hidden_act SCREAMING_SNAKE_CASE__ : Tuple = downsample_in_first_stage SCREAMING_SNAKE_CASE__ : Any = ["""stem"""] + [f'''stage{idx}''' for idx in range(1 , len(_a ) + 1 )] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = get_aligned_output_features_output_indices( out_features=_a , out_indices=_a , stage_names=self.stage_names ) class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Dict = version.parse("""1.11""") @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def _a ( self ) -> float: """simple docstring""" return 1E-3
680
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> int: assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and number_of_steps > 0 ), F'''number_of_steps needs to be positive integer, your input {number_of_steps}''' if number_of_steps == 1: return 1 SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = 1, 1 for _ in range(number_of_steps - 1 ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = current + previous, current return current if __name__ == "__main__": import doctest doctest.testmod()
680
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 __a (UpperCamelCase_): '''simple docstring''' # to overwrite at feature extractactor specific tests _SCREAMING_SNAKE_CASE :List[Any] = None _SCREAMING_SNAKE_CASE :Tuple = None @property def _a ( self ) -> Tuple: """simple docstring""" return self.feat_extract_tester.prepare_feat_extract_dict() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = 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 _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Optional[Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(_a ) == len(_a ) for x, y in zip(_a , processed_features[input_name] ) ) ) SCREAMING_SNAKE_CASE__ : int = self.feat_extract_tester.prepare_inputs_for_common(equal_length=_a ) SCREAMING_SNAKE_CASE__ : int = BatchFeature({input_name: speech_inputs} , tensor_type="""np""" ) SCREAMING_SNAKE_CASE__ : int = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : 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) ) @require_torch def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.prepare_inputs_for_common(equal_length=_a ) SCREAMING_SNAKE_CASE__ : Any = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Dict = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} , tensor_type="""pt""" ) SCREAMING_SNAKE_CASE__ : List[str] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : Union[str, 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) ) @require_tf def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_common(equal_length=_a ) SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : str = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = BatchFeature({input_name: speech_inputs} , tensor_type="""tf""" ) SCREAMING_SNAKE_CASE__ : Any = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : Tuple = 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 _a ( self , _a=False ) -> Any: """simple docstring""" def _inputs_have_equal_length(_a ): SCREAMING_SNAKE_CASE__ : int = len(input[0] ) for input_slice in input[1:]: if len(_a ) != length: return False return True def _inputs_are_equal(_a , _a ): 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 SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : List[str] = self.feat_extract_tester.prepare_inputs_for_common(numpify=_a ) SCREAMING_SNAKE_CASE__ : List[str] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : List[str] = self.feat_extract_tester.seq_length_diff SCREAMING_SNAKE_CASE__ : int = self.feat_extract_tester.max_seq_length + pad_diff SCREAMING_SNAKE_CASE__ : int = self.feat_extract_tester.min_seq_length SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.batch_size SCREAMING_SNAKE_CASE__ : Tuple = self.feat_extract_tester.feature_size # test padding for List[int] + numpy SCREAMING_SNAKE_CASE__ : int = feat_extract.pad(_a , padding=_a ) SCREAMING_SNAKE_CASE__ : Dict = input_a[input_name] SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.pad(_a , padding="""longest""" ) SCREAMING_SNAKE_CASE__ : str = input_a[input_name] SCREAMING_SNAKE_CASE__ : str = feat_extract.pad(_a , padding="""max_length""" , max_length=len(speech_inputs[-1] ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = input_a[input_name] SCREAMING_SNAKE_CASE__ : int = feat_extract.pad(_a , padding="""longest""" , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : List[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] SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.pad( _a , padding="""max_length""" , max_length=_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 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 SCREAMING_SNAKE_CASE__ : List[Any] = feat_extract.pad(_a , pad_to_multiple_of=10 ) SCREAMING_SNAKE_CASE__ : List[str] = input_a[input_name] SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad(_a , padding="""longest""" , pad_to_multiple_of=10 ) SCREAMING_SNAKE_CASE__ : Optional[int] = input_a[input_name] SCREAMING_SNAKE_CASE__ : List[Any] = feat_extract.pad( _a , padding="""max_length""" , pad_to_multiple_of=10 , max_length=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = input_a[input_name] SCREAMING_SNAKE_CASE__ : Dict = feat_extract.pad( _a , padding="""max_length""" , pad_to_multiple_of=10 , max_length=_a , return_tensors="""np""" , ) SCREAMING_SNAKE_CASE__ : List[str] = input_a[input_name] self.assertTrue(all(len(_a ) % 10 == 0 for x in input_a ) ) self.assertTrue(_inputs_are_equal(_a , _a ) ) SCREAMING_SNAKE_CASE__ : 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 SCREAMING_SNAKE_CASE__ : Union[str, 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 _a ( self , _a=False ) -> Optional[int]: """simple docstring""" def _inputs_have_equal_length(_a ): SCREAMING_SNAKE_CASE__ : Tuple = len(input[0] ) for input_slice in input[1:]: if len(_a ) != length: return False return True def _inputs_are_equal(_a , _a ): 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 SCREAMING_SNAKE_CASE__ : str = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.feat_extract_tester.prepare_inputs_for_common(numpify=_a ) SCREAMING_SNAKE_CASE__ : Any = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = BatchFeature({input_name: speech_inputs} ) # truncate to smallest SCREAMING_SNAKE_CASE__ : int = feat_extract.pad( _a , padding="""max_length""" , max_length=len(speech_inputs[0] ) , truncation=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = input_a[input_name] SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.pad(_a , padding="""max_length""" , max_length=len(speech_inputs[0] ) ) SCREAMING_SNAKE_CASE__ : str = input_a[input_name] self.assertTrue(_inputs_have_equal_length(_a ) ) self.assertFalse(_inputs_have_equal_length(_a ) ) # truncate to smallest with np SCREAMING_SNAKE_CASE__ : Tuple = feat_extract.pad( _a , padding="""max_length""" , max_length=len(speech_inputs[0] ) , return_tensors="""np""" , truncation=_a , ) SCREAMING_SNAKE_CASE__ : int = input_a[input_name] SCREAMING_SNAKE_CASE__ : List[Any] = feat_extract.pad( _a , padding="""max_length""" , max_length=len(speech_inputs[0] ) , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Tuple = 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 SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad( _a , padding="""max_length""" , max_length=len(speech_inputs[1] ) , truncation=_a , return_tensors="""np""" , ) SCREAMING_SNAKE_CASE__ : List[Any] = input_a[input_name] SCREAMING_SNAKE_CASE__ : int = feat_extract.pad( _a , padding="""max_length""" , max_length=len(speech_inputs[1] ) , truncation=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = input_a[input_name] SCREAMING_SNAKE_CASE__ : Optional[Any] = feat_extract.pad( _a , padding="""max_length""" , max_length=len(speech_inputs[1] ) , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Tuple = 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 SCREAMING_SNAKE_CASE__ : List[str] = 12 SCREAMING_SNAKE_CASE__ : List[str] = feat_extract.pad( _a , padding="""max_length""" , max_length=len(speech_inputs[0] ) , pad_to_multiple_of=_a , truncation=_a , ) SCREAMING_SNAKE_CASE__ : List[str] = input_a[input_name] SCREAMING_SNAKE_CASE__ : int = feat_extract.pad( _a , padding="""max_length""" , max_length=len(speech_inputs[0] ) , pad_to_multiple_of=_a , ) SCREAMING_SNAKE_CASE__ : Optional[int] = input_a[input_name] # retrieve expected_length as multiple of pad_to_multiple_of SCREAMING_SNAKE_CASE__ : Dict = len(speech_inputs[0] ) if expected_length % pad_to_multiple_of != 0: SCREAMING_SNAKE_CASE__ : Tuple = ((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 _a ( self ) -> int: """simple docstring""" self._check_padding(numpify=_a ) def _a ( self ) -> int: """simple docstring""" self._check_padding(numpify=_a ) def _a ( self ) -> Any: """simple docstring""" self._check_truncation(numpify=_a ) def _a ( self ) -> Union[str, Any]: """simple docstring""" self._check_truncation(numpify=_a ) @require_torch def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Dict = self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Optional[int] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.pad(_a , padding="""longest""" , return_tensors="""np""" )[input_name] SCREAMING_SNAKE_CASE__ : Union[str, Any] = 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 _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Tuple = self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE__ : Optional[Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : List[str] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : str = feat_extract.pad(_a , padding="""longest""" , return_tensors="""np""" )[input_name] SCREAMING_SNAKE_CASE__ : str = 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 _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.feature_extraction_class(**_a ) SCREAMING_SNAKE_CASE__ : Dict = self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE__ : str = [len(_a ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Dict = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Dict = 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 _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : int = True SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE__ : int = [len(_a ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Optional[Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : str = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Optional[Any] = min(_a ) SCREAMING_SNAKE_CASE__ : 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] )
680
"""simple docstring""" from math import factorial def _lowercase ( __lowerCAmelCase = 100 ) -> int: return sum(int(__lowerCAmelCase ) for x in str(factorial(__lowerCAmelCase ) ) ) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
680
1
"""simple docstring""" import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Union[str, Path]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = True _SCREAMING_SNAKE_CASE :Optional[int] = None _SCREAMING_SNAKE_CASE :int = 1 _SCREAMING_SNAKE_CASE :Optional[Union[str, bool]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None def _a ( self ) -> "DownloadConfig": """simple docstring""" return self.__class__(**{k: copy.deepcopy(_a ) for k, v in self.__dict__.items()} )
680
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from typing import List from unittest.mock import Mock import torch from torch.utils.data import DataLoader, IterableDataset, TensorDataset from accelerate.accelerator import Accelerator from accelerate.utils.dataclasses import DistributedType class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = data def __iter__( self ) -> Tuple: """simple docstring""" for element in self.data: yield element def _lowercase ( __lowerCAmelCase=True ) -> str: SCREAMING_SNAKE_CASE__ : str = Accelerator(even_batches=__lowerCAmelCase ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = False ) -> Optional[int]: if iterable: SCREAMING_SNAKE_CASE__ : int = DummyIterableDataset(torch.as_tensor(range(__lowerCAmelCase ) ) ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = TensorDataset(torch.as_tensor(range(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : str = DataLoader(__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = accelerator.prepare(__lowerCAmelCase ) return dl def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> Tuple: SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(accelerator=__lowerCAmelCase , dataset_size=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = [len(batch[0] ) for batch in dl] if accelerator.process_index == 0: assert batch_sizes == process_0_expected_batch_sizes elif accelerator.process_index == 1: assert batch_sizes == process_1_expected_batch_sizes def _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Tuple = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1, 1] , ) # without padding, we would expect the same number of batches, but different sizes verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_accelerator(even_batches=__lowerCAmelCase ) verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , ) verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , ) def _lowercase ( ) -> str: SCREAMING_SNAKE_CASE__ : List[str] = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) SCREAMING_SNAKE_CASE__ : int = [] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Optional[Any] = ddp_model(batch[0].float() ) SCREAMING_SNAKE_CASE__ : List[Any] = output.sum() loss.backward() batch_idxs.append(__lowerCAmelCase ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: with warnings.catch_warnings(record=__lowerCAmelCase ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category , __lowerCAmelCase ) assert "only supported for multi-GPU" in str(w[-1].message ) def _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = False SCREAMING_SNAKE_CASE__ : Any = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerator.prepare(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) SCREAMING_SNAKE_CASE__ : List[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[Any] = train_dl.batch_sampler.even_batches SCREAMING_SNAKE_CASE__ : str = valid_dl.batch_sampler.even_batches assert train_dl_overridden_value == overridden_even_batches assert valid_dl_overridden_value == overridden_even_batches assert train_dl.batch_sampler.even_batches == default_even_batches assert valid_dl.batch_sampler.even_batches == default_even_batches def _lowercase ( ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[Any] = True SCREAMING_SNAKE_CASE__ : List[Any] = False SCREAMING_SNAKE_CASE__ : int = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : str = accelerator.prepare(__lowerCAmelCase ) create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings("""ignore""" ) try: with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = batch_dl.batch_sampler.even_batches except AttributeError: # ensure attribute error is not raised when processing iterable dl raise AssertionError assert batch_dl_overridden_value == overridden_even_batches assert batch_dl.batch_sampler.even_batches == default_even_batches def _lowercase ( ) -> List[str]: SCREAMING_SNAKE_CASE__ : str = create_accelerator() SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase ) create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase ) with warnings.catch_warnings(record=__lowerCAmelCase ) as w: with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): pass assert issubclass(w[-1].category , __lowerCAmelCase ) assert "only supported for map-style datasets" in str(w[-1].message ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_accelerator() accelerator.print("""Test that even_batches variable ensures uniform batches across processes""" ) test_default_ensures_even_batch_sizes() accelerator.print("""Run tests with even_batches disabled""" ) test_can_disable_even_batches() accelerator.print("""Test joining uneven inputs""" ) test_can_join_uneven_inputs() accelerator.print("""Test overriding even_batches when joining uneven inputs""" ) test_join_can_override_even_batches() accelerator.print("""Test overriding even_batches for mixed dataloader types""" ) test_join_can_override_for_mixed_type_dataloaders() accelerator.print("""Test overriding even_batches raises a warning for iterable dataloaders""" ) test_join_raises_warning_for_iterable_when_overriding_even_batches() accelerator.print("""Test join with non DDP distributed raises warning""" ) SCREAMING_SNAKE_CASE__ : Dict = accelerator.state.distributed_type SCREAMING_SNAKE_CASE__ : Optional[int] = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = original_state if __name__ == "__main__": main()
680
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import _LazyModule a :Optional[Any] = {"tokenization_bertweet": ["BertweetTokenizer"]} if TYPE_CHECKING: from .tokenization_bertweet import BertweetTokenizer else: import sys a :Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
"""simple docstring""" def _lowercase ( __lowerCAmelCase = 200_0000 ) -> int: SCREAMING_SNAKE_CASE__ : int = [0 for i in range(n + 1 )] SCREAMING_SNAKE_CASE__ : str = 1 SCREAMING_SNAKE_CASE__ : str = 1 for i in range(2 , int(n**0.5 ) + 1 ): if primality_list[i] == 0: for j in range(i * i , n + 1 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 for i in range(__lowerCAmelCase ): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(f'{solution() = }')
680
1
"""simple docstring""" import os from typing import Optional import fsspec from fsspec.archive import AbstractArchiveFileSystem from fsspec.utils import DEFAULT_BLOCK_SIZE class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :int = """""" _SCREAMING_SNAKE_CASE :str = ( None # protocol passed in prefix to the url. ex: "gzip", for gzip://file.txt::http://foo.bar/file.txt.gz ) _SCREAMING_SNAKE_CASE :str = None # compression type in fsspec. ex: "gzip" _SCREAMING_SNAKE_CASE :str = None # extension of the filename to strip. ex: "".gz" to get file.txt from file.txt.gz def __init__( self , _a = "" , _a = None , _a = None , **_a ) -> Tuple: """simple docstring""" super().__init__(self , **_a ) # always open as "rb" since fsspec can then use the TextIOWrapper to make it work for "r" mode SCREAMING_SNAKE_CASE__ : List[str] = fsspec.open( _a , mode="""rb""" , protocol=_a , compression=self.compression , client_kwargs={ """requote_redirect_url""": False, # see https://github.com/huggingface/datasets/pull/5459 """trust_env""": True, # Enable reading proxy env variables. **(target_options or {}).pop("""client_kwargs""" , {} ), # To avoid issues if it was already passed. } , **(target_options or {}) , ) SCREAMING_SNAKE_CASE__ : Tuple = os.path.basename(self.file.path.split("""::""" )[0] ) SCREAMING_SNAKE_CASE__ : Any = ( self.compressed_name[: self.compressed_name.rindex(""".""" )] if """.""" in self.compressed_name else self.compressed_name ) SCREAMING_SNAKE_CASE__ : Any = None @classmethod def _a ( cls , _a ) -> Any: """simple docstring""" return super()._strip_protocol(_a ).lstrip("""/""" ) def _a ( self ) -> Any: """simple docstring""" if self.dir_cache is None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = {**self.file.fs.info(self.file.path ), """name""": self.uncompressed_name} SCREAMING_SNAKE_CASE__ : Dict = {f["""name"""]: f} def _a ( self , _a ) -> List[str]: """simple docstring""" return self.file.open().read() def _a ( self , _a , _a = "rb" , _a=None , _a=True , _a=None , **_a , ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self._strip_protocol(_a ) if mode != "rb": raise ValueError(f'''Tried to read with mode {mode} on file {self.file.path} opened with mode \'rb\'''' ) return self.file.open() class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = """bz2""" _SCREAMING_SNAKE_CASE :Optional[int] = """bz2""" _SCREAMING_SNAKE_CASE :Union[str, Any] = """.bz2""" class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Dict = """gzip""" _SCREAMING_SNAKE_CASE :Optional[Any] = """gzip""" _SCREAMING_SNAKE_CASE :Optional[int] = """.gz""" class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = """lz4""" _SCREAMING_SNAKE_CASE :List[Any] = """lz4""" _SCREAMING_SNAKE_CASE :List[Any] = """.lz4""" class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = """xz""" _SCREAMING_SNAKE_CASE :List[str] = """xz""" _SCREAMING_SNAKE_CASE :Dict = """.xz""" class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Any = """zstd""" _SCREAMING_SNAKE_CASE :str = """zstd""" _SCREAMING_SNAKE_CASE :str = """.zst""" def __init__( self , _a , _a = "rb" , _a = None , _a = None , _a = DEFAULT_BLOCK_SIZE , **_a , ) -> List[Any]: """simple docstring""" super().__init__( fo=_a , mode=_a , target_protocol=_a , target_options=_a , block_size=_a , **_a , ) # We need to wrap the zstd decompressor to avoid this error in fsspec==2021.7.0 and zstandard==0.15.2: # # File "/Users/user/.virtualenvs/hf-datasets/lib/python3.7/site-packages/fsspec/core.py", line 145, in open # out.close = close # AttributeError: 'zstd.ZstdDecompressionReader' object attribute 'close' is read-only # # see https://github.com/intake/filesystem_spec/issues/725 SCREAMING_SNAKE_CASE__ : Tuple = self.file.__enter__ class __a : '''simple docstring''' def __init__( self , _a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = file_ def __enter__( self ) -> Any: """simple docstring""" self._file.__enter__() return self def __exit__( self , *_a , **_a ) -> Union[str, Any]: """simple docstring""" self._file.__exit__(*_a , **_a ) def __iter__( self ) -> Any: """simple docstring""" return iter(self._file ) def _a ( self ) -> List[str]: """simple docstring""" return next(self._file ) def __getattr__( self , _a ) -> Any: """simple docstring""" return getattr(self._file , _a ) def fixed_enter(*_a , **_a ): return WrappedFile(_enter(*_a , **_a ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = fixed_enter
680
"""simple docstring""" import numpy as np import qiskit def _lowercase ( __lowerCAmelCase = 8 , __lowerCAmelCase = None ) -> str: SCREAMING_SNAKE_CASE__ : List[Any] = np.random.default_rng(seed=__lowerCAmelCase ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. SCREAMING_SNAKE_CASE__ : List[str] = 6 * key_len # Measurement basis for Alice's qubits. SCREAMING_SNAKE_CASE__ : List[Any] = rng.integers(2 , size=__lowerCAmelCase ) # The set of states Alice will prepare. SCREAMING_SNAKE_CASE__ : Optional[Any] = rng.integers(2 , size=__lowerCAmelCase ) # Measurement basis for Bob's qubits. SCREAMING_SNAKE_CASE__ : str = rng.integers(2 , size=__lowerCAmelCase ) # Quantum Circuit to simulate BB84 SCREAMING_SNAKE_CASE__ : Union[str, Any] = qiskit.QuantumCircuit(__lowerCAmelCase , name="""BB84""" ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(__lowerCAmelCase ): if alice_state[index] == 1: bbaa_circ.x(__lowerCAmelCase ) if alice_basis[index] == 1: bbaa_circ.h(__lowerCAmelCase ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(__lowerCAmelCase ): if bob_basis[index] == 1: bbaa_circ.h(__lowerCAmelCase ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. SCREAMING_SNAKE_CASE__ : str = qiskit.Aer.get_backend("""aer_simulator""" ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. SCREAMING_SNAKE_CASE__ : Optional[int] = qiskit.execute(__lowerCAmelCase , __lowerCAmelCase , shots=1 , seed_simulator=__lowerCAmelCase ) # Returns the result of measurement. SCREAMING_SNAKE_CASE__ : int = job.result().get_counts(__lowerCAmelCase ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. SCREAMING_SNAKE_CASE__ : Optional[Any] = """""".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. SCREAMING_SNAKE_CASE__ : Optional[int] = gen_key[:key_len] if len(__lowerCAmelCase ) >= key_len else gen_key.ljust(__lowerCAmelCase , """0""" ) return key if __name__ == "__main__": print(f'The generated key is : {bbaa(8, seed=0)}') from doctest import testmod testmod()
680
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a :int = logging.get_logger(__name__) a :List[Any] = { "abeja/gpt-neox-japanese-2.7b": "https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/config.json", } class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = """gpt_neox_japanese""" def __init__( self , _a=32_000 , _a=2_560 , _a=32 , _a=32 , _a=4 , _a="gelu" , _a=1.00 , _a=10_000 , _a=2_048 , _a=0.02 , _a=1E-5 , _a=True , _a=31_996 , _a=31_999 , _a=0.1 , _a=0.0 , **_a , ) -> str: """simple docstring""" super().__init__(bos_token_id=_a , eos_token_id=_a , **_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = vocab_size SCREAMING_SNAKE_CASE__ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : List[str] = hidden_size SCREAMING_SNAKE_CASE__ : List[str] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Any = num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[int] = intermediate_multiple_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_act SCREAMING_SNAKE_CASE__ : Tuple = rotary_pct SCREAMING_SNAKE_CASE__ : List[Any] = rotary_emb_base SCREAMING_SNAKE_CASE__ : int = initializer_range SCREAMING_SNAKE_CASE__ : List[str] = layer_norm_eps SCREAMING_SNAKE_CASE__ : str = use_cache SCREAMING_SNAKE_CASE__ : str = attention_dropout SCREAMING_SNAKE_CASE__ : List[Any] = hidden_dropout
680
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __a (UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :str = StableDiffusionInpaintPipeline _SCREAMING_SNAKE_CASE :Any = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS _SCREAMING_SNAKE_CASE :Dict = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS _SCREAMING_SNAKE_CASE :Optional[int] = frozenset( []) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _SCREAMING_SNAKE_CASE :Dict = frozenset([]) def _a ( self ) -> Dict: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , 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 , ) SCREAMING_SNAKE_CASE__ : List[str] = PNDMScheduler(skip_prk_steps=_a ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = 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 ) SCREAMING_SNAKE_CASE__ : int = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) SCREAMING_SNAKE_CASE__ : int = CLIPTextModel(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) SCREAMING_SNAKE_CASE__ : int = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def _a ( self , _a , _a=0 ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = floats_tensor((1, 3, 32, 32) , rng=random.Random(_a ) ).to(_a ) SCREAMING_SNAKE_CASE__ : Tuple = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : Any = Image.fromarray(np.uinta(_a ) ).convert("""RGB""" ).resize((64, 64) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(_a ).startswith("""mps""" ): SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(_a ) else: SCREAMING_SNAKE_CASE__ : str = torch.Generator(device=_a ).manual_seed(_a ) SCREAMING_SNAKE_CASE__ : Tuple = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInpaintPipeline(**_a ) SCREAMING_SNAKE_CASE__ : Any = sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : int = self.get_dummy_inputs(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe(**_a ).images SCREAMING_SNAKE_CASE__ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : str = np.array([0.4_727, 0.5_735, 0.3_941, 0.5_446, 0.5_926, 0.4_394, 0.5_062, 0.4_654, 0.4_476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _a ( self ) -> Optional[int]: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : Any = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : Any = StableDiffusionInpaintPipeline.from_pretrained(_a , safety_checker=_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : int = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Tuple = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : int = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) SCREAMING_SNAKE_CASE__ : List[str] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInpaintPipeline.from_pretrained( _a , torch_dtype=torch.floataa , safety_checker=_a , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Any = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Tuple = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def _a ( self ) -> Tuple: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE__ : Dict = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : str = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : List[str] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : Dict = PNDMScheduler.from_pretrained(_a , subfolder="""scheduler""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = StableDiffusionInpaintPipeline.from_pretrained( _a , safety_checker=_a , scheduler=_a , torch_dtype=torch.floataa , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE__ : Union[str, Any] = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , num_inference_steps=2 , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : List[str] = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
680
1
"""simple docstring""" import math def _lowercase ( __lowerCAmelCase ) -> bool: SCREAMING_SNAKE_CASE__ : List[str] = math.loga(math.sqrt(4 * positive_integer + 1 ) / 2 + 1 / 2 ) return exponent == int(__lowerCAmelCase ) def _lowercase ( __lowerCAmelCase = 1 / 1_2345 ) -> int: SCREAMING_SNAKE_CASE__ : Optional[int] = 0 SCREAMING_SNAKE_CASE__ : Dict = 0 SCREAMING_SNAKE_CASE__ : str = 3 while True: SCREAMING_SNAKE_CASE__ : Union[str, Any] = (integer**2 - 1) / 4 # if candidate is an integer, then there is a partition for k if partition_candidate == int(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Optional[Any] = int(__lowerCAmelCase ) total_partitions += 1 if check_partition_perfect(__lowerCAmelCase ): perfect_partitions += 1 if perfect_partitions > 0: if perfect_partitions / total_partitions < max_proportion: return int(__lowerCAmelCase ) integer += 1 if __name__ == "__main__": print(f'{solution() = }')
680
"""simple docstring""" import argparse import logging import pickle import random import time import numpy as np from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) a :str = logging.getLogger(__name__) def _lowercase ( ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Dict = argparse.ArgumentParser( description="""Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids).""" ) parser.add_argument("""--file_path""" , type=__lowerCAmelCase , default="""data/dump.txt""" , help="""The path to the data.""" ) parser.add_argument("""--tokenizer_type""" , type=__lowerCAmelCase , default="""bert""" , choices=["""bert""", """roberta""", """gpt2"""] ) parser.add_argument("""--tokenizer_name""" , type=__lowerCAmelCase , default="""bert-base-uncased""" , help="""The tokenizer to use.""" ) parser.add_argument("""--dump_file""" , type=__lowerCAmelCase , default="""data/dump""" , help="""The dump file prefix.""" ) SCREAMING_SNAKE_CASE__ : str = parser.parse_args() logger.info(F'''Loading Tokenizer ({args.tokenizer_name})''' ) if args.tokenizer_type == "bert": SCREAMING_SNAKE_CASE__ : List[str] = BertTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : str = tokenizer.special_tokens_map["""cls_token"""] # `[CLS]` SCREAMING_SNAKE_CASE__ : str = tokenizer.special_tokens_map["""sep_token"""] # `[SEP]` elif args.tokenizer_type == "roberta": SCREAMING_SNAKE_CASE__ : List[Any] = RobertaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.special_tokens_map["""cls_token"""] # `<s>` SCREAMING_SNAKE_CASE__ : Dict = tokenizer.special_tokens_map["""sep_token"""] # `</s>` elif args.tokenizer_type == "gpt2": SCREAMING_SNAKE_CASE__ : List[Any] = GPTaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.special_tokens_map["""bos_token"""] # `<|endoftext|>` SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.special_tokens_map["""eos_token"""] # `<|endoftext|>` logger.info(F'''Loading text from {args.file_path}''' ) with open(args.file_path , """r""" , encoding="""utf8""" ) as fp: SCREAMING_SNAKE_CASE__ : int = fp.readlines() logger.info("""Start encoding""" ) logger.info(F'''{len(__lowerCAmelCase )} examples to process.''' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1_0000 SCREAMING_SNAKE_CASE__ : Dict = time.time() for text in data: SCREAMING_SNAKE_CASE__ : Dict = F'''{bos} {text.strip()} {sep}''' SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) rslt.append(__lowerCAmelCase ) iter += 1 if iter % interval == 0: SCREAMING_SNAKE_CASE__ : str = time.time() logger.info(F'''{iter} examples processed. - {(end-start):.2f}s/{interval}expl''' ) SCREAMING_SNAKE_CASE__ : Tuple = time.time() logger.info("""Finished binarization""" ) logger.info(F'''{len(__lowerCAmelCase )} examples processed.''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = F'''{args.dump_file}.{args.tokenizer_name}.pickle''' SCREAMING_SNAKE_CASE__ : Dict = tokenizer.vocab_size if vocab_size < (1 << 16): SCREAMING_SNAKE_CASE__ : Tuple = [np.uintaa(__lowerCAmelCase ) for d in rslt] else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [np.intaa(__lowerCAmelCase ) for d in rslt] random.shuffle(rslt_ ) logger.info(F'''Dump to {dp_file}''' ) with open(__lowerCAmelCase , """wb""" ) as handle: pickle.dump(rslt_ , __lowerCAmelCase , protocol=pickle.HIGHEST_PROTOCOL ) if __name__ == "__main__": main()
680
1
"""simple docstring""" import argparse import os import re import torch from flax.traverse_util import flatten_dict from tax import checkpoints from transformers import ( AutoTokenizer, PixaStructConfig, PixaStructForConditionalGeneration, PixaStructImageProcessor, PixaStructProcessor, PixaStructTextConfig, PixaStructVisionConfig, ) def _lowercase ( __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : List[str] = checkpoints.load_tax_checkpoint(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = flatten_dict(__lowerCAmelCase ) return flax_params def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Union[str, Any] = {} SCREAMING_SNAKE_CASE__ : Any = { """token_embedder""": """embeddings""", """encoder_norm""": """layernorm""", """kernel""": """weight""", """.out""": """.output""", """scale""": """weight""", """embedders_0.pos_embedding""": """row_embedder.weight""", """embedders_1.pos_embedding""": """column_embedder.weight""", } SCREAMING_SNAKE_CASE__ : Optional[int] = { """query""": """attention.query""", """key""": """attention.key""", """value""": """attention.value""", """output.dense""": """output""", """encoder_decoder_attention.o""": """encoder_decoder_attention.attention.o""", """pre_self_attention_layer_norm""": """self_attention.layer_norm""", """pre_cross_attention_layer_norm""": """encoder_decoder_attention.layer_norm""", """mlp.""": """mlp.DenseReluDense.""", """pre_mlp_layer_norm""": """mlp.layer_norm""", """self_attention.o""": """self_attention.attention.o""", """decoder.embeddings.embedding""": """decoder.embed_tokens.weight""", """decoder.relpos_bias.rel_embedding""": """decoder.layer.0.self_attention.attention.relative_attention_bias.weight""", """decoder.decoder_norm.weight""": """decoder.final_layer_norm.weight""", """decoder.logits_dense.weight""": """decoder.lm_head.weight""", } for key in flax_dict.keys(): if "target" in key: # remove the first prefix from the key SCREAMING_SNAKE_CASE__ : List[str] = """.""".join(key[1:] ) # rename the key for old, new in CONVERSION_MAPPING.items(): SCREAMING_SNAKE_CASE__ : List[Any] = new_key.replace(__lowerCAmelCase , __lowerCAmelCase ) if "decoder" in new_key: for old, new in DECODER_CONVERSION_MAPPING.items(): SCREAMING_SNAKE_CASE__ : str = new_key.replace(__lowerCAmelCase , __lowerCAmelCase ) if "layers" in new_key and "decoder" not in new_key: # use regex to replace the layer number SCREAMING_SNAKE_CASE__ : str = re.sub(r"""layers_(\d+)""" , r"""layer.\1""" , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = new_key.replace("""encoder""" , """encoder.encoder""" ) elif "layers" in new_key and "decoder" in new_key: # use regex to replace the layer number SCREAMING_SNAKE_CASE__ : Union[str, Any] = re.sub(r"""layers_(\d+)""" , r"""layer.\1""" , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = flax_dict[key] SCREAMING_SNAKE_CASE__ : Optional[int] = {} # convert converted_dict into torch format for key in converted_dict.keys(): if ("embed_tokens" not in key) and ("embedder" not in key): SCREAMING_SNAKE_CASE__ : Dict = torch.from_numpy(converted_dict[key].T ) else: SCREAMING_SNAKE_CASE__ : Any = torch.from_numpy(converted_dict[key] ) return converted_torch_dict def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=False , __lowerCAmelCase=False ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Tuple = get_flax_param(__lowerCAmelCase ) if not use_large: SCREAMING_SNAKE_CASE__ : Any = PixaStructVisionConfig() SCREAMING_SNAKE_CASE__ : List[Any] = PixaStructTextConfig() else: SCREAMING_SNAKE_CASE__ : int = PixaStructVisionConfig( hidden_size=1536 , d_ff=3968 , num_attention_heads=24 , num_hidden_layers=18 ) SCREAMING_SNAKE_CASE__ : List[Any] = PixaStructTextConfig(hidden_size=1536 , d_ff=3968 , num_heads=24 , num_layers=18 ) SCREAMING_SNAKE_CASE__ : int = PixaStructConfig( vision_config=encoder_config.to_dict() , text_config=decoder_config.to_dict() , is_vqa=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = PixaStructForConditionalGeneration(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : int = rename_and_convert_flax_params(__lowerCAmelCase ) model.load_state_dict(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoTokenizer.from_pretrained("""ybelkada/test-pix2struct-tokenizer""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = PixaStructImageProcessor() SCREAMING_SNAKE_CASE__ : int = PixaStructProcessor(image_processor=__lowerCAmelCase , tokenizer=__lowerCAmelCase ) if use_large: SCREAMING_SNAKE_CASE__ : Any = 4096 SCREAMING_SNAKE_CASE__ : Optional[Any] = True # mkdir if needed os.makedirs(__lowerCAmelCase , exist_ok=__lowerCAmelCase ) model.save_pretrained(__lowerCAmelCase ) processor.save_pretrained(__lowerCAmelCase ) print("""Model saved in {}""".format(__lowerCAmelCase ) ) if __name__ == "__main__": a :Tuple = argparse.ArgumentParser() parser.add_argument("--t5x_checkpoint_path", default=None, type=str, help="Path to the original T5x checkpoint.") parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--use_large", action="store_true", help="Use large model.") parser.add_argument("--is_vqa", action="store_true", help="Use large model.") a :List[str] = parser.parse_args() convert_pixastruct_original_pytorch_checkpoint_to_hf( args.tax_checkpoint_path, args.pytorch_dump_folder_path, args.use_large )
680
"""simple docstring""" import glob import os import random from string import ascii_lowercase, digits import cva a :List[Any] = "" a :Union[str, Any] = "" a :List[str] = "" a :str = 1 # (0 is vertical, 1 is horizontal) def _lowercase ( ) -> None: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = get_dataset(__lowerCAmelCase , __lowerCAmelCase ) print("""Processing...""" ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = update_image_and_anno(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) for index, image in enumerate(__lowerCAmelCase ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' SCREAMING_SNAKE_CASE__ : List[Any] = random_chars(32 ) SCREAMING_SNAKE_CASE__ : List[str] = paths[index].split(os.sep )[-1].rsplit(""".""" , 1 )[0] SCREAMING_SNAKE_CASE__ : List[str] = F'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(F'''/{file_root}.jpg''' , __lowerCAmelCase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F'''Success {index+1}/{len(__lowerCAmelCase )} with {file_name}''' ) SCREAMING_SNAKE_CASE__ : int = [] for anno in new_annos[index]: SCREAMING_SNAKE_CASE__ : Tuple = F'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(__lowerCAmelCase ) with open(F'''/{file_root}.txt''' , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> tuple[list, list]: SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] for label_file in glob.glob(os.path.join(__lowerCAmelCase , """*.txt""" ) ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(__lowerCAmelCase ) as in_file: SCREAMING_SNAKE_CASE__ : Dict = in_file.readlines() SCREAMING_SNAKE_CASE__ : int = os.path.join(__lowerCAmelCase , F'''{label_name}.jpg''' ) SCREAMING_SNAKE_CASE__ : int = [] for obj_list in obj_lists: SCREAMING_SNAKE_CASE__ : Optional[int] = obj_list.rstrip("""\n""" ).split(""" """ ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(__lowerCAmelCase ) labels.append(__lowerCAmelCase ) return img_paths, labels def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = 1 ) -> tuple[list, list, list]: SCREAMING_SNAKE_CASE__ : Dict = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [] for idx in range(len(__lowerCAmelCase ) ): SCREAMING_SNAKE_CASE__ : List[str] = [] SCREAMING_SNAKE_CASE__ : str = img_list[idx] path_list.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = anno_list[idx] SCREAMING_SNAKE_CASE__ : Tuple = cva.imread(__lowerCAmelCase ) if flip_type == 1: SCREAMING_SNAKE_CASE__ : int = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: SCREAMING_SNAKE_CASE__ : Optional[int] = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: SCREAMING_SNAKE_CASE__ : Any = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: SCREAMING_SNAKE_CASE__ : List[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(__lowerCAmelCase ) new_imgs_list.append(__lowerCAmelCase ) return new_imgs_list, new_annos_lists, path_list def _lowercase ( __lowerCAmelCase = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" SCREAMING_SNAKE_CASE__ : List[str] = ascii_lowercase + digits return "".join(random.choice(__lowerCAmelCase ) for _ in range(__lowerCAmelCase ) ) if __name__ == "__main__": main() print("DONE ✅")
680
1
"""simple docstring""" from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import ( BackboneOutput, BaseModelOutputWithNoAttention, BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention, ) from ...modeling_utils import PreTrainedModel from ...utils import ( add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings, ) from ...utils.backbone_utils import BackboneMixin from .configuration_resnet import ResNetConfig a :List[str] = logging.get_logger(__name__) # General docstring a :Tuple = "ResNetConfig" # Base docstring a :Union[str, Any] = "microsoft/resnet-50" a :List[Any] = [1, 2_048, 7, 7] # Image classification docstring a :str = "microsoft/resnet-50" a :Union[str, Any] = "tiger cat" a :int = [ "microsoft/resnet-50", # See all resnet models at https://huggingface.co/models?filter=resnet ] class __a (nn.Module): '''simple docstring''' def __init__( self , _a , _a , _a = 3 , _a = 1 , _a = "relu" ) -> Dict: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Dict = nn.Convad( _a , _a , kernel_size=_a , stride=_a , padding=kernel_size // 2 , bias=_a ) SCREAMING_SNAKE_CASE__ : Tuple = nn.BatchNormad(_a ) SCREAMING_SNAKE_CASE__ : List[str] = ACTaFN[activation] if activation is not None else nn.Identity() def _a ( self , _a ) -> Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.convolution(_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.normalization(_a ) SCREAMING_SNAKE_CASE__ : Tuple = self.activation(_a ) return hidden_state class __a (nn.Module): '''simple docstring''' def __init__( self , _a ) -> Optional[Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Tuple = ResNetConvLayer( config.num_channels , config.embedding_size , kernel_size=7 , stride=2 , activation=config.hidden_act ) SCREAMING_SNAKE_CASE__ : int = nn.MaxPoolad(kernel_size=3 , stride=2 , padding=1 ) SCREAMING_SNAKE_CASE__ : List[Any] = config.num_channels def _a ( self , _a ) -> Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = pixel_values.shape[1] if num_channels != self.num_channels: raise ValueError( """Make sure that the channel dimension of the pixel values match with the one set in the configuration.""" ) SCREAMING_SNAKE_CASE__ : int = self.embedder(_a ) SCREAMING_SNAKE_CASE__ : List[str] = self.pooler(_a ) return embedding class __a (nn.Module): '''simple docstring''' def __init__( self , _a , _a , _a = 2 ) -> List[str]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Optional[Any] = nn.Convad(_a , _a , kernel_size=1 , stride=_a , bias=_a ) SCREAMING_SNAKE_CASE__ : str = nn.BatchNormad(_a ) def _a ( self , _a ) -> Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.convolution(_a ) SCREAMING_SNAKE_CASE__ : Tuple = self.normalization(_a ) return hidden_state class __a (nn.Module): '''simple docstring''' def __init__( self , _a , _a , _a = 1 , _a = "relu" ) -> List[str]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Dict = in_channels != out_channels or stride != 1 SCREAMING_SNAKE_CASE__ : List[str] = ( ResNetShortCut(_a , _a , stride=_a ) if should_apply_shortcut else nn.Identity() ) SCREAMING_SNAKE_CASE__ : str = nn.Sequential( ResNetConvLayer(_a , _a , stride=_a ) , ResNetConvLayer(_a , _a , activation=_a ) , ) SCREAMING_SNAKE_CASE__ : Any = ACTaFN[activation] def _a ( self , _a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_state SCREAMING_SNAKE_CASE__ : List[Any] = self.layer(_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.shortcut(_a ) hidden_state += residual SCREAMING_SNAKE_CASE__ : Any = self.activation(_a ) return hidden_state class __a (nn.Module): '''simple docstring''' def __init__( self , _a , _a , _a = 1 , _a = "relu" , _a = 4 ) -> int: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Optional[Any] = in_channels != out_channels or stride != 1 SCREAMING_SNAKE_CASE__ : Optional[Any] = out_channels // reduction SCREAMING_SNAKE_CASE__ : Any = ( ResNetShortCut(_a , _a , stride=_a ) if should_apply_shortcut else nn.Identity() ) SCREAMING_SNAKE_CASE__ : Dict = nn.Sequential( ResNetConvLayer(_a , _a , kernel_size=1 ) , ResNetConvLayer(_a , _a , stride=_a ) , ResNetConvLayer(_a , _a , kernel_size=1 , activation=_a ) , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ACTaFN[activation] def _a ( self , _a ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_state SCREAMING_SNAKE_CASE__ : List[str] = self.layer(_a ) SCREAMING_SNAKE_CASE__ : str = self.shortcut(_a ) hidden_state += residual SCREAMING_SNAKE_CASE__ : Optional[int] = self.activation(_a ) return hidden_state class __a (nn.Module): '''simple docstring''' def __init__( self , _a , _a , _a , _a = 2 , _a = 2 , ) -> Optional[int]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : int = ResNetBottleNeckLayer if config.layer_type == """bottleneck""" else ResNetBasicLayer SCREAMING_SNAKE_CASE__ : Dict = nn.Sequential( # downsampling is done in the first layer with stride of 2 layer(_a , _a , stride=_a , activation=config.hidden_act ) , *[layer(_a , _a , activation=config.hidden_act ) for _ in range(depth - 1 )] , ) def _a ( self , _a ) -> Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = input for layer in self.layers: SCREAMING_SNAKE_CASE__ : Optional[int] = layer(_a ) return hidden_state class __a (nn.Module): '''simple docstring''' def __init__( self , _a ) -> Union[str, Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Dict = nn.ModuleList([] ) # based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input self.stages.append( ResNetStage( _a , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , ) ) SCREAMING_SNAKE_CASE__ : Tuple = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for (in_channels, out_channels), depth in zip(_a , config.depths[1:] ): self.stages.append(ResNetStage(_a , _a , _a , depth=_a ) ) def _a ( self , _a , _a = False , _a = True ) -> BaseModelOutputWithNoAttention: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: SCREAMING_SNAKE_CASE__ : str = hidden_states + (hidden_state,) SCREAMING_SNAKE_CASE__ : Any = stage_module(_a ) if output_hidden_states: SCREAMING_SNAKE_CASE__ : List[Any] = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return BaseModelOutputWithNoAttention( last_hidden_state=_a , hidden_states=_a , ) class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = ResNetConfig _SCREAMING_SNAKE_CASE :int = """resnet""" _SCREAMING_SNAKE_CASE :Dict = """pixel_values""" _SCREAMING_SNAKE_CASE :str = True def _a ( self , _a ) -> Any: """simple docstring""" if isinstance(_a , nn.Convad ): nn.init.kaiming_normal_(module.weight , mode="""fan_out""" , nonlinearity="""relu""" ) elif isinstance(_a , (nn.BatchNormad, nn.GroupNorm) ): nn.init.constant_(module.weight , 1 ) nn.init.constant_(module.bias , 0 ) def _a ( self , _a , _a=False ) -> Tuple: """simple docstring""" if isinstance(_a , _a ): SCREAMING_SNAKE_CASE__ : List[str] = value a :List[Any] = r"\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`ResNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n" a :str = r"\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConvNextImageProcessor.__call__`] for details.\n\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n" @add_start_docstrings( """The bare ResNet model outputting raw features without any specific head on top.""" , UpperCamelCase_ , ) class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , _a ) -> Any: """simple docstring""" super().__init__(_a ) SCREAMING_SNAKE_CASE__ : int = config SCREAMING_SNAKE_CASE__ : Dict = ResNetEmbeddings(_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ResNetEncoder(_a ) SCREAMING_SNAKE_CASE__ : List[str] = nn.AdaptiveAvgPoolad((1, 1) ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(_a ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=_a , config_class=_CONFIG_FOR_DOC , modality="""vision""" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def _a ( self , _a , _a = None , _a = None ) -> BaseModelOutputWithPoolingAndNoAttention: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) SCREAMING_SNAKE_CASE__ : Any = return_dict if return_dict is not None else self.config.use_return_dict SCREAMING_SNAKE_CASE__ : str = self.embedder(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = self.encoder( _a , output_hidden_states=_a , return_dict=_a ) SCREAMING_SNAKE_CASE__ : Dict = encoder_outputs[0] SCREAMING_SNAKE_CASE__ : int = self.pooler(_a ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=_a , pooler_output=_a , hidden_states=encoder_outputs.hidden_states , ) @add_start_docstrings( """ ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. """ , UpperCamelCase_ , ) class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , _a ) -> Optional[int]: """simple docstring""" super().__init__(_a ) SCREAMING_SNAKE_CASE__ : Tuple = config.num_labels SCREAMING_SNAKE_CASE__ : Any = ResNetModel(_a ) # classification head SCREAMING_SNAKE_CASE__ : Optional[Any] = nn.Sequential( nn.Flatten() , nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() , ) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(_a ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=_a , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def _a ( self , _a = None , _a = None , _a = None , _a = None , ) -> ImageClassifierOutputWithNoAttention: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = return_dict if return_dict is not None else self.config.use_return_dict SCREAMING_SNAKE_CASE__ : List[str] = self.resnet(_a , output_hidden_states=_a , return_dict=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = outputs.pooler_output if return_dict else outputs[1] SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.classifier(_a ) SCREAMING_SNAKE_CASE__ : int = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: SCREAMING_SNAKE_CASE__ : Any = """regression""" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): SCREAMING_SNAKE_CASE__ : Dict = """single_label_classification""" else: SCREAMING_SNAKE_CASE__ : Dict = """multi_label_classification""" if self.config.problem_type == "regression": SCREAMING_SNAKE_CASE__ : Optional[int] = MSELoss() if self.num_labels == 1: SCREAMING_SNAKE_CASE__ : Any = loss_fct(logits.squeeze() , labels.squeeze() ) else: SCREAMING_SNAKE_CASE__ : List[Any] = loss_fct(_a , _a ) elif self.config.problem_type == "single_label_classification": SCREAMING_SNAKE_CASE__ : Tuple = CrossEntropyLoss() SCREAMING_SNAKE_CASE__ : str = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": SCREAMING_SNAKE_CASE__ : Union[str, Any] = BCEWithLogitsLoss() SCREAMING_SNAKE_CASE__ : List[str] = loss_fct(_a , _a ) if not return_dict: SCREAMING_SNAKE_CASE__ : Optional[int] = (logits,) + outputs[2:] return (loss,) + output if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=_a , logits=_a , hidden_states=outputs.hidden_states ) @add_start_docstrings( """ ResNet backbone, to be used with frameworks like DETR and MaskFormer. """ , UpperCamelCase_ , ) class __a (UpperCamelCase_ , UpperCamelCase_): '''simple docstring''' def __init__( self , _a ) -> int: """simple docstring""" super().__init__(_a ) super()._init_backbone(_a ) SCREAMING_SNAKE_CASE__ : List[str] = [config.embedding_size] + config.hidden_sizes SCREAMING_SNAKE_CASE__ : List[str] = ResNetEmbeddings(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ResNetEncoder(_a ) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(_a ) @replace_return_docstrings(output_type=_a , config_class=_CONFIG_FOR_DOC ) def _a ( self , _a , _a = None , _a = None ) -> BackboneOutput: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = return_dict if return_dict is not None else self.config.use_return_dict SCREAMING_SNAKE_CASE__ : List[str] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) SCREAMING_SNAKE_CASE__ : Tuple = self.embedder(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.encoder(_a , output_hidden_states=_a , return_dict=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = outputs.hidden_states SCREAMING_SNAKE_CASE__ : Dict = () for idx, stage in enumerate(self.stage_names ): if stage in self.out_features: feature_maps += (hidden_states[idx],) if not return_dict: SCREAMING_SNAKE_CASE__ : int = (feature_maps,) if output_hidden_states: output += (outputs.hidden_states,) return output return BackboneOutput( feature_maps=_a , hidden_states=outputs.hidden_states if output_hidden_states else None , attentions=_a , )
680
"""simple docstring""" import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class __a (enum.Enum): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = 0 _SCREAMING_SNAKE_CASE :List[Any] = 1 _SCREAMING_SNAKE_CASE :Dict = 2 @add_end_docstrings(UpperCamelCase_) class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = """ In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision and denounces one of the men as a horse thief. Although his father initially slaps him for making such an accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop, begging for his blessing. <eod> </s> <eos> """ def __init__( self , *_a , **_a ) -> Tuple: """simple docstring""" super().__init__(*_a , **_a ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == """tf""" else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. SCREAMING_SNAKE_CASE__ : Any = None if self.model.config.prefix is not None: SCREAMING_SNAKE_CASE__ : List[str] = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. SCREAMING_SNAKE_CASE__ : Optional[Any] = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self._sanitize_parameters(prefix=_a , **self._forward_params ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {**self._preprocess_params, **preprocess_params} SCREAMING_SNAKE_CASE__ : Optional[Any] = {**self._forward_params, **forward_params} def _a ( self , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , **_a , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = {} if prefix is not None: SCREAMING_SNAKE_CASE__ : Dict = prefix if prefix: SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer( _a , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Tuple = prefix_inputs["""input_ids"""].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( f'''{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected''' """ [None, 'hole']""" ) SCREAMING_SNAKE_CASE__ : int = handle_long_generation preprocess_params.update(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs SCREAMING_SNAKE_CASE__ : int = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_full_text`""" ) if return_tensors is not None: raise ValueError("""`return_full_text` is mutually exclusive with `return_tensors`""" ) SCREAMING_SNAKE_CASE__ : List[Any] = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_tensors`""" ) SCREAMING_SNAKE_CASE__ : Tuple = ReturnType.TENSORS if return_type is not None: SCREAMING_SNAKE_CASE__ : int = return_type if clean_up_tokenization_spaces is not None: SCREAMING_SNAKE_CASE__ : List[str] = clean_up_tokenization_spaces if stop_sequence is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.encode(_a , add_special_tokens=_a ) if len(_a ) > 1: warnings.warn( """Stopping on a multiple token sequence is not yet supported on transformers. The first token of""" """ the stop sequence will be used as the stop sequence string in the interim.""" ) SCREAMING_SNAKE_CASE__ : List[Any] = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def _a ( self , *_a , **_a ) -> Any: """simple docstring""" if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({"""add_space_before_punct_symbol""": True} ) return super()._parse_and_tokenize(*_a , **_a ) def __call__( self , _a , **_a ) -> Optional[int]: """simple docstring""" return super().__call__(_a , **_a ) def _a ( self , _a , _a="" , _a=None , **_a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer( prefix + prompt_text , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Tuple = prompt_text if handle_long_generation == "hole": SCREAMING_SNAKE_CASE__ : List[Any] = inputs["""input_ids"""].shape[-1] if "max_new_tokens" in generate_kwargs: SCREAMING_SNAKE_CASE__ : Union[str, Any] = generate_kwargs["""max_new_tokens"""] else: SCREAMING_SNAKE_CASE__ : Tuple = generate_kwargs.get("""max_length""" , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError("""We cannot infer how many new tokens are expected""" ) if cur_len + new_tokens > self.tokenizer.model_max_length: SCREAMING_SNAKE_CASE__ : str = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( """We cannot use `hole` to handle this generation the number of desired tokens exceeds the""" """ models max length""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs["""input_ids"""][:, -keep_length:] if "attention_mask" in inputs: SCREAMING_SNAKE_CASE__ : Optional[int] = inputs["""attention_mask"""][:, -keep_length:] return inputs def _a ( self , _a , **_a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_inputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : Optional[int] = model_inputs.get("""attention_mask""" , _a ) # Allow empty prompts if input_ids.shape[1] == 0: SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : List[Any] = None SCREAMING_SNAKE_CASE__ : List[str] = 1 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.shape[0] SCREAMING_SNAKE_CASE__ : Tuple = model_inputs.pop("""prompt_text""" ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs.pop("""prefix_length""" , 0 ) if prefix_length > 0: SCREAMING_SNAKE_CASE__ : List[str] = """max_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].max_new_tokens is not None ) if not has_max_new_tokens: SCREAMING_SNAKE_CASE__ : int = generate_kwargs.get("""max_length""" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length SCREAMING_SNAKE_CASE__ : Dict = """min_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL SCREAMING_SNAKE_CASE__ : Tuple = self.model.generate(input_ids=_a , attention_mask=_a , **_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = generated_sequence.shape[0] if self.framework == "pt": SCREAMING_SNAKE_CASE__ : str = generated_sequence.reshape(_a , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.reshape(_a , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def _a ( self , _a , _a=ReturnType.FULL_TEXT , _a=True ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = model_outputs["""generated_sequence"""][0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_outputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : str = model_outputs["""prompt_text"""] SCREAMING_SNAKE_CASE__ : Any = generated_sequence.numpy().tolist() SCREAMING_SNAKE_CASE__ : List[Any] = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: SCREAMING_SNAKE_CASE__ : Tuple = {"""generated_token_ids""": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.decode( _a , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: SCREAMING_SNAKE_CASE__ : Dict = 0 else: SCREAMING_SNAKE_CASE__ : Optional[int] = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) ) if return_type == ReturnType.FULL_TEXT: SCREAMING_SNAKE_CASE__ : Tuple = prompt_text + text[prompt_length:] else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = text[prompt_length:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {"""generated_text""": all_text} records.append(_a ) return records
680
1
"""simple docstring""" import argparse import os import evaluate import torch from datasets import load_dataset 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 # and perform gradient accumulation # # 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 run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a :str = 16 a :Union[str, Any] = 32 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase = 16 ) -> Tuple: SCREAMING_SNAKE_CASE__ : int = AutoTokenizer.from_pretrained("""bert-base-cased""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__lowerCAmelCase ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__lowerCAmelCase , max_length=__lowerCAmelCase ) 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(): SCREAMING_SNAKE_CASE__ : List[str] = datasets.map( __lowerCAmelCase , batched=__lowerCAmelCase , 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 SCREAMING_SNAKE_CASE__ : Any = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__lowerCAmelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE__ : int = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE__ : str = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE__ : Dict = 8 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = None return tokenizer.pad( __lowerCAmelCase , padding="""longest""" , max_length=__lowerCAmelCase , pad_to_multiple_of=__lowerCAmelCase , return_tensors="""pt""" , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE__ : int = DataLoader( tokenized_datasets["""train"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = DataLoader( tokenized_datasets["""validation"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": from accelerate.test_utils.training import mocked_dataloaders a :Dict = mocked_dataloaders # noqa: F811 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , __lowerCAmelCase ) == "1": SCREAMING_SNAKE_CASE__ : Optional[int] = 2 # New Code # SCREAMING_SNAKE_CASE__ : Optional[int] = int(args.gradient_accumulation_steps ) # Initialize accelerator SCREAMING_SNAKE_CASE__ : Optional[Any] = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=__lowerCAmelCase ) if accelerator.distributed_type == DistributedType.TPU and gradient_accumulation_steps > 1: raise NotImplementedError( """Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE__ : Any = config["""lr"""] SCREAMING_SNAKE_CASE__ : str = int(config["""num_epochs"""] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = int(config["""seed"""] ) SCREAMING_SNAKE_CASE__ : List[str] = int(config["""batch_size"""] ) SCREAMING_SNAKE_CASE__ : Any = evaluate.load("""glue""" , """mrpc""" ) set_seed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = get_dataloaders(__lowerCAmelCase , __lowerCAmelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE__ : int = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=__lowerCAmelCase ) # 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). SCREAMING_SNAKE_CASE__ : int = model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE__ : Union[str, Any] = AdamW(params=model.parameters() , lr=__lowerCAmelCase ) # Instantiate scheduler SCREAMING_SNAKE_CASE__ : Any = get_linear_schedule_with_warmup( optimizer=__lowerCAmelCase , num_warmup_steps=100 , num_training_steps=(len(__lowerCAmelCase ) * num_epochs) , ) # 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. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = accelerator.prepare( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Now we train the model for epoch in range(__lowerCAmelCase ): model.train() for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = output.loss accelerator.backward(__lowerCAmelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=__lowerCAmelCase , references=__lowerCAmelCase , ) SCREAMING_SNAKE_CASE__ : List[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , __lowerCAmelCase ) def _lowercase ( ) -> Any: SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=__lowerCAmelCase , default=__lowerCAmelCase , 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.""" , ) # New Code # parser.add_argument( """--gradient_accumulation_steps""" , type=__lowerCAmelCase , default=1 , help="""The number of minibatches to be ran before gradients are accumulated.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : int = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": main()
680
"""simple docstring""" from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> list[float]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = coefficient_matrix.shape SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE__ : Tuple = F'''Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if colsa != 1: SCREAMING_SNAKE_CASE__ : str = F'''Constant matrix must be nx1 but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if rowsa != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Coefficient and constant matrices dimensions must be nxn and nx1 but """ F'''received {rowsa}x{colsa} and {rowsa}x{colsa}''' ) raise ValueError(__lowerCAmelCase ) if len(__lowerCAmelCase ) != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Number of initial values must be equal to number of rows in coefficient """ F'''matrix but received {len(__lowerCAmelCase )} and {rowsa}''' ) raise ValueError(__lowerCAmelCase ) if iterations <= 0: raise ValueError("""Iterations must be at least 1""" ) SCREAMING_SNAKE_CASE__ : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = table.shape strictly_diagonally_dominant(__lowerCAmelCase ) # Iterates the whole matrix for given number of times for _ in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = [] for row in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = 0 for col in range(__lowerCAmelCase ): if col == row: SCREAMING_SNAKE_CASE__ : int = table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE__ : Any = (temp + val) / denom new_val.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = new_val return [float(__lowerCAmelCase ) for i in new_val] def _lowercase ( __lowerCAmelCase ) -> bool: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = table.shape SCREAMING_SNAKE_CASE__ : str = True for i in range(0 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("""Coefficient matrix is not strictly diagonally dominant""" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
680
1
"""simple docstring""" from .constants import ( MODEL_NAME, OPTIMIZER_NAME, RNG_STATE_NAME, SAFE_WEIGHTS_INDEX_NAME, SAFE_WEIGHTS_NAME, SCALER_NAME, SCHEDULER_NAME, TORCH_LAUNCH_PARAMS, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ) from .dataclasses import ( BnbQuantizationConfig, ComputeEnvironment, CustomDtype, DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, DynamoBackend, FPaRecipeKwargs, FullyShardedDataParallelPlugin, GradientAccumulationPlugin, GradScalerKwargs, InitProcessGroupKwargs, KwargsHandler, LoggerType, MegatronLMPlugin, PrecisionType, ProjectConfiguration, RNGType, SageMakerDistributedType, TensorInformation, TorchDynamoPlugin, ) from .environment import get_int_from_env, parse_choice_from_env, parse_flag_from_env from .imports import ( get_ccl_version, is_abit_bnb_available, is_abit_bnb_available, is_aim_available, is_bfaa_available, is_bnb_available, is_botoa_available, is_ccl_available, is_comet_ml_available, is_datasets_available, is_deepspeed_available, is_fpa_available, is_ipex_available, is_megatron_lm_available, is_mlflow_available, is_mps_available, is_npu_available, is_rich_available, is_safetensors_available, is_sagemaker_available, is_tensorboard_available, is_tpu_available, is_transformers_available, is_wandb_available, is_xpu_available, ) from .modeling import ( check_device_map, check_tied_parameters_in_config, check_tied_parameters_on_same_device, compute_module_sizes, convert_file_size_to_int, dtype_byte_size, find_tied_parameters, get_balanced_memory, get_max_layer_size, get_max_memory, get_mixed_precision_context_manager, id_tensor_storage, infer_auto_device_map, load_checkpoint_in_model, load_offloaded_weights, load_state_dict, named_module_tensors, retie_parameters, set_module_tensor_to_device, shard_checkpoint, ) from .offload import ( OffloadedWeightsLoader, PrefixedDataset, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, save_offload_index, ) from .operations import ( broadcast, broadcast_object_list, concatenate, convert_outputs_to_fpaa, convert_to_fpaa, find_batch_size, find_device, gather, gather_object, get_data_structure, honor_type, initialize_tensors, is_namedtuple, is_tensor_information, is_torch_tensor, listify, pad_across_processes, recursively_apply, reduce, send_to_device, slice_tensors, ) from .versions import compare_versions, is_torch_version if is_deepspeed_available(): from .deepspeed import ( DeepSpeedEngineWrapper, DeepSpeedOptimizerWrapper, DeepSpeedSchedulerWrapper, DummyOptim, DummyScheduler, HfDeepSpeedConfig, ) from .bnb import has_abit_bnb_layers, load_and_quantize_model from .fsdp_utils import load_fsdp_model, load_fsdp_optimizer, save_fsdp_model, save_fsdp_optimizer from .launch import ( PrepareForLaunch, _filter_args, prepare_deepspeed_cmd_env, prepare_multi_gpu_env, prepare_sagemager_args_inputs, prepare_simple_launcher_cmd_env, prepare_tpu, ) from .megatron_lm import ( AbstractTrainStep, BertTrainStep, GPTTrainStep, MegatronEngine, MegatronLMDummyDataLoader, MegatronLMDummyScheduler, MegatronLMOptimizerWrapper, MegatronLMSchedulerWrapper, TaTrainStep, avg_losses_across_data_parallel_group, gather_across_data_parallel_groups, ) from .megatron_lm import initialize as megatron_lm_initialize from .megatron_lm import prepare_data_loader as megatron_lm_prepare_data_loader from .megatron_lm import prepare_model as megatron_lm_prepare_model from .megatron_lm import prepare_optimizer as megatron_lm_prepare_optimizer from .megatron_lm import prepare_scheduler as megatron_lm_prepare_scheduler from .memory import find_executable_batch_size, release_memory from .other import ( extract_model_from_parallel, get_pretty_name, is_port_in_use, merge_dicts, patch_environment, save, wait_for_everyone, write_basic_config, ) from .random import set_seed, synchronize_rng_state, synchronize_rng_states from .torch_xla import install_xla from .tqdm import tqdm from .transformer_engine import convert_model, has_transformer_engine_layers
680
"""simple docstring""" import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Union[str, Path]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = True _SCREAMING_SNAKE_CASE :Optional[int] = None _SCREAMING_SNAKE_CASE :int = 1 _SCREAMING_SNAKE_CASE :Optional[Union[str, bool]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None def _a ( self ) -> "DownloadConfig": """simple docstring""" return self.__class__(**{k: copy.deepcopy(_a ) for k, v in self.__dict__.items()} )
680
1
"""simple docstring""" import math import os import sys def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Union[str, Any] = """""" try: with open(__lowerCAmelCase , """rb""" ) as binary_file: SCREAMING_SNAKE_CASE__ : Optional[int] = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Dict = F'''{dat:08b}''' result += curr_byte return result except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> None: lexicon.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = last_match_id if math.loga(__lowerCAmelCase ).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE__ : Dict = """0""" + lexicon[curr_key] SCREAMING_SNAKE_CASE__ : str = bin(__lowerCAmelCase )[2:] def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Dict = {"""0""": """0""", """1""": """1"""} SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = """""", """""" SCREAMING_SNAKE_CASE__ : Any = len(__lowerCAmelCase ) for i in range(len(__lowerCAmelCase ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon[curr_string] result += last_match_id add_key_to_lexicon(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) index += 1 SCREAMING_SNAKE_CASE__ : List[str] = """""" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE__ : List[Any] = lexicon[curr_string] result += last_match_id return result def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Any = os.path.getsize(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = bin(__lowerCAmelCase )[2:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = len(__lowerCAmelCase ) return "0" * (length_length - 1) + file_length_binary + compressed def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Optional[int] = 8 try: with open(__lowerCAmelCase , """wb""" ) as opened_file: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ to_write[i : i + byte_length] for i in range(0 , len(__lowerCAmelCase ) , __lowerCAmelCase ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("""10000000""" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(__lowerCAmelCase , 2 ).to_bytes(1 , byteorder="""big""" ) ) except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Dict = read_file_binary(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = compress_data(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = add_file_length(__lowerCAmelCase , __lowerCAmelCase ) write_file_binary(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
680
"""simple docstring""" import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger a :Optional[Any] = "<<<<<<< This should probably be modified because it mentions: " a :Tuple = "=======\n>>>>>>>\n" a :str = [ "TextEncoderConfig", "ByteTextEncoder", "SubwordTextEncoder", "encoder_config", "maybe_build_from_corpus", "manual_dir", ] a :Union[str, Any] = [ # (pattern, replacement) # Order is important here for some replacements (r"tfds\.core", r"datasets"), (r"tf\.io\.gfile\.GFile", r"open"), (r"tf\.([\w\d]+)", r"datasets.Value('\1')"), (r"tfds\.features\.Text\(\)", r"datasets.Value('string')"), (r"tfds\.features\.Text\(", r"datasets.Value('string'),"), (r"features\s*=\s*tfds.features.FeaturesDict\(", r"features=datasets.Features("), (r"tfds\.features\.FeaturesDict\(", r"dict("), (r"The TensorFlow Datasets Authors", r"The TensorFlow Datasets Authors and the HuggingFace Datasets Authors"), (r"tfds\.", r"datasets."), (r"dl_manager\.manual_dir", r"self.config.data_dir"), (r"self\.builder_config", r"self.config"), ] def _lowercase ( __lowerCAmelCase ) -> int: return ConvertCommand(args.tfds_path , args.datasets_directory ) class __a (UpperCamelCase_): '''simple docstring''' @staticmethod def _a ( _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.add_parser( """convert""" , help="""Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.""" , ) train_parser.add_argument( """--tfds_path""" , type=_a , required=_a , help="""Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.""" , ) train_parser.add_argument( """--datasets_directory""" , type=_a , required=_a , help="""Path to the HuggingFace Datasets folder.""" ) train_parser.set_defaults(func=_a ) def __init__( self , _a , _a , *_a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = get_logger("""datasets-cli/converting""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tfds_path SCREAMING_SNAKE_CASE__ : List[Any] = datasets_directory def _a ( self ) -> List[str]: """simple docstring""" if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.abspath(self._tfds_path ) elif os.path.isfile(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Tuple = os.path.dirname(self._tfds_path ) else: raise ValueError("""--tfds_path is neither a directory nor a file. Please check path.""" ) SCREAMING_SNAKE_CASE__ : Dict = os.path.abspath(self._datasets_directory ) self._logger.info(f'''Converting datasets from {abs_tfds_path} to {abs_datasets_path}''' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : List[Any] = {} if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.listdir(_a ) else: SCREAMING_SNAKE_CASE__ : List[Any] = [os.path.basename(self._tfds_path )] for f_name in file_names: self._logger.info(f'''Looking at file {f_name}''' ) SCREAMING_SNAKE_CASE__ : int = os.path.join(_a , _a ) SCREAMING_SNAKE_CASE__ : Dict = os.path.join(_a , _a ) if not os.path.isfile(_a ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info("""Skipping file""" ) continue with open(_a , encoding="""utf-8""" ) as f: SCREAMING_SNAKE_CASE__ : List[str] = f.readlines() SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = False SCREAMING_SNAKE_CASE__ : Optional[int] = False SCREAMING_SNAKE_CASE__ : Dict = [] for line in lines: SCREAMING_SNAKE_CASE__ : List[str] = line # Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: SCREAMING_SNAKE_CASE__ : List[Any] = """import datasets\n""" elif "import tensorflow" in out_line: # order is important here SCREAMING_SNAKE_CASE__ : Optional[Any] = """""" continue elif "from absl import logging" in out_line: SCREAMING_SNAKE_CASE__ : Any = """from datasets import logging\n""" elif "getLogger" in out_line: SCREAMING_SNAKE_CASE__ : Optional[int] = out_line.replace("""getLogger""" , """get_logger""" ) elif any(expression in out_line for expression in TO_HIGHLIGHT ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Tuple = list(filter(lambda _a : e in out_line , _a ) ) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(_a ) + """\n""" ) out_lines.append(_a ) out_lines.append(_a ) continue else: for pattern, replacement in TO_CONVERT: SCREAMING_SNAKE_CASE__ : int = re.sub(_a , _a , _a ) # Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: SCREAMING_SNAKE_CASE__ : Dict = re.match(r"""from\stensorflow_datasets.*import\s([^\.\r\n]+)""" , _a ) tfds_imports.extend(imp.strip() for imp in match.group(1 ).split(""",""" ) ) SCREAMING_SNAKE_CASE__ : Dict = """from . import """ + match.group(1 ) # Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(f'''Error converting {out_line.strip()}''' ) if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line: SCREAMING_SNAKE_CASE__ : Union[str, Any] = True out_lines.append(_a ) if is_builder or "wmt" in f_name: # We create a new directory for each dataset SCREAMING_SNAKE_CASE__ : Union[str, Any] = f_name.replace(""".py""" , """""" ) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(_a , _a ) SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(_a , _a ) os.makedirs(_a , exist_ok=_a ) self._logger.info(f'''Adding directory {output_dir}''' ) imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} ) else: # Utilities will be moved at the end utils_files.append(_a ) if needs_manual_update: with_manual_update.append(_a ) with open(_a , """w""" , encoding="""utf-8""" ) as f: f.writelines(_a ) self._logger.info(f'''Converted in {output_file}''' ) for utils_file in utils_files: try: SCREAMING_SNAKE_CASE__ : str = os.path.basename(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = imports_to_builder_map[f_name.replace(""".py""" , """""" )] self._logger.info(f'''Moving {dest_folder} to {utils_file}''' ) shutil.copy(_a , _a ) except KeyError: self._logger.error(f'''Cannot find destination folder for {utils_file}. Please copy manually.''' ) if with_manual_update: for file_path in with_manual_update: self._logger.warning( f'''You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.''' )
680
1
"""simple docstring""" from math import asin, atan, cos, radians, sin, sqrt, tan a :List[Any] = 637_8137.0 a :Dict = 635_6752.31_4245 a :Optional[int] = 6_378_137 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> float: SCREAMING_SNAKE_CASE__ : Tuple = (AXIS_A - AXIS_B) / AXIS_A SCREAMING_SNAKE_CASE__ : Optional[Any] = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : Tuple = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : Dict = radians(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : int = radians(__lowerCAmelCase ) # Equation SCREAMING_SNAKE_CASE__ : Union[str, Any] = sin((phi_a - phi_a) / 2 ) SCREAMING_SNAKE_CASE__ : Tuple = sin((lambda_a - lambda_a) / 2 ) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda SCREAMING_SNAKE_CASE__ : List[str] = sqrt(sin_sq_phi + (cos(__lowerCAmelCase ) * cos(__lowerCAmelCase ) * sin_sq_lambda) ) return 2 * RADIUS * asin(__lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
680
"""simple docstring""" from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance a :str = 637_8137.0 a :Optional[Any] = 635_6752.31_4245 a :List[Any] = 6_378_137 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> float: SCREAMING_SNAKE_CASE__ : Dict = (AXIS_A - AXIS_B) / AXIS_A # Parametric latitudes # https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) # Compute central angle between two points # using haversine theta. sigma = haversine_distance / equatorial radius SCREAMING_SNAKE_CASE__ : Tuple = haversine_distance(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) / EQUATORIAL_RADIUS # Intermediate P and Q values SCREAMING_SNAKE_CASE__ : List[str] = (b_lata + b_lata) / 2 SCREAMING_SNAKE_CASE__ : Dict = (b_lata - b_lata) / 2 # Intermediate X value # X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2) SCREAMING_SNAKE_CASE__ : Tuple = (sin(__lowerCAmelCase ) ** 2) * (cos(__lowerCAmelCase ) ** 2) SCREAMING_SNAKE_CASE__ : str = cos(sigma / 2 ) ** 2 SCREAMING_SNAKE_CASE__ : List[str] = (sigma - sin(__lowerCAmelCase )) * (x_numerator / x_demonimator) # Intermediate Y value # Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2) SCREAMING_SNAKE_CASE__ : int = (cos(__lowerCAmelCase ) ** 2) * (sin(__lowerCAmelCase ) ** 2) SCREAMING_SNAKE_CASE__ : int = sin(sigma / 2 ) ** 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = (sigma + sin(__lowerCAmelCase )) * (y_numerator / y_denominator) return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value))) if __name__ == "__main__": import doctest doctest.testmod()
680
1
"""simple docstring""" def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> int: return (pointa[0] - pointa[0]) ** 2 + (pointa[1] - pointa[1]) ** 2 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase=0 ) -> List[str]: return sorted(__lowerCAmelCase , key=lambda __lowerCAmelCase : x[column] ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=float("""inf""" ) ) -> List[Any]: for i in range(points_counts - 1 ): for j in range(i + 1 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[Any] = euclidean_distance_sqr(points[i] , points[j] ) if current_dis < min_dis: SCREAMING_SNAKE_CASE__ : List[Any] = current_dis return min_dis def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=float("""inf""" ) ) -> Optional[Any]: for i in range(min(6 , points_counts - 1 ) , __lowerCAmelCase ): for j in range(max(0 , i - 6 ) , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = euclidean_distance_sqr(points[i] , points[j] ) if current_dis < min_dis: SCREAMING_SNAKE_CASE__ : List[Any] = current_dis return min_dis def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: # base case if points_counts <= 3: return dis_between_closest_pair(__lowerCAmelCase , __lowerCAmelCase ) # recursion SCREAMING_SNAKE_CASE__ : Tuple = points_counts // 2 SCREAMING_SNAKE_CASE__ : Any = closest_pair_of_points_sqr( __lowerCAmelCase , points_sorted_on_y[:mid] , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = closest_pair_of_points_sqr( __lowerCAmelCase , points_sorted_on_y[mid:] , points_counts - mid ) SCREAMING_SNAKE_CASE__ : int = min(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = [] for point in points_sorted_on_x: if abs(point[0] - points_sorted_on_x[mid][0] ) < closest_pair_dis: cross_strip.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = dis_between_closest_in_strip( __lowerCAmelCase , len(__lowerCAmelCase ) , __lowerCAmelCase ) return min(__lowerCAmelCase , __lowerCAmelCase ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[int] = column_based_sort(__lowerCAmelCase , column=0 ) SCREAMING_SNAKE_CASE__ : List[Any] = column_based_sort(__lowerCAmelCase , column=1 ) return ( closest_pair_of_points_sqr( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) ) ** 0.5 if __name__ == "__main__": a :List[str] = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)] print("Distance:", closest_pair_of_points(points, len(points)))
680
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision.transforms import functional as F from transformers import DetrImageProcessor, TableTransformerConfig, TableTransformerForObjectDetection from transformers.utils import logging logging.set_verbosity_info() a :Any = logging.get_logger(__name__) # here we list all keys to be renamed (original name on the left, our name on the right) a :str = [] for i in range(6): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (f'transformer.encoder.layers.{i}.self_attn.out_proj.weight', f'encoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (f'transformer.encoder.layers.{i}.self_attn.out_proj.bias', f'encoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append((f'transformer.encoder.layers.{i}.linear1.weight', f'encoder.layers.{i}.fc1.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.linear1.bias', f'encoder.layers.{i}.fc1.bias')) rename_keys.append((f'transformer.encoder.layers.{i}.linear2.weight', f'encoder.layers.{i}.fc2.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.linear2.bias', f'encoder.layers.{i}.fc2.bias')) rename_keys.append( (f'transformer.encoder.layers.{i}.norm1.weight', f'encoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((f'transformer.encoder.layers.{i}.norm1.bias', f'encoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append((f'transformer.encoder.layers.{i}.norm2.weight', f'encoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.norm2.bias', f'encoder.layers.{i}.final_layer_norm.bias')) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( (f'transformer.decoder.layers.{i}.self_attn.out_proj.weight', f'decoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (f'transformer.decoder.layers.{i}.self_attn.out_proj.bias', f'decoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append( ( f'transformer.decoder.layers.{i}.multihead_attn.out_proj.weight', f'decoder.layers.{i}.encoder_attn.out_proj.weight', ) ) rename_keys.append( ( f'transformer.decoder.layers.{i}.multihead_attn.out_proj.bias', f'decoder.layers.{i}.encoder_attn.out_proj.bias', ) ) rename_keys.append((f'transformer.decoder.layers.{i}.linear1.weight', f'decoder.layers.{i}.fc1.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.linear1.bias', f'decoder.layers.{i}.fc1.bias')) rename_keys.append((f'transformer.decoder.layers.{i}.linear2.weight', f'decoder.layers.{i}.fc2.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.linear2.bias', f'decoder.layers.{i}.fc2.bias')) rename_keys.append( (f'transformer.decoder.layers.{i}.norm1.weight', f'decoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((f'transformer.decoder.layers.{i}.norm1.bias', f'decoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append( (f'transformer.decoder.layers.{i}.norm2.weight', f'decoder.layers.{i}.encoder_attn_layer_norm.weight') ) rename_keys.append( (f'transformer.decoder.layers.{i}.norm2.bias', f'decoder.layers.{i}.encoder_attn_layer_norm.bias') ) rename_keys.append((f'transformer.decoder.layers.{i}.norm3.weight', f'decoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.norm3.bias', f'decoder.layers.{i}.final_layer_norm.bias')) # convolutional projection + query embeddings + layernorm of encoder + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ("input_proj.weight", "input_projection.weight"), ("input_proj.bias", "input_projection.bias"), ("query_embed.weight", "query_position_embeddings.weight"), ("transformer.encoder.norm.weight", "encoder.layernorm.weight"), ("transformer.encoder.norm.bias", "encoder.layernorm.bias"), ("transformer.decoder.norm.weight", "decoder.layernorm.weight"), ("transformer.decoder.norm.bias", "decoder.layernorm.bias"), ("class_embed.weight", "class_labels_classifier.weight"), ("class_embed.bias", "class_labels_classifier.bias"), ("bbox_embed.layers.0.weight", "bbox_predictor.layers.0.weight"), ("bbox_embed.layers.0.bias", "bbox_predictor.layers.0.bias"), ("bbox_embed.layers.1.weight", "bbox_predictor.layers.1.weight"), ("bbox_embed.layers.1.bias", "bbox_predictor.layers.1.bias"), ("bbox_embed.layers.2.weight", "bbox_predictor.layers.2.weight"), ("bbox_embed.layers.2.bias", "bbox_predictor.layers.2.bias"), ] ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Tuple = state_dict.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = val def _lowercase ( __lowerCAmelCase ) -> Tuple: SCREAMING_SNAKE_CASE__ : str = OrderedDict() for key, value in state_dict.items(): if "backbone.0.body" in key: SCREAMING_SNAKE_CASE__ : List[Any] = key.replace("""backbone.0.body""" , """backbone.conv_encoder.model""" ) SCREAMING_SNAKE_CASE__ : Dict = value else: SCREAMING_SNAKE_CASE__ : Tuple = value return new_state_dict def _lowercase ( __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : str = """""" # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : int = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : int = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE__ : Any = in_proj_bias[:256] SCREAMING_SNAKE_CASE__ : Dict = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[256:512] SCREAMING_SNAKE_CASE__ : int = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[-256:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6 ): # read in weights + bias of input projection layer of self-attention SCREAMING_SNAKE_CASE__ : List[str] = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : Tuple = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Any = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[:256] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[256:512] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias[-256:] # read in weights + bias of input projection layer of cross-attention SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop( F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : List[Any] = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) of cross-attention to the state dict SCREAMING_SNAKE_CASE__ : int = in_proj_weight_cross_attn[:256, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias_cross_attn[:256] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight_cross_attn[256:512, :] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_bias_cross_attn[256:512] SCREAMING_SNAKE_CASE__ : int = in_proj_weight_cross_attn[-256:, :] SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias_cross_attn[-256:] def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = image.size SCREAMING_SNAKE_CASE__ : Optional[Any] = max(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = 800 if """detection""" in checkpoint_url else 1000 SCREAMING_SNAKE_CASE__ : List[str] = target_max_size / current_max_size SCREAMING_SNAKE_CASE__ : str = image.resize((int(round(scale * width ) ), int(round(scale * height ) )) ) return resized_image def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[int] = F.to_tensor(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = F.normalize(__lowerCAmelCase , mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ) return image @torch.no_grad() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Optional[Any]: logger.info("""Converting model...""" ) # load original state dict SCREAMING_SNAKE_CASE__ : str = torch.hub.load_state_dict_from_url(__lowerCAmelCase , map_location="""cpu""" ) # rename keys for src, dest in rename_keys: rename_key(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = rename_backbone_keys(__lowerCAmelCase ) # query, key and value matrices need special treatment read_in_q_k_v(__lowerCAmelCase ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them SCREAMING_SNAKE_CASE__ : Optional[int] = """model.""" for key in state_dict.copy().keys(): if not key.startswith("""class_labels_classifier""" ) and not key.startswith("""bbox_predictor""" ): SCREAMING_SNAKE_CASE__ : Optional[int] = state_dict.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = val # create HuggingFace model and load state dict SCREAMING_SNAKE_CASE__ : Tuple = TableTransformerConfig( backbone="""resnet18""" , mask_loss_coefficient=1 , dice_loss_coefficient=1 , ce_loss_coefficient=1 , bbox_loss_coefficient=5 , giou_loss_coefficient=2 , eos_coefficient=0.4 , class_cost=1 , bbox_cost=5 , giou_cost=2 , ) if "detection" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] = 15 SCREAMING_SNAKE_CASE__ : Any = 2 SCREAMING_SNAKE_CASE__ : str = {0: """table""", 1: """table rotated"""} SCREAMING_SNAKE_CASE__ : Union[str, Any] = idalabel SCREAMING_SNAKE_CASE__ : List[str] = {v: k for k, v in idalabel.items()} else: SCREAMING_SNAKE_CASE__ : Tuple = 125 SCREAMING_SNAKE_CASE__ : str = 6 SCREAMING_SNAKE_CASE__ : List[Any] = { 0: """table""", 1: """table column""", 2: """table row""", 3: """table column header""", 4: """table projected row header""", 5: """table spanning cell""", } SCREAMING_SNAKE_CASE__ : Any = idalabel SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Dict = DetrImageProcessor( format="""coco_detection""" , max_size=800 if """detection""" in checkpoint_url else 1000 ) SCREAMING_SNAKE_CASE__ : Tuple = TableTransformerForObjectDetection(__lowerCAmelCase ) model.load_state_dict(__lowerCAmelCase ) model.eval() # verify our conversion SCREAMING_SNAKE_CASE__ : Dict = """example_pdf.png""" if """detection""" in checkpoint_url else """example_table.png""" SCREAMING_SNAKE_CASE__ : Tuple = hf_hub_download(repo_id="""nielsr/example-pdf""" , repo_type="""dataset""" , filename=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = Image.open(__lowerCAmelCase ).convert("""RGB""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = normalize(resize(__lowerCAmelCase , __lowerCAmelCase ) ).unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : Dict = model(__lowerCAmelCase ) if "detection" in checkpoint_url: SCREAMING_SNAKE_CASE__ : List[Any] = (1, 15, 3) SCREAMING_SNAKE_CASE__ : str = torch.tensor( [[-6.7_897, -16.9_985, 6.7_937], [-8.0_186, -22.2_192, 6.9_677], [-7.3_117, -21.0_708, 7.4_055]] ) SCREAMING_SNAKE_CASE__ : str = torch.tensor([[0.4_867, 0.1_767, 0.6_732], [0.6_718, 0.4_479, 0.3_830], [0.4_716, 0.1_760, 0.6_364]] ) else: SCREAMING_SNAKE_CASE__ : Dict = (1, 125, 7) SCREAMING_SNAKE_CASE__ : Any = torch.tensor( [[-18.1_430, -8.3_214, 4.8_274], [-18.4_685, -7.1_361, -4.2_667], [-26.3_693, -9.3_429, -4.9_962]] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([[0.4_983, 0.5_595, 0.9_440], [0.4_916, 0.6_315, 0.5_954], [0.6_108, 0.8_637, 0.1_135]] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(F'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(__lowerCAmelCase ).mkdir(exist_ok=__lowerCAmelCase ) model.save_pretrained(__lowerCAmelCase ) image_processor.save_pretrained(__lowerCAmelCase ) if push_to_hub: # Push model to HF hub logger.info("""Pushing model to the hub...""" ) SCREAMING_SNAKE_CASE__ : List[Any] = ( """microsoft/table-transformer-detection""" if """detection""" in checkpoint_url else """microsoft/table-transformer-structure-recognition""" ) model.push_to_hub(__lowerCAmelCase ) image_processor.push_to_hub(__lowerCAmelCase ) if __name__ == "__main__": a :Any = argparse.ArgumentParser() parser.add_argument( "--checkpoint_url", default="https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth", type=str, choices=[ "https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth", "https://pubtables1m.blob.core.windows.net/model/pubtables1m_structure_detr_r18.pth", ], help="URL of the Table Transformer checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) a :int = parser.parse_args() convert_table_transformer_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
680
1
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> str: return "".join([hex(__lowerCAmelCase )[2:].zfill(2 ).upper() for byte in list(__lowerCAmelCase )] ) def _lowercase ( __lowerCAmelCase ) -> bytes: # Check data validity, following RFC3548 # https://www.ietf.org/rfc/rfc3548.txt if (len(__lowerCAmelCase ) % 2) != 0: raise ValueError( """Base16 encoded data is invalid: Data does not have an even number of hex digits.""" ) # Check the character set - the standard base16 alphabet # is uppercase according to RFC3548 section 6 if not set(__lowerCAmelCase ) <= set("""0123456789ABCDEF""" ): raise ValueError( """Base16 encoded data is invalid: Data is not uppercase hex or it contains invalid characters.""" ) # For every two hexadecimal digits (= a byte), turn it into an integer. # Then, string the result together into bytes, and return it. return bytes(int(data[i] + data[i + 1] , 16 ) for i in range(0 , len(__lowerCAmelCase ) , 2 ) ) if __name__ == "__main__": import doctest doctest.testmod()
680
"""simple docstring""" from __future__ import annotations import unittest from transformers import 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, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers import ( TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, BertConfig, DPRConfig, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) class __a : '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=2 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , _a=0 , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : str = seq_length SCREAMING_SNAKE_CASE__ : List[str] = is_training SCREAMING_SNAKE_CASE__ : List[str] = use_input_mask SCREAMING_SNAKE_CASE__ : Dict = use_token_type_ids SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE__ : Dict = hidden_size SCREAMING_SNAKE_CASE__ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE__ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : str = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Any = type_vocab_size SCREAMING_SNAKE_CASE__ : int = type_sequence_label_size SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : Any = num_labels SCREAMING_SNAKE_CASE__ : Dict = num_choices SCREAMING_SNAKE_CASE__ : Any = scope SCREAMING_SNAKE_CASE__ : int = projection_dim def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : str = None if self.use_input_mask: # follow test_modeling_tf_ctrl.py SCREAMING_SNAKE_CASE__ : str = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : Any = BertConfig( 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 , ) SCREAMING_SNAKE_CASE__ : str = DPRConfig(projection_dim=self.projection_dim , **config.to_dict() ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRContextEncoder(config=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , attention_mask=_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : str = model(_a ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = TFDPRQuestionEncoder(config=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_a , attention_mask=_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : List[str] = model(_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(_a ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = TFDPRReader(config=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , attention_mask=_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) ) self.parent.assertEqual(result.relevance_logits.shape , (self.batch_size,) ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE__ : int = {"""input_ids""": input_ids} return config, inputs_dict @require_tf class __a (UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = ( ( TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) if is_tf_available() else () ) _SCREAMING_SNAKE_CASE :int = {"""feature-extraction""": TFDPRQuestionEncoder} if is_tf_available() else {} _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = False _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :Dict = False def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFDPRModelTester(self ) SCREAMING_SNAKE_CASE__ : List[str] = ConfigTester(self , config_class=_a , hidden_size=37 ) def _a ( self ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_context_encoder(*_a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_question_encoder(*_a ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_reader(*_a ) @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRContextEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[int] = TFDPRContextEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = TFDPRQuestionEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRReader.from_pretrained(_a ) self.assertIsNotNone(_a ) @require_tf class __a (unittest.TestCase): '''simple docstring''' @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFDPRQuestionEncoder.from_pretrained("""facebook/dpr-question_encoder-single-nq-base""" ) SCREAMING_SNAKE_CASE__ : List[Any] = tf.constant( [[101, 7_592, 1_010, 2_003, 2_026, 3_899, 10_140, 1_029, 102]] ) # [CLS] hello, is my dog cute? [SEP] SCREAMING_SNAKE_CASE__ : Tuple = model(_a )[0] # embedding shape = (1, 768) # compare the actual values for a slice. SCREAMING_SNAKE_CASE__ : Any = tf.constant( [ [ 0.03_236_253, 0.12_753_335, 0.16_818_509, 0.00_279_786, 0.3_896_933, 0.24_264_945, 0.2_178_971, -0.02_335_227, -0.08_481_959, -0.14_324_117, ] ] ) self.assertTrue(numpy.allclose(output[:, :10].numpy() , expected_slice.numpy() , atol=1E-4 ) )
680
1
"""simple docstring""" import gc import threading import time import psutil import torch class __a : '''simple docstring''' def __init__( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = psutil.Process() SCREAMING_SNAKE_CASE__ : Optional[int] = False def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = -1 while True: SCREAMING_SNAKE_CASE__ : Any = max(self.process.memory_info().rss , self.cpu_memory_peak ) # can't sleep or will not catch the peak right (this comment is here on purpose) if not self.peak_monitoring: break def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = True SCREAMING_SNAKE_CASE__ : Dict = threading.Thread(target=self.peak_monitor ) SCREAMING_SNAKE_CASE__ : Tuple = True self.thread.start() def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = False self.thread.join() return self.cpu_memory_peak a :str = PeakCPUMemory() def _lowercase ( ) -> Union[str, Any]: # Time SCREAMING_SNAKE_CASE__ : Dict = {"""time""": time.time()} gc.collect() torch.cuda.empty_cache() # CPU mem SCREAMING_SNAKE_CASE__ : Union[str, Any] = psutil.Process().memory_info().rss cpu_peak_tracker.start() # GPU mem for i in range(torch.cuda.device_count() ): SCREAMING_SNAKE_CASE__ : Dict = torch.cuda.memory_allocated(__lowerCAmelCase ) torch.cuda.reset_peak_memory_stats() return measures def _lowercase ( __lowerCAmelCase ) -> int: # Time SCREAMING_SNAKE_CASE__ : str = {"""time""": time.time() - start_measures["""time"""]} gc.collect() torch.cuda.empty_cache() # CPU mem SCREAMING_SNAKE_CASE__ : List[Any] = (psutil.Process().memory_info().rss - start_measures["""cpu"""]) / 2**20 SCREAMING_SNAKE_CASE__ : Dict = (cpu_peak_tracker.stop() - start_measures["""cpu"""]) / 2**20 # GPU mem for i in range(torch.cuda.device_count() ): SCREAMING_SNAKE_CASE__ : int = (torch.cuda.memory_allocated(__lowerCAmelCase ) - start_measures[str(__lowerCAmelCase )]) / 2**20 SCREAMING_SNAKE_CASE__ : Optional[Any] = (torch.cuda.max_memory_allocated(__lowerCAmelCase ) - start_measures[str(__lowerCAmelCase )]) / 2**20 return measures def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Tuple: print(F'''{description}:''' ) print(F'''- Time: {measures['time']:.2f}s''' ) for i in range(torch.cuda.device_count() ): print(F'''- GPU {i} allocated: {measures[str(__lowerCAmelCase )]:.2f}MiB''' ) SCREAMING_SNAKE_CASE__ : int = measures[F'''{i}-peak'''] print(F'''- GPU {i} peak: {peak:.2f}MiB''' ) print(F'''- CPU RAM allocated: {measures['cpu']:.2f}MiB''' ) print(F'''- CPU RAM peak: {measures['cpu-peak']:.2f}MiB''' )
680
"""simple docstring""" # DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion # and https://github.com/hojonathanho/diffusion import math from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.schedulers.scheduling_utils import SchedulerMixin from diffusers.utils import BaseOutput, deprecate @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :torch.FloatTensor _SCREAMING_SNAKE_CASE :Optional[torch.FloatTensor] = None def _lowercase ( __lowerCAmelCase , __lowerCAmelCase=0.999 , __lowerCAmelCase="cosine" , ) -> Union[str, Any]: if alpha_transform_type == "cosine": def alpha_bar_fn(__lowerCAmelCase ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(__lowerCAmelCase ): return math.exp(t * -12.0 ) else: raise ValueError(F'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) SCREAMING_SNAKE_CASE__ : List[Any] = [] for i in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = i / num_diffusion_timesteps SCREAMING_SNAKE_CASE__ : int = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(__lowerCAmelCase ) / alpha_bar_fn(__lowerCAmelCase ) , __lowerCAmelCase ) ) return torch.tensor(__lowerCAmelCase , dtype=torch.floataa ) class __a (UpperCamelCase_ , UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = 1 @register_to_config def __init__( self , _a = 1_000 , _a = 0.0_001 , _a = 0.02 , _a = "linear" , _a = None , _a = True , _a = True , _a = 0 , _a = "epsilon" , _a = 1.0 , **_a , ) -> Dict: """simple docstring""" if kwargs.get("""set_alpha_to_one""" , _a ) is not None: SCREAMING_SNAKE_CASE__ : Tuple = ( """The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead.""" ) deprecate("""set_alpha_to_one""" , """1.0.0""" , _a , standard_warn=_a ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs["""set_alpha_to_one"""] if trained_betas is not None: SCREAMING_SNAKE_CASE__ : Dict = torch.tensor(_a , dtype=torch.floataa ) elif beta_schedule == "linear": SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.linspace(_a , _a , _a , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. SCREAMING_SNAKE_CASE__ : Optional[int] = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , _a , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule SCREAMING_SNAKE_CASE__ : Tuple = betas_for_alpha_bar(_a ) else: raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = 1.0 - self.betas SCREAMING_SNAKE_CASE__ : List[Any] = torch.cumprod(self.alphas , dim=0 ) # At every step in inverted ddim, we are looking into the next alphas_cumprod # For the final step, there is no next alphas_cumprod, and the index is out of bounds # `set_alpha_to_zero` decides whether we set this parameter simply to zero # in this case, self.step() just output the predicted noise # or whether we use the final alpha of the "non-previous" one. SCREAMING_SNAKE_CASE__ : Any = torch.tensor(0.0 ) if set_alpha_to_zero else self.alphas_cumprod[-1] # standard deviation of the initial noise distribution SCREAMING_SNAKE_CASE__ : Tuple = 1.0 # setable values SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : List[str] = torch.from_numpy(np.arange(0 , _a ).copy().astype(np.intaa ) ) def _a ( self , _a , _a = None ) -> torch.FloatTensor: """simple docstring""" return sample def _a ( self , _a , _a = None ) -> Optional[int]: """simple docstring""" if num_inference_steps > self.config.num_train_timesteps: raise ValueError( f'''`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:''' f''' {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle''' f''' maximal {self.config.num_train_timesteps} timesteps.''' ) SCREAMING_SNAKE_CASE__ : List[str] = num_inference_steps SCREAMING_SNAKE_CASE__ : Optional[Any] = self.config.num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 SCREAMING_SNAKE_CASE__ : str = (np.arange(0 , _a ) * step_ratio).round().copy().astype(np.intaa ) SCREAMING_SNAKE_CASE__ : Tuple = torch.from_numpy(_a ).to(_a ) self.timesteps += self.config.steps_offset def _a ( self , _a , _a , _a , _a = 0.0 , _a = False , _a = None , _a = True , ) -> Union[DDIMSchedulerOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = timestep + self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas # change original implementation to exactly match noise levels for analogous forward process SCREAMING_SNAKE_CASE__ : Optional[int] = self.alphas_cumprod[timestep] SCREAMING_SNAKE_CASE__ : Optional[int] = ( self.alphas_cumprod[prev_timestep] if prev_timestep < self.config.num_train_timesteps else self.final_alpha_cumprod ) SCREAMING_SNAKE_CASE__ : Any = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf if self.config.prediction_type == "epsilon": SCREAMING_SNAKE_CASE__ : int = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 SCREAMING_SNAKE_CASE__ : List[Any] = model_output elif self.config.prediction_type == "sample": SCREAMING_SNAKE_CASE__ : Dict = model_output SCREAMING_SNAKE_CASE__ : int = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 elif self.config.prediction_type == "v_prediction": SCREAMING_SNAKE_CASE__ : Dict = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output SCREAMING_SNAKE_CASE__ : str = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or''' """ `v_prediction`""" ) # 4. Clip or threshold "predicted x_0" if self.config.clip_sample: SCREAMING_SNAKE_CASE__ : Tuple = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : Any = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : Dict = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if not return_dict: return (prev_sample, pred_original_sample) return DDIMSchedulerOutput(prev_sample=_a , pred_original_sample=_a ) def __len__( self ) -> Dict: """simple docstring""" return self.config.num_train_timesteps
680
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a :List[Any] = {"configuration_yolos": ["YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP", "YolosConfig", "YolosOnnxConfig"]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :int = ["YolosFeatureExtractor"] a :Dict = ["YolosImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Optional[Any] = [ "YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST", "YolosForObjectDetection", "YolosModel", "YolosPreTrainedModel", ] if TYPE_CHECKING: from .configuration_yolos import YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP, YolosConfig, YolosOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_yolos import YolosFeatureExtractor from .image_processing_yolos import YolosImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_yolos import ( YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST, YolosForObjectDetection, YolosModel, YolosPreTrainedModel, ) else: import sys a :List[str] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) a :Union[str, Any] = { "configuration_speecht5": [ "SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP", "SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP", "SpeechT5Config", "SpeechT5HifiGanConfig", ], "feature_extraction_speecht5": ["SpeechT5FeatureExtractor"], "processing_speecht5": ["SpeechT5Processor"], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = ["SpeechT5Tokenizer"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST", "SpeechT5ForSpeechToText", "SpeechT5ForSpeechToSpeech", "SpeechT5ForTextToSpeech", "SpeechT5Model", "SpeechT5PreTrainedModel", "SpeechT5HifiGan", ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys a :Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
1
"""simple docstring""" import numpy as np import qiskit def _lowercase ( __lowerCAmelCase = 8 , __lowerCAmelCase = None ) -> str: SCREAMING_SNAKE_CASE__ : List[Any] = np.random.default_rng(seed=__lowerCAmelCase ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. SCREAMING_SNAKE_CASE__ : List[str] = 6 * key_len # Measurement basis for Alice's qubits. SCREAMING_SNAKE_CASE__ : List[Any] = rng.integers(2 , size=__lowerCAmelCase ) # The set of states Alice will prepare. SCREAMING_SNAKE_CASE__ : Optional[Any] = rng.integers(2 , size=__lowerCAmelCase ) # Measurement basis for Bob's qubits. SCREAMING_SNAKE_CASE__ : str = rng.integers(2 , size=__lowerCAmelCase ) # Quantum Circuit to simulate BB84 SCREAMING_SNAKE_CASE__ : Union[str, Any] = qiskit.QuantumCircuit(__lowerCAmelCase , name="""BB84""" ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(__lowerCAmelCase ): if alice_state[index] == 1: bbaa_circ.x(__lowerCAmelCase ) if alice_basis[index] == 1: bbaa_circ.h(__lowerCAmelCase ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(__lowerCAmelCase ): if bob_basis[index] == 1: bbaa_circ.h(__lowerCAmelCase ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. SCREAMING_SNAKE_CASE__ : str = qiskit.Aer.get_backend("""aer_simulator""" ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. SCREAMING_SNAKE_CASE__ : Optional[int] = qiskit.execute(__lowerCAmelCase , __lowerCAmelCase , shots=1 , seed_simulator=__lowerCAmelCase ) # Returns the result of measurement. SCREAMING_SNAKE_CASE__ : int = job.result().get_counts(__lowerCAmelCase ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. SCREAMING_SNAKE_CASE__ : Optional[Any] = """""".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. SCREAMING_SNAKE_CASE__ : Optional[int] = gen_key[:key_len] if len(__lowerCAmelCase ) >= key_len else gen_key.ljust(__lowerCAmelCase , """0""" ) return key if __name__ == "__main__": print(f'The generated key is : {bbaa(8, seed=0)}') from doctest import testmod testmod()
680
"""simple docstring""" import math import os import sys def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Union[str, Any] = """""" try: with open(__lowerCAmelCase , """rb""" ) as binary_file: SCREAMING_SNAKE_CASE__ : Optional[int] = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Dict = F'''{dat:08b}''' result += curr_byte return result except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> None: lexicon.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = last_match_id if math.loga(__lowerCAmelCase ).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE__ : Dict = """0""" + lexicon[curr_key] SCREAMING_SNAKE_CASE__ : str = bin(__lowerCAmelCase )[2:] def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Dict = {"""0""": """0""", """1""": """1"""} SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = """""", """""" SCREAMING_SNAKE_CASE__ : Any = len(__lowerCAmelCase ) for i in range(len(__lowerCAmelCase ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon[curr_string] result += last_match_id add_key_to_lexicon(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) index += 1 SCREAMING_SNAKE_CASE__ : List[str] = """""" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE__ : List[Any] = lexicon[curr_string] result += last_match_id return result def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Any = os.path.getsize(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = bin(__lowerCAmelCase )[2:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = len(__lowerCAmelCase ) return "0" * (length_length - 1) + file_length_binary + compressed def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Optional[int] = 8 try: with open(__lowerCAmelCase , """wb""" ) as opened_file: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ to_write[i : i + byte_length] for i in range(0 , len(__lowerCAmelCase ) , __lowerCAmelCase ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("""10000000""" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(__lowerCAmelCase , 2 ).to_bytes(1 , byteorder="""big""" ) ) except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Dict = read_file_binary(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = compress_data(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = add_file_length(__lowerCAmelCase , __lowerCAmelCase ) write_file_binary(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
680
1
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> int: assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and number_of_steps > 0 ), F'''number_of_steps needs to be positive integer, your input {number_of_steps}''' if number_of_steps == 1: return 1 SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = 1, 1 for _ in range(number_of_steps - 1 ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = current + previous, current return current if __name__ == "__main__": import doctest doctest.testmod()
680
"""simple docstring""" import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Tuple = SamImageProcessor() SCREAMING_SNAKE_CASE__ : List[str] = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> Union[str, Any]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> Tuple: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Tuple = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Dict = processor(images=_a , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_torch def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [torch.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : str = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : List[Any] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : Any = processor.post_process_masks(_a , _a , _a ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Dict = processor.post_process_masks( _a , torch.tensor(_a ) , torch.tensor(_a ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np SCREAMING_SNAKE_CASE__ : Dict = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks(_a , np.array(_a ) , np.array(_a ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Dict = [[1, 0], [0, 1]] with self.assertRaises(_a ): SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks(_a , np.array(_a ) , np.array(_a ) ) @require_vision @require_tf class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Optional[int] = SamImageProcessor() SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> List[str]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> int: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Any = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : int = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Tuple = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Any = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Any = processor(images=_a , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_tf def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Union[str, Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [tf.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Optional[int] = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks(_a , _a , _a , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks( _a , tf.convert_to_tensor(_a ) , tf.convert_to_tensor(_a ) , return_tensors="""tf""" , ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np SCREAMING_SNAKE_CASE__ : Optional[int] = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks( _a , np.array(_a ) , np.array(_a ) , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Any = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): SCREAMING_SNAKE_CASE__ : str = processor.post_process_masks( _a , np.array(_a ) , np.array(_a ) , return_tensors="""tf""" ) @require_vision @require_torchvision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Dict = SamImageProcessor() SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> Any: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> Union[str, Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : int = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : List[Any] = [tf.convert_to_tensor(_a )] SCREAMING_SNAKE_CASE__ : Dict = [torch.tensor(_a )] SCREAMING_SNAKE_CASE__ : Optional[int] = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : List[str] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : List[Any] = processor.post_process_masks( _a , _a , _a , return_tensors="""tf""" ) SCREAMING_SNAKE_CASE__ : List[str] = processor.post_process_masks( _a , _a , _a , return_tensors="""pt""" ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : str = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : int = image_processor(_a , return_tensors="""pt""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : Any = processor(images=_a , return_tensors="""pt""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor(_a , return_tensors="""tf""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : str = processor(images=_a , return_tensors="""tf""" )["""pixel_values"""].numpy() self.assertTrue(np.allclose(_a , _a ) ) self.assertTrue(np.allclose(_a , _a ) ) self.assertTrue(np.allclose(_a , _a ) )
680
1
"""simple docstring""" from collections import deque from math import floor from random import random from time import time class __a : '''simple docstring''' def __init__( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = {} def _a ( self , _a , _a , _a=1 ) -> Optional[Any]: """simple docstring""" if self.graph.get(_a ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: SCREAMING_SNAKE_CASE__ : List[Any] = [[w, v]] if not self.graph.get(_a ): SCREAMING_SNAKE_CASE__ : Optional[int] = [] def _a ( self ) -> List[Any]: """simple docstring""" return list(self.graph ) def _a ( self , _a , _a ) -> Dict: """simple docstring""" if self.graph.get(_a ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(_a ) def _a ( self , _a=-2 , _a=-1 ) -> Dict: """simple docstring""" if s == d: return [] SCREAMING_SNAKE_CASE__ : Dict = [] SCREAMING_SNAKE_CASE__ : Dict = [] if s == -2: SCREAMING_SNAKE_CASE__ : List[Any] = list(self.graph )[0] stack.append(_a ) visited.append(_a ) SCREAMING_SNAKE_CASE__ : Dict = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE__ : List[str] = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(_a ) return visited else: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE__ : List[str] = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(_a ) != 0: SCREAMING_SNAKE_CASE__ : Optional[int] = stack[len(_a ) - 1] else: SCREAMING_SNAKE_CASE__ : Dict = ss # check if se have reached the starting point if len(_a ) == 0: return visited def _a ( self , _a=-1 ) -> Optional[Any]: """simple docstring""" if c == -1: SCREAMING_SNAKE_CASE__ : Optional[int] = floor(random() * 10_000 ) + 10 for i in range(_a ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): SCREAMING_SNAKE_CASE__ : Dict = floor(random() * c ) + 1 if n != i: self.add_pair(_a , _a , 1 ) def _a ( self , _a=-2 ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = deque() SCREAMING_SNAKE_CASE__ : Optional[Any] = [] if s == -2: SCREAMING_SNAKE_CASE__ : Any = list(self.graph )[0] d.append(_a ) visited.append(_a ) while d: SCREAMING_SNAKE_CASE__ : Tuple = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def _a ( self , _a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = 0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def _a ( self , _a ) -> Tuple: """simple docstring""" return len(self.graph[u] ) def _a ( self , _a=-2 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] if s == -2: SCREAMING_SNAKE_CASE__ : Optional[Any] = list(self.graph )[0] stack.append(_a ) visited.append(_a ) SCREAMING_SNAKE_CASE__ : str = s SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE__ : str = s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(_a ) != 0: SCREAMING_SNAKE_CASE__ : Tuple = stack[len(_a ) - 1] else: SCREAMING_SNAKE_CASE__ : List[str] = ss # check if se have reached the starting point if len(_a ) == 0: return sorted_nodes def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Optional[Any] = list(self.graph )[0] stack.append(_a ) visited.append(_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = -2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] SCREAMING_SNAKE_CASE__ : List[Any] = s SCREAMING_SNAKE_CASE__ : Optional[Any] = False SCREAMING_SNAKE_CASE__ : Tuple = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE__ : List[Any] = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): SCREAMING_SNAKE_CASE__ : str = len(_a ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = node[1] break # check if all the children are visited if s == ss: stack.pop() SCREAMING_SNAKE_CASE__ : Optional[Any] = True if len(_a ) != 0: SCREAMING_SNAKE_CASE__ : Optional[int] = stack[len(_a ) - 1] else: SCREAMING_SNAKE_CASE__ : int = False indirect_parents.append(_a ) SCREAMING_SNAKE_CASE__ : str = s SCREAMING_SNAKE_CASE__ : Optional[Any] = ss # check if se have reached the starting point if len(_a ) == 0: return list(_a ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Optional[Any] = [] SCREAMING_SNAKE_CASE__ : Optional[Any] = list(self.graph )[0] stack.append(_a ) visited.append(_a ) SCREAMING_SNAKE_CASE__ : Any = -2 SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Optional[Any] = s SCREAMING_SNAKE_CASE__ : Optional[int] = False SCREAMING_SNAKE_CASE__ : str = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE__ : Any = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): SCREAMING_SNAKE_CASE__ : int = len(_a ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE__ : Tuple = node[1] break # check if all the children are visited if s == ss: stack.pop() SCREAMING_SNAKE_CASE__ : int = True if len(_a ) != 0: SCREAMING_SNAKE_CASE__ : List[str] = stack[len(_a ) - 1] else: SCREAMING_SNAKE_CASE__ : str = False indirect_parents.append(_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = s SCREAMING_SNAKE_CASE__ : List[str] = ss # check if se have reached the starting point if len(_a ) == 0: return False def _a ( self , _a=-2 , _a=-1 ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = time() self.dfs(_a , _a ) SCREAMING_SNAKE_CASE__ : List[str] = time() return end - begin def _a ( self , _a=-2 ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = time() self.bfs(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = time() return end - begin class __a : '''simple docstring''' def __init__( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = {} def _a ( self , _a , _a , _a=1 ) -> List[str]: """simple docstring""" if self.graph.get(_a ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist SCREAMING_SNAKE_CASE__ : str = [[w, v]] # add the other way if self.graph.get(_a ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist SCREAMING_SNAKE_CASE__ : str = [[w, u]] def _a ( self , _a , _a ) -> Optional[int]: """simple docstring""" if self.graph.get(_a ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(_a ) # the other way round if self.graph.get(_a ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(_a ) def _a ( self , _a=-2 , _a=-1 ) -> Dict: """simple docstring""" if s == d: return [] SCREAMING_SNAKE_CASE__ : Optional[Any] = [] SCREAMING_SNAKE_CASE__ : Any = [] if s == -2: SCREAMING_SNAKE_CASE__ : Any = list(self.graph )[0] stack.append(_a ) visited.append(_a ) SCREAMING_SNAKE_CASE__ : List[str] = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE__ : List[str] = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(_a ) return visited else: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE__ : Tuple = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(_a ) != 0: SCREAMING_SNAKE_CASE__ : Optional[Any] = stack[len(_a ) - 1] else: SCREAMING_SNAKE_CASE__ : List[Any] = ss # check if se have reached the starting point if len(_a ) == 0: return visited def _a ( self , _a=-1 ) -> Any: """simple docstring""" if c == -1: SCREAMING_SNAKE_CASE__ : List[str] = floor(random() * 10_000 ) + 10 for i in range(_a ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): SCREAMING_SNAKE_CASE__ : Dict = floor(random() * c ) + 1 if n != i: self.add_pair(_a , _a , 1 ) def _a ( self , _a=-2 ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = deque() SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] if s == -2: SCREAMING_SNAKE_CASE__ : Optional[Any] = list(self.graph )[0] d.append(_a ) visited.append(_a ) while d: SCREAMING_SNAKE_CASE__ : Dict = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def _a ( self , _a ) -> Union[str, Any]: """simple docstring""" return len(self.graph[u] ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : List[str] = list(self.graph )[0] stack.append(_a ) visited.append(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = -2 SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = s SCREAMING_SNAKE_CASE__ : Optional[int] = False SCREAMING_SNAKE_CASE__ : Optional[int] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE__ : str = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): SCREAMING_SNAKE_CASE__ : Optional[int] = len(_a ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = node[1] break # check if all the children are visited if s == ss: stack.pop() SCREAMING_SNAKE_CASE__ : Any = True if len(_a ) != 0: SCREAMING_SNAKE_CASE__ : Dict = stack[len(_a ) - 1] else: SCREAMING_SNAKE_CASE__ : Tuple = False indirect_parents.append(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = s SCREAMING_SNAKE_CASE__ : str = ss # check if se have reached the starting point if len(_a ) == 0: return list(_a ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Optional[Any] = [] SCREAMING_SNAKE_CASE__ : Optional[Any] = list(self.graph )[0] stack.append(_a ) visited.append(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = -2 SCREAMING_SNAKE_CASE__ : List[str] = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = s SCREAMING_SNAKE_CASE__ : List[Any] = False SCREAMING_SNAKE_CASE__ : str = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE__ : str = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = len(_a ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = node[1] break # check if all the children are visited if s == ss: stack.pop() SCREAMING_SNAKE_CASE__ : int = True if len(_a ) != 0: SCREAMING_SNAKE_CASE__ : Union[str, Any] = stack[len(_a ) - 1] else: SCREAMING_SNAKE_CASE__ : List[Any] = False indirect_parents.append(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = s SCREAMING_SNAKE_CASE__ : Optional[int] = ss # check if se have reached the starting point if len(_a ) == 0: return False def _a ( self ) -> List[Any]: """simple docstring""" return list(self.graph ) def _a ( self , _a=-2 , _a=-1 ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = time() self.dfs(_a , _a ) SCREAMING_SNAKE_CASE__ : Dict = time() return end - begin def _a ( self , _a=-2 ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = time() self.bfs(_a ) SCREAMING_SNAKE_CASE__ : Any = time() return end - begin
680
"""simple docstring""" import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __a (UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = LayoutLMTokenizer _SCREAMING_SNAKE_CASE :Optional[int] = LayoutLMTokenizerFast _SCREAMING_SNAKE_CASE :str = True _SCREAMING_SNAKE_CASE :Optional[int] = True def _a ( self ) -> Tuple: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : List[str] = [ """[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] SCREAMING_SNAKE_CASE__ : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def _a ( self , **_a ) -> Optional[int]: """simple docstring""" return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **_a ) def _a ( self , _a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = """UNwant\u00E9d,running""" SCREAMING_SNAKE_CASE__ : Optional[Any] = """unwanted, running""" return input_text, output_text def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(_a , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_a ) , [7, 4, 5, 10, 8, 9] ) def _a ( self ) -> Optional[int]: """simple docstring""" pass
680
1
"""simple docstring""" def _lowercase ( ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : List[str] = 0 for i in range(1 , 1001 ): total += i**i return str(__lowerCAmelCase )[-10:] if __name__ == "__main__": print(solution())
680
"""simple docstring""" import argparse import os import evaluate import torch from datasets import load_dataset 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 # and perform gradient accumulation # # 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 run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a :str = 16 a :Union[str, Any] = 32 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase = 16 ) -> Tuple: SCREAMING_SNAKE_CASE__ : int = AutoTokenizer.from_pretrained("""bert-base-cased""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__lowerCAmelCase ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__lowerCAmelCase , max_length=__lowerCAmelCase ) 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(): SCREAMING_SNAKE_CASE__ : List[str] = datasets.map( __lowerCAmelCase , batched=__lowerCAmelCase , 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 SCREAMING_SNAKE_CASE__ : Any = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__lowerCAmelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE__ : int = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE__ : str = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE__ : Dict = 8 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = None return tokenizer.pad( __lowerCAmelCase , padding="""longest""" , max_length=__lowerCAmelCase , pad_to_multiple_of=__lowerCAmelCase , return_tensors="""pt""" , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE__ : int = DataLoader( tokenized_datasets["""train"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = DataLoader( tokenized_datasets["""validation"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": from accelerate.test_utils.training import mocked_dataloaders a :Dict = mocked_dataloaders # noqa: F811 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , __lowerCAmelCase ) == "1": SCREAMING_SNAKE_CASE__ : Optional[int] = 2 # New Code # SCREAMING_SNAKE_CASE__ : Optional[int] = int(args.gradient_accumulation_steps ) # Initialize accelerator SCREAMING_SNAKE_CASE__ : Optional[Any] = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=__lowerCAmelCase ) if accelerator.distributed_type == DistributedType.TPU and gradient_accumulation_steps > 1: raise NotImplementedError( """Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE__ : Any = config["""lr"""] SCREAMING_SNAKE_CASE__ : str = int(config["""num_epochs"""] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = int(config["""seed"""] ) SCREAMING_SNAKE_CASE__ : List[str] = int(config["""batch_size"""] ) SCREAMING_SNAKE_CASE__ : Any = evaluate.load("""glue""" , """mrpc""" ) set_seed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = get_dataloaders(__lowerCAmelCase , __lowerCAmelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE__ : int = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=__lowerCAmelCase ) # 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). SCREAMING_SNAKE_CASE__ : int = model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE__ : Union[str, Any] = AdamW(params=model.parameters() , lr=__lowerCAmelCase ) # Instantiate scheduler SCREAMING_SNAKE_CASE__ : Any = get_linear_schedule_with_warmup( optimizer=__lowerCAmelCase , num_warmup_steps=100 , num_training_steps=(len(__lowerCAmelCase ) * num_epochs) , ) # 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. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = accelerator.prepare( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Now we train the model for epoch in range(__lowerCAmelCase ): model.train() for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = output.loss accelerator.backward(__lowerCAmelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=__lowerCAmelCase , references=__lowerCAmelCase , ) SCREAMING_SNAKE_CASE__ : List[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , __lowerCAmelCase ) def _lowercase ( ) -> Any: SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=__lowerCAmelCase , default=__lowerCAmelCase , 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.""" , ) # New Code # parser.add_argument( """--gradient_accumulation_steps""" , type=__lowerCAmelCase , default=1 , help="""The number of minibatches to be ran before gradients are accumulated.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : int = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": main()
680
1
"""simple docstring""" import os from math import logaa def _lowercase ( __lowerCAmelCase = "base_exp.txt" ) -> int: SCREAMING_SNAKE_CASE__ : float = 0 SCREAMING_SNAKE_CASE__ : Tuple = 0 for i, line in enumerate(open(os.path.join(os.path.dirname(__lowerCAmelCase ) , __lowerCAmelCase ) ) ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = list(map(__lowerCAmelCase , line.split(""",""" ) ) ) if x * logaa(__lowerCAmelCase ) > largest: SCREAMING_SNAKE_CASE__ : Tuple = x * logaa(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = i + 1 return result if __name__ == "__main__": print(solution())
680
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available a :str = { "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST", "ErnieForCausalLM", "ErnieForMaskedLM", "ErnieForMultipleChoice", "ErnieForNextSentencePrediction", "ErnieForPreTraining", "ErnieForQuestionAnswering", "ErnieForSequenceClassification", "ErnieForTokenClassification", "ErnieModel", "ErniePreTrainedModel", ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys a :Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
1
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig a :List[Any] = logging.get_logger(__name__) a :Union[str, Any] = { "Intel/dpt-large": "https://huggingface.co/Intel/dpt-large/resolve/main/config.json", # See all DPT models at https://huggingface.co/models?filter=dpt } class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = """dpt""" def __init__( self , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.0 , _a=0.0 , _a=0.02 , _a=1E-1_2 , _a=384 , _a=16 , _a=3 , _a=False , _a=True , _a=[2, 5, 8, 11] , _a="project" , _a=[4, 2, 1, 0.5] , _a=[96, 192, 384, 768] , _a=256 , _a=-1 , _a=False , _a=True , _a=0.4 , _a=255 , _a=0.1 , _a=[1, 1_024, 24, 24] , _a=[0, 1] , _a=None , **_a , ) -> int: """simple docstring""" super().__init__(**_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_size SCREAMING_SNAKE_CASE__ : int = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info("""Initializing the config with a `BiT` backbone.""" ) SCREAMING_SNAKE_CASE__ : Any = { """global_padding""": """same""", """layer_type""": """bottleneck""", """depths""": [3, 4, 9], """out_features""": ["""stage1""", """stage2""", """stage3"""], """embedding_dynamic_padding""": True, } SCREAMING_SNAKE_CASE__ : List[str] = BitConfig(**_a ) elif isinstance(_a , _a ): logger.info("""Initializing the config with a `BiT` backbone.""" ) SCREAMING_SNAKE_CASE__ : List[Any] = BitConfig(**_a ) elif isinstance(_a , _a ): SCREAMING_SNAKE_CASE__ : Optional[Any] = backbone_config else: raise ValueError( f'''backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}.''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = backbone_featmap_shape SCREAMING_SNAKE_CASE__ : List[Any] = neck_ignore_stages if readout_type != "project": raise ValueError("""Readout type must be 'project' when using `DPT-hybrid` mode.""" ) else: SCREAMING_SNAKE_CASE__ : List[Any] = None SCREAMING_SNAKE_CASE__ : List[Any] = None SCREAMING_SNAKE_CASE__ : int = [] SCREAMING_SNAKE_CASE__ : Optional[int] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : List[str] = intermediate_size SCREAMING_SNAKE_CASE__ : List[str] = hidden_act SCREAMING_SNAKE_CASE__ : int = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Tuple = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Tuple = initializer_range SCREAMING_SNAKE_CASE__ : str = layer_norm_eps SCREAMING_SNAKE_CASE__ : Tuple = image_size SCREAMING_SNAKE_CASE__ : List[str] = patch_size SCREAMING_SNAKE_CASE__ : int = num_channels SCREAMING_SNAKE_CASE__ : Dict = qkv_bias SCREAMING_SNAKE_CASE__ : Optional[Any] = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError("""Readout_type must be one of ['ignore', 'add', 'project']""" ) SCREAMING_SNAKE_CASE__ : List[Any] = readout_type SCREAMING_SNAKE_CASE__ : Tuple = reassemble_factors SCREAMING_SNAKE_CASE__ : Any = neck_hidden_sizes SCREAMING_SNAKE_CASE__ : Any = fusion_hidden_size SCREAMING_SNAKE_CASE__ : Tuple = head_in_index SCREAMING_SNAKE_CASE__ : Dict = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) SCREAMING_SNAKE_CASE__ : Dict = use_auxiliary_head SCREAMING_SNAKE_CASE__ : Any = auxiliary_loss_weight SCREAMING_SNAKE_CASE__ : Optional[int] = semantic_loss_ignore_index SCREAMING_SNAKE_CASE__ : Any = semantic_classifier_dropout def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: SCREAMING_SNAKE_CASE__ : Any = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE__ : Tuple = self.__class__.model_type return output
680
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> int: assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and number_of_steps > 0 ), F'''number_of_steps needs to be positive integer, your input {number_of_steps}''' if number_of_steps == 1: return 1 SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = 1, 1 for _ in range(number_of_steps - 1 ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = current + previous, current return current if __name__ == "__main__": import doctest doctest.testmod()
680
1
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> str: return " ".join( """""".join(word[::-1] ) if len(__lowerCAmelCase ) > 4 else word for word in sentence.split() ) if __name__ == "__main__": import doctest doctest.testmod() print(reverse_long_words("Hey wollef sroirraw"))
680
"""simple docstring""" from math import factorial def _lowercase ( __lowerCAmelCase = 100 ) -> int: return sum(int(__lowerCAmelCase ) for x in str(factorial(__lowerCAmelCase ) ) ) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
680
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __a (UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :str = StableDiffusionInpaintPipeline _SCREAMING_SNAKE_CASE :Any = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS _SCREAMING_SNAKE_CASE :Dict = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS _SCREAMING_SNAKE_CASE :Optional[int] = frozenset( []) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _SCREAMING_SNAKE_CASE :Dict = frozenset([]) def _a ( self ) -> Dict: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , 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 , ) SCREAMING_SNAKE_CASE__ : List[str] = PNDMScheduler(skip_prk_steps=_a ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = 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 ) SCREAMING_SNAKE_CASE__ : int = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) SCREAMING_SNAKE_CASE__ : int = CLIPTextModel(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) SCREAMING_SNAKE_CASE__ : int = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def _a ( self , _a , _a=0 ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = floats_tensor((1, 3, 32, 32) , rng=random.Random(_a ) ).to(_a ) SCREAMING_SNAKE_CASE__ : Tuple = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : Any = Image.fromarray(np.uinta(_a ) ).convert("""RGB""" ).resize((64, 64) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(_a ).startswith("""mps""" ): SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(_a ) else: SCREAMING_SNAKE_CASE__ : str = torch.Generator(device=_a ).manual_seed(_a ) SCREAMING_SNAKE_CASE__ : Tuple = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInpaintPipeline(**_a ) SCREAMING_SNAKE_CASE__ : Any = sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : int = self.get_dummy_inputs(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe(**_a ).images SCREAMING_SNAKE_CASE__ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : str = np.array([0.4_727, 0.5_735, 0.3_941, 0.5_446, 0.5_926, 0.4_394, 0.5_062, 0.4_654, 0.4_476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _a ( self ) -> Optional[int]: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : Any = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : Any = StableDiffusionInpaintPipeline.from_pretrained(_a , safety_checker=_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : int = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Tuple = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : int = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) SCREAMING_SNAKE_CASE__ : List[str] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInpaintPipeline.from_pretrained( _a , torch_dtype=torch.floataa , safety_checker=_a , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Any = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Tuple = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def _a ( self ) -> Tuple: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE__ : Dict = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : str = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : List[str] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : Dict = PNDMScheduler.from_pretrained(_a , subfolder="""scheduler""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = StableDiffusionInpaintPipeline.from_pretrained( _a , safety_checker=_a , scheduler=_a , torch_dtype=torch.floataa , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE__ : Union[str, Any] = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , num_inference_steps=2 , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : List[str] = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
680
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from typing import List from unittest.mock import Mock import torch from torch.utils.data import DataLoader, IterableDataset, TensorDataset from accelerate.accelerator import Accelerator from accelerate.utils.dataclasses import DistributedType class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = data def __iter__( self ) -> Tuple: """simple docstring""" for element in self.data: yield element def _lowercase ( __lowerCAmelCase=True ) -> str: SCREAMING_SNAKE_CASE__ : str = Accelerator(even_batches=__lowerCAmelCase ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = False ) -> Optional[int]: if iterable: SCREAMING_SNAKE_CASE__ : int = DummyIterableDataset(torch.as_tensor(range(__lowerCAmelCase ) ) ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = TensorDataset(torch.as_tensor(range(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : str = DataLoader(__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = accelerator.prepare(__lowerCAmelCase ) return dl def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> Tuple: SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(accelerator=__lowerCAmelCase , dataset_size=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = [len(batch[0] ) for batch in dl] if accelerator.process_index == 0: assert batch_sizes == process_0_expected_batch_sizes elif accelerator.process_index == 1: assert batch_sizes == process_1_expected_batch_sizes def _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Tuple = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1, 1] , ) # without padding, we would expect the same number of batches, but different sizes verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_accelerator(even_batches=__lowerCAmelCase ) verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , ) verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , ) def _lowercase ( ) -> str: SCREAMING_SNAKE_CASE__ : List[str] = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) SCREAMING_SNAKE_CASE__ : int = [] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Optional[Any] = ddp_model(batch[0].float() ) SCREAMING_SNAKE_CASE__ : List[Any] = output.sum() loss.backward() batch_idxs.append(__lowerCAmelCase ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: with warnings.catch_warnings(record=__lowerCAmelCase ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category , __lowerCAmelCase ) assert "only supported for multi-GPU" in str(w[-1].message ) def _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = False SCREAMING_SNAKE_CASE__ : Any = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerator.prepare(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) SCREAMING_SNAKE_CASE__ : List[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[Any] = train_dl.batch_sampler.even_batches SCREAMING_SNAKE_CASE__ : str = valid_dl.batch_sampler.even_batches assert train_dl_overridden_value == overridden_even_batches assert valid_dl_overridden_value == overridden_even_batches assert train_dl.batch_sampler.even_batches == default_even_batches assert valid_dl.batch_sampler.even_batches == default_even_batches def _lowercase ( ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[Any] = True SCREAMING_SNAKE_CASE__ : List[Any] = False SCREAMING_SNAKE_CASE__ : int = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : str = accelerator.prepare(__lowerCAmelCase ) create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings("""ignore""" ) try: with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = batch_dl.batch_sampler.even_batches except AttributeError: # ensure attribute error is not raised when processing iterable dl raise AssertionError assert batch_dl_overridden_value == overridden_even_batches assert batch_dl.batch_sampler.even_batches == default_even_batches def _lowercase ( ) -> List[str]: SCREAMING_SNAKE_CASE__ : str = create_accelerator() SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase ) create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase ) with warnings.catch_warnings(record=__lowerCAmelCase ) as w: with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): pass assert issubclass(w[-1].category , __lowerCAmelCase ) assert "only supported for map-style datasets" in str(w[-1].message ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_accelerator() accelerator.print("""Test that even_batches variable ensures uniform batches across processes""" ) test_default_ensures_even_batch_sizes() accelerator.print("""Run tests with even_batches disabled""" ) test_can_disable_even_batches() accelerator.print("""Test joining uneven inputs""" ) test_can_join_uneven_inputs() accelerator.print("""Test overriding even_batches when joining uneven inputs""" ) test_join_can_override_even_batches() accelerator.print("""Test overriding even_batches for mixed dataloader types""" ) test_join_can_override_for_mixed_type_dataloaders() accelerator.print("""Test overriding even_batches raises a warning for iterable dataloaders""" ) test_join_raises_warning_for_iterable_when_overriding_even_batches() accelerator.print("""Test join with non DDP distributed raises warning""" ) SCREAMING_SNAKE_CASE__ : Dict = accelerator.state.distributed_type SCREAMING_SNAKE_CASE__ : Optional[int] = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = original_state if __name__ == "__main__": main()
680
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) a :List[Any] = { "configuration_mobilebert": [ "MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "MobileBertConfig", "MobileBertOnnxConfig", ], "tokenization_mobilebert": ["MobileBertTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Tuple = ["MobileBertTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :List[str] = [ "MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "MobileBertForMaskedLM", "MobileBertForMultipleChoice", "MobileBertForNextSentencePrediction", "MobileBertForPreTraining", "MobileBertForQuestionAnswering", "MobileBertForSequenceClassification", "MobileBertForTokenClassification", "MobileBertLayer", "MobileBertModel", "MobileBertPreTrainedModel", "load_tf_weights_in_mobilebert", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFMobileBertForMaskedLM", "TFMobileBertForMultipleChoice", "TFMobileBertForNextSentencePrediction", "TFMobileBertForPreTraining", "TFMobileBertForQuestionAnswering", "TFMobileBertForSequenceClassification", "TFMobileBertForTokenClassification", "TFMobileBertMainLayer", "TFMobileBertModel", "TFMobileBertPreTrainedModel", ] if TYPE_CHECKING: from .configuration_mobilebert import ( MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileBertConfig, MobileBertOnnxConfig, ) from .tokenization_mobilebert import MobileBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mobilebert_fast import MobileBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilebert import ( MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, MobileBertLayer, MobileBertModel, MobileBertPreTrainedModel, load_tf_weights_in_mobilebert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilebert import ( TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileBertForMaskedLM, TFMobileBertForMultipleChoice, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertMainLayer, TFMobileBertModel, TFMobileBertPreTrainedModel, ) else: import sys a :Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
"""simple docstring""" def _lowercase ( __lowerCAmelCase = 200_0000 ) -> int: SCREAMING_SNAKE_CASE__ : int = [0 for i in range(n + 1 )] SCREAMING_SNAKE_CASE__ : str = 1 SCREAMING_SNAKE_CASE__ : str = 1 for i in range(2 , int(n**0.5 ) + 1 ): if primality_list[i] == 0: for j in range(i * i , n + 1 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 for i in range(__lowerCAmelCase ): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(f'{solution() = }')
680
1
"""simple docstring""" import json import os import shutil import tempfile import unittest from multiprocessing import get_context from pathlib import Path import datasets import numpy as np from datasets import load_dataset from parameterized import parameterized from transformers import AutoProcessor from transformers.models.wavaveca import WavaVecaCTCTokenizer, WavaVecaFeatureExtractor from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES from transformers.testing_utils import require_pyctcdecode, require_torch, require_torchaudio, slow from transformers.utils import FEATURE_EXTRACTOR_NAME, is_pyctcdecode_available, is_torch_available from ..wavaveca.test_feature_extraction_wavaveca import floats_list if is_pyctcdecode_available(): from huggingface_hub import snapshot_download from pyctcdecode import BeamSearchDecoderCTC from transformers.models.wavaveca_with_lm import WavaVecaProcessorWithLM from transformers.models.wavaveca_with_lm.processing_wavaveca_with_lm import WavaVecaDecoderWithLMOutput if is_torch_available(): from transformers import WavaVecaForCTC @require_pyctcdecode class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = """| <pad> <unk> <s> </s> a b c d e f g h i j k""".split() SCREAMING_SNAKE_CASE__ : Optional[int] = dict(zip(_a , range(len(_a ) ) ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = { """unk_token""": """<unk>""", """bos_token""": """<s>""", """eos_token""": """</s>""", } SCREAMING_SNAKE_CASE__ : Union[str, Any] = { """feature_size""": 1, """padding_value""": 0.0, """sampling_rate""": 16_000, """return_attention_mask""": False, """do_normalize""": True, } SCREAMING_SNAKE_CASE__ : Any = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.join(self.tmpdirname , _a ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(_a ) + """\n""" ) with open(self.feature_extraction_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(_a ) + """\n""" ) # load decoder from hub SCREAMING_SNAKE_CASE__ : Any = """hf-internal-testing/ngram-beam-search-decoder""" def _a ( self , **_a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.add_kwargs_tokens_map.copy() kwargs.update(_a ) return WavaVecaCTCTokenizer.from_pretrained(self.tmpdirname , **_a ) def _a ( self , **_a ) -> Optional[Any]: """simple docstring""" return WavaVecaFeatureExtractor.from_pretrained(self.tmpdirname , **_a ) def _a ( self , **_a ) -> List[str]: """simple docstring""" return BeamSearchDecoderCTC.load_from_hf_hub(self.decoder_name , **_a ) def _a ( self ) -> Dict: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Tuple = self.get_feature_extractor() SCREAMING_SNAKE_CASE__ : List[Any] = self.get_decoder() SCREAMING_SNAKE_CASE__ : List[str] = WavaVecaProcessorWithLM(tokenizer=_a , feature_extractor=_a , decoder=_a ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Optional[Any] = WavaVecaProcessorWithLM.from_pretrained(self.tmpdirname ) # tokenizer self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , _a ) # feature extractor self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , _a ) # decoder self.assertEqual(processor.decoder._alphabet.labels , decoder._alphabet.labels ) self.assertEqual( processor.decoder.model_container[decoder._model_key]._unigram_set , decoder.model_container[decoder._model_key]._unigram_set , ) self.assertIsInstance(processor.decoder , _a ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = WavaVecaProcessorWithLM( tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() , decoder=self.get_decoder() ) processor.save_pretrained(self.tmpdirname ) # make sure that error is thrown when decoder alphabet doesn't match SCREAMING_SNAKE_CASE__ : List[str] = WavaVecaProcessorWithLM.from_pretrained( self.tmpdirname , alpha=5.0 , beta=3.0 , score_boundary=-7.0 , unk_score_offset=3 ) # decoder self.assertEqual(processor.language_model.alpha , 5.0 ) self.assertEqual(processor.language_model.beta , 3.0 ) self.assertEqual(processor.language_model.score_boundary , -7.0 ) self.assertEqual(processor.language_model.unk_score_offset , 3 ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.get_tokenizer() # add token to trigger raise tokenizer.add_tokens(["""xx"""] ) with self.assertRaisesRegex(_a , """include""" ): WavaVecaProcessorWithLM( tokenizer=_a , feature_extractor=self.get_feature_extractor() , decoder=self.get_decoder() ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_feature_extractor() SCREAMING_SNAKE_CASE__ : Any = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_decoder() SCREAMING_SNAKE_CASE__ : Any = WavaVecaProcessorWithLM(tokenizer=_a , feature_extractor=_a , decoder=_a ) SCREAMING_SNAKE_CASE__ : Any = floats_list((3, 1_000) ) SCREAMING_SNAKE_CASE__ : List[str] = feature_extractor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : int = processor(_a , return_tensors="""np""" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_feature_extractor() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_decoder() SCREAMING_SNAKE_CASE__ : List[Any] = WavaVecaProcessorWithLM(tokenizer=_a , feature_extractor=_a , decoder=_a ) SCREAMING_SNAKE_CASE__ : Tuple = """This is a test string""" SCREAMING_SNAKE_CASE__ : Dict = processor(text=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer(_a ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _a ( self , _a=(2, 10, 16) , _a=77 ) -> Tuple: """simple docstring""" np.random.seed(_a ) return np.random.rand(*_a ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.get_feature_extractor() SCREAMING_SNAKE_CASE__ : Dict = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_decoder() SCREAMING_SNAKE_CASE__ : int = WavaVecaProcessorWithLM(tokenizer=_a , feature_extractor=_a , decoder=_a ) SCREAMING_SNAKE_CASE__ : str = self._get_dummy_logits(shape=(10, 16) , seed=13 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.decode(_a ) SCREAMING_SNAKE_CASE__ : int = decoder.decode_beams(_a )[0] self.assertEqual(decoded_decoder[0] , decoded_processor.text ) self.assertEqual("""</s> <s> </s>""" , decoded_processor.text ) self.assertEqual(decoded_decoder[-2] , decoded_processor.logit_score ) self.assertEqual(decoded_decoder[-1] , decoded_processor.lm_score ) @parameterized.expand([[None], ["""fork"""], ["""spawn"""]] ) def _a ( self , _a ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_feature_extractor() SCREAMING_SNAKE_CASE__ : List[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_decoder() SCREAMING_SNAKE_CASE__ : List[str] = WavaVecaProcessorWithLM(tokenizer=_a , feature_extractor=_a , decoder=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self._get_dummy_logits() # note: pool should be instantiated *after* Wav2Vec2ProcessorWithLM. # otherwise, the LM won't be available to the pool's sub-processes. # manual logic used to allow parameterized test for both pool=None and pool=Pool(...) if pool_context is None: SCREAMING_SNAKE_CASE__ : Optional[int] = processor.batch_decode(_a ) else: with get_context(_a ).Pool() as pool: SCREAMING_SNAKE_CASE__ : str = processor.batch_decode(_a , _a ) SCREAMING_SNAKE_CASE__ : Dict = list(_a ) with get_context("""fork""" ).Pool() as p: SCREAMING_SNAKE_CASE__ : int = decoder.decode_beams_batch(_a , _a ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = [], [], [] for beams in decoded_beams: texts_decoder.append(beams[0][0] ) logit_scores_decoder.append(beams[0][-2] ) lm_scores_decoder.append(beams[0][-1] ) self.assertListEqual(_a , decoded_processor.text ) self.assertListEqual(["""<s> <s> </s>""", """<s> <s> <s>"""] , decoded_processor.text ) self.assertListEqual(_a , decoded_processor.logit_score ) self.assertListEqual(_a , decoded_processor.lm_score ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.get_feature_extractor() SCREAMING_SNAKE_CASE__ : Tuple = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_decoder() SCREAMING_SNAKE_CASE__ : Tuple = WavaVecaProcessorWithLM(tokenizer=_a , feature_extractor=_a , decoder=_a ) SCREAMING_SNAKE_CASE__ : List[Any] = self._get_dummy_logits() SCREAMING_SNAKE_CASE__ : Any = 15 SCREAMING_SNAKE_CASE__ : Tuple = -20.0 SCREAMING_SNAKE_CASE__ : str = -4.0 SCREAMING_SNAKE_CASE__ : Any = processor.batch_decode( _a , beam_width=_a , beam_prune_logp=_a , token_min_logp=_a , ) SCREAMING_SNAKE_CASE__ : List[Any] = decoded_processor_out.text SCREAMING_SNAKE_CASE__ : Optional[int] = list(_a ) with get_context("""fork""" ).Pool() as pool: SCREAMING_SNAKE_CASE__ : Tuple = decoder.decode_beams_batch( _a , _a , beam_width=_a , beam_prune_logp=_a , token_min_logp=_a , ) SCREAMING_SNAKE_CASE__ : Dict = [d[0][0] for d in decoded_decoder_out] SCREAMING_SNAKE_CASE__ : Any = [d[0][2] for d in decoded_decoder_out] SCREAMING_SNAKE_CASE__ : List[Any] = [d[0][3] for d in decoded_decoder_out] self.assertListEqual(_a , _a ) self.assertListEqual(["""</s> <s> <s>""", """<s> <s> <s>"""] , _a ) self.assertTrue(np.array_equal(_a , decoded_processor_out.logit_score ) ) self.assertTrue(np.allclose([-20.054, -18.447] , _a , atol=1E-3 ) ) self.assertTrue(np.array_equal(_a , decoded_processor_out.lm_score ) ) self.assertTrue(np.allclose([-15.554, -13.9_474] , _a , atol=1E-3 ) ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_feature_extractor() SCREAMING_SNAKE_CASE__ : Tuple = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : List[str] = self.get_decoder() SCREAMING_SNAKE_CASE__ : Union[str, Any] = WavaVecaProcessorWithLM(tokenizer=_a , feature_extractor=_a , decoder=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._get_dummy_logits() SCREAMING_SNAKE_CASE__ : str = 2.0 SCREAMING_SNAKE_CASE__ : Tuple = 5.0 SCREAMING_SNAKE_CASE__ : Tuple = -20.0 SCREAMING_SNAKE_CASE__ : Tuple = True SCREAMING_SNAKE_CASE__ : Optional[int] = processor.batch_decode( _a , alpha=_a , beta=_a , unk_score_offset=_a , lm_score_boundary=_a , ) SCREAMING_SNAKE_CASE__ : List[str] = decoded_processor_out.text SCREAMING_SNAKE_CASE__ : Optional[Any] = list(_a ) decoder.reset_params( alpha=_a , beta=_a , unk_score_offset=_a , lm_score_boundary=_a , ) with get_context("""fork""" ).Pool() as pool: SCREAMING_SNAKE_CASE__ : List[str] = decoder.decode_beams_batch( _a , _a , ) SCREAMING_SNAKE_CASE__ : Dict = [d[0][0] for d in decoded_decoder_out] self.assertListEqual(_a , _a ) self.assertListEqual(["""<s> </s> <s> </s> </s>""", """</s> </s> <s> </s> </s>"""] , _a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.decoder.model_container[processor.decoder._model_key] self.assertEqual(lm_model.alpha , 2.0 ) self.assertEqual(lm_model.beta , 5.0 ) self.assertEqual(lm_model.unk_score_offset , -20.0 ) self.assertEqual(lm_model.score_boundary , _a ) def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = WavaVecaProcessorWithLM.from_pretrained("""hf-internal-testing/processor_with_lm""" ) SCREAMING_SNAKE_CASE__ : str = processor.decoder.model_container[processor.decoder._model_key] SCREAMING_SNAKE_CASE__ : Optional[int] = Path(language_model._kenlm_model.path.decode("""utf-8""" ) ).parent.parent.absolute() SCREAMING_SNAKE_CASE__ : int = os.listdir(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = ["""alphabet.json""", """language_model"""] downloaded_decoder_files.sort() expected_decoder_files.sort() # test that only decoder relevant files from # https://huggingface.co/hf-internal-testing/processor_with_lm/tree/main # are downloaded and none of the rest (e.g. README.md, ...) self.assertListEqual(_a , _a ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = snapshot_download("""hf-internal-testing/processor_with_lm""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = WavaVecaProcessorWithLM.from_pretrained(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.decoder.model_container[processor.decoder._model_key] SCREAMING_SNAKE_CASE__ : Any = Path(language_model._kenlm_model.path.decode("""utf-8""" ) ).parent.parent.absolute() SCREAMING_SNAKE_CASE__ : Any = os.listdir(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = os.listdir(_a ) local_decoder_files.sort() expected_decoder_files.sort() # test that both decoder form hub and local files in cache are the same self.assertListEqual(_a , _a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = WavaVecaProcessorWithLM.from_pretrained("""hf-internal-testing/processor_with_lm""" ) SCREAMING_SNAKE_CASE__ : int = AutoProcessor.from_pretrained("""hf-internal-testing/processor_with_lm""" ) SCREAMING_SNAKE_CASE__ : str = floats_list((3, 1_000) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = processor_wavaveca(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : str = processor_auto(_a , return_tensors="""np""" ) for key in input_wavaveca.keys(): self.assertAlmostEqual(input_wavaveca[key].sum() , input_auto[key].sum() , delta=1E-2 ) SCREAMING_SNAKE_CASE__ : str = self._get_dummy_logits() SCREAMING_SNAKE_CASE__ : Any = processor_wavaveca.batch_decode(_a ) SCREAMING_SNAKE_CASE__ : str = processor_auto.batch_decode(_a ) self.assertListEqual(decoded_wavaveca.text , decoded_auto.text ) def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.get_feature_extractor() SCREAMING_SNAKE_CASE__ : List[str] = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Tuple = self.get_decoder() SCREAMING_SNAKE_CASE__ : Any = WavaVecaProcessorWithLM(tokenizer=_a , feature_extractor=_a , decoder=_a ) self.assertListEqual( processor.model_input_names , feature_extractor.model_input_names , msg="""`processor` and `feature_extractor` model input names do not match""" , ) @staticmethod def _a ( _a , _a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = [d[key] for d in offsets] return retrieved_list def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = WavaVecaProcessorWithLM.from_pretrained("""hf-internal-testing/processor_with_lm""" ) SCREAMING_SNAKE_CASE__ : str = self._get_dummy_logits()[0] SCREAMING_SNAKE_CASE__ : Dict = processor.decode(_a , output_word_offsets=_a ) # check Wav2Vec2CTCTokenizerOutput keys for word self.assertEqual(len(outputs.keys() ) , 4 ) self.assertTrue("""text""" in outputs ) self.assertTrue("""word_offsets""" in outputs ) self.assertTrue(isinstance(_a , _a ) ) self.assertEqual(""" """.join(self.get_from_offsets(outputs["""word_offsets"""] , """word""" ) ) , outputs.text ) self.assertListEqual(self.get_from_offsets(outputs["""word_offsets"""] , """word""" ) , ["""<s>""", """<s>""", """</s>"""] ) self.assertListEqual(self.get_from_offsets(outputs["""word_offsets"""] , """start_offset""" ) , [0, 2, 4] ) self.assertListEqual(self.get_from_offsets(outputs["""word_offsets"""] , """end_offset""" ) , [1, 3, 5] ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = WavaVecaProcessorWithLM.from_pretrained("""hf-internal-testing/processor_with_lm""" ) SCREAMING_SNAKE_CASE__ : List[str] = self._get_dummy_logits() SCREAMING_SNAKE_CASE__ : List[Any] = processor.batch_decode(_a , output_word_offsets=_a ) # check Wav2Vec2CTCTokenizerOutput keys for word self.assertEqual(len(outputs.keys() ) , 4 ) self.assertTrue("""text""" in outputs ) self.assertTrue("""word_offsets""" in outputs ) self.assertTrue(isinstance(_a , _a ) ) self.assertListEqual( [""" """.join(self.get_from_offsets(_a , """word""" ) ) for o in outputs["""word_offsets"""]] , outputs.text ) self.assertListEqual(self.get_from_offsets(outputs["""word_offsets"""][0] , """word""" ) , ["""<s>""", """<s>""", """</s>"""] ) self.assertListEqual(self.get_from_offsets(outputs["""word_offsets"""][0] , """start_offset""" ) , [0, 2, 4] ) self.assertListEqual(self.get_from_offsets(outputs["""word_offsets"""][0] , """end_offset""" ) , [1, 3, 5] ) @slow @require_torch @require_torchaudio def _a ( self ) -> int: """simple docstring""" import torch SCREAMING_SNAKE_CASE__ : Dict = load_dataset("""common_voice""" , """en""" , split="""train""" , streaming=_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ds.cast_column("""audio""" , datasets.Audio(sampling_rate=16_000 ) ) SCREAMING_SNAKE_CASE__ : str = iter(_a ) SCREAMING_SNAKE_CASE__ : int = next(_a ) SCREAMING_SNAKE_CASE__ : Any = AutoProcessor.from_pretrained("""patrickvonplaten/wav2vec2-base-100h-with-lm""" ) SCREAMING_SNAKE_CASE__ : List[Any] = WavaVecaForCTC.from_pretrained("""patrickvonplaten/wav2vec2-base-100h-with-lm""" ) # compare to filename `common_voice_en_100038.mp3` of dataset viewer on https://huggingface.co/datasets/common_voice/viewer/en/train SCREAMING_SNAKE_CASE__ : int = processor(sample["""audio"""]["""array"""] , return_tensors="""pt""" ).input_values with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[int] = model(_a ).logits.cpu().numpy() SCREAMING_SNAKE_CASE__ : List[Any] = processor.decode(logits[0] , output_word_offsets=_a ) SCREAMING_SNAKE_CASE__ : str = model.config.inputs_to_logits_ratio / processor.feature_extractor.sampling_rate SCREAMING_SNAKE_CASE__ : Optional[int] = [ { """start_time""": d["""start_offset"""] * time_offset, """end_time""": d["""end_offset"""] * time_offset, """word""": d["""word"""], } for d in output["""word_offsets"""] ] SCREAMING_SNAKE_CASE__ : Optional[int] = """WHY DOES MILISANDRA LOOK LIKE SHE WANTS TO CONSUME JOHN SNOW ON THE RIVER AT THE WALL""" # output words self.assertEqual(""" """.join(self.get_from_offsets(_a , """word""" ) ) , _a ) self.assertEqual(""" """.join(self.get_from_offsets(_a , """word""" ) ) , output.text ) # output times SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor(self.get_from_offsets(_a , """start_time""" ) ) SCREAMING_SNAKE_CASE__ : int = torch.tensor(self.get_from_offsets(_a , """end_time""" ) ) # fmt: off SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([1.4_199, 1.6_599, 2.2_599, 3.0, 3.24, 3.5_999, 3.7_999, 4.0_999, 4.26, 4.94, 5.28, 5.6_599, 5.78, 5.94, 6.32, 6.5_399, 6.6_599] ) SCREAMING_SNAKE_CASE__ : Tuple = torch.tensor([1.5_399, 1.8_999, 2.9, 3.16, 3.5_399, 3.72, 4.0_199, 4.1_799, 4.76, 5.1_599, 5.5_599, 5.6_999, 5.86, 6.1_999, 6.38, 6.6_199, 6.94] ) # fmt: on self.assertTrue(torch.allclose(_a , _a , atol=0.01 ) ) self.assertTrue(torch.allclose(_a , _a , atol=0.01 ) )
680
"""simple docstring""" import numpy as np import qiskit def _lowercase ( __lowerCAmelCase = 8 , __lowerCAmelCase = None ) -> str: SCREAMING_SNAKE_CASE__ : List[Any] = np.random.default_rng(seed=__lowerCAmelCase ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. SCREAMING_SNAKE_CASE__ : List[str] = 6 * key_len # Measurement basis for Alice's qubits. SCREAMING_SNAKE_CASE__ : List[Any] = rng.integers(2 , size=__lowerCAmelCase ) # The set of states Alice will prepare. SCREAMING_SNAKE_CASE__ : Optional[Any] = rng.integers(2 , size=__lowerCAmelCase ) # Measurement basis for Bob's qubits. SCREAMING_SNAKE_CASE__ : str = rng.integers(2 , size=__lowerCAmelCase ) # Quantum Circuit to simulate BB84 SCREAMING_SNAKE_CASE__ : Union[str, Any] = qiskit.QuantumCircuit(__lowerCAmelCase , name="""BB84""" ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(__lowerCAmelCase ): if alice_state[index] == 1: bbaa_circ.x(__lowerCAmelCase ) if alice_basis[index] == 1: bbaa_circ.h(__lowerCAmelCase ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(__lowerCAmelCase ): if bob_basis[index] == 1: bbaa_circ.h(__lowerCAmelCase ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. SCREAMING_SNAKE_CASE__ : str = qiskit.Aer.get_backend("""aer_simulator""" ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. SCREAMING_SNAKE_CASE__ : Optional[int] = qiskit.execute(__lowerCAmelCase , __lowerCAmelCase , shots=1 , seed_simulator=__lowerCAmelCase ) # Returns the result of measurement. SCREAMING_SNAKE_CASE__ : int = job.result().get_counts(__lowerCAmelCase ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. SCREAMING_SNAKE_CASE__ : Optional[Any] = """""".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. SCREAMING_SNAKE_CASE__ : Optional[int] = gen_key[:key_len] if len(__lowerCAmelCase ) >= key_len else gen_key.ljust(__lowerCAmelCase , """0""" ) return key if __name__ == "__main__": print(f'The generated key is : {bbaa(8, seed=0)}') from doctest import testmod testmod()
680
1
"""simple docstring""" import numpy as np class __a : '''simple docstring''' def __init__( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = (0, 0) SCREAMING_SNAKE_CASE__ : Optional[Any] = None SCREAMING_SNAKE_CASE__ : List[Any] = 0 SCREAMING_SNAKE_CASE__ : List[Any] = 0 SCREAMING_SNAKE_CASE__ : List[str] = 0 def __eq__( self , _a ) -> str: """simple docstring""" return self.position == cell.position def _a ( self ) -> List[Any]: """simple docstring""" print(self.position ) class __a : '''simple docstring''' def __init__( self , _a=(5, 5) ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = np.zeros(_a ) SCREAMING_SNAKE_CASE__ : Any = world_size[0] SCREAMING_SNAKE_CASE__ : Tuple = world_size[1] def _a ( self ) -> List[Any]: """simple docstring""" print(self.w ) def _a ( self , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] SCREAMING_SNAKE_CASE__ : List[str] = cell.position[0] SCREAMING_SNAKE_CASE__ : Optional[int] = cell.position[1] SCREAMING_SNAKE_CASE__ : str = [] for n in neughbour_cord: SCREAMING_SNAKE_CASE__ : Tuple = current_x + n[0] SCREAMING_SNAKE_CASE__ : List[str] = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: SCREAMING_SNAKE_CASE__ : Union[str, Any] = Cell() SCREAMING_SNAKE_CASE__ : List[str] = (x, y) SCREAMING_SNAKE_CASE__ : int = cell neighbours.append(_a ) return neighbours def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> List[str]: SCREAMING_SNAKE_CASE__ : List[str] = [] SCREAMING_SNAKE_CASE__ : Any = [] _open.append(__lowerCAmelCase ) while _open: SCREAMING_SNAKE_CASE__ : Any = np.argmin([n.f for n in _open] ) SCREAMING_SNAKE_CASE__ : List[Any] = _open[min_f] _closed.append(_open.pop(__lowerCAmelCase ) ) if current == goal: break for n in world.get_neigbours(__lowerCAmelCase ): for c in _closed: if c == n: continue SCREAMING_SNAKE_CASE__ : List[Any] = current.g + 1 SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = n.position SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = goal.position SCREAMING_SNAKE_CASE__ : str = (ya - ya) ** 2 + (xa - xa) ** 2 SCREAMING_SNAKE_CASE__ : List[str] = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = [] while current.parent is not None: path.append(current.position ) SCREAMING_SNAKE_CASE__ : Optional[int] = current.parent path.append(current.position ) return path[::-1] if __name__ == "__main__": a :Tuple = Gridworld() # Start position and goal a :List[Any] = Cell() a :List[str] = (0, 0) a :int = Cell() a :List[str] = (4, 4) print(f'path from {start.position} to {goal.position}') a :Optional[int] = astar(world, start, goal) # Just for visual reasons. for i in s: a :Optional[Any] = 1 print(world.w)
680
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __a (UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :str = StableDiffusionInpaintPipeline _SCREAMING_SNAKE_CASE :Any = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS _SCREAMING_SNAKE_CASE :Dict = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS _SCREAMING_SNAKE_CASE :Optional[int] = frozenset( []) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _SCREAMING_SNAKE_CASE :Dict = frozenset([]) def _a ( self ) -> Dict: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , 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 , ) SCREAMING_SNAKE_CASE__ : List[str] = PNDMScheduler(skip_prk_steps=_a ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = 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 ) SCREAMING_SNAKE_CASE__ : int = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) SCREAMING_SNAKE_CASE__ : int = CLIPTextModel(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) SCREAMING_SNAKE_CASE__ : int = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def _a ( self , _a , _a=0 ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = floats_tensor((1, 3, 32, 32) , rng=random.Random(_a ) ).to(_a ) SCREAMING_SNAKE_CASE__ : Tuple = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : Any = Image.fromarray(np.uinta(_a ) ).convert("""RGB""" ).resize((64, 64) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(_a ).startswith("""mps""" ): SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(_a ) else: SCREAMING_SNAKE_CASE__ : str = torch.Generator(device=_a ).manual_seed(_a ) SCREAMING_SNAKE_CASE__ : Tuple = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInpaintPipeline(**_a ) SCREAMING_SNAKE_CASE__ : Any = sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : int = self.get_dummy_inputs(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe(**_a ).images SCREAMING_SNAKE_CASE__ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : str = np.array([0.4_727, 0.5_735, 0.3_941, 0.5_446, 0.5_926, 0.4_394, 0.5_062, 0.4_654, 0.4_476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _a ( self ) -> Optional[int]: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : Any = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : Any = StableDiffusionInpaintPipeline.from_pretrained(_a , safety_checker=_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : int = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Tuple = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : int = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) SCREAMING_SNAKE_CASE__ : List[str] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInpaintPipeline.from_pretrained( _a , torch_dtype=torch.floataa , safety_checker=_a , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Any = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Tuple = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def _a ( self ) -> Tuple: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE__ : Dict = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : str = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : List[str] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : Dict = PNDMScheduler.from_pretrained(_a , subfolder="""scheduler""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = StableDiffusionInpaintPipeline.from_pretrained( _a , safety_checker=_a , scheduler=_a , torch_dtype=torch.floataa , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE__ : Union[str, Any] = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , num_inference_steps=2 , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : List[str] = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
680
1
"""simple docstring""" import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Tuple = SamImageProcessor() SCREAMING_SNAKE_CASE__ : List[str] = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> Union[str, Any]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> Tuple: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Tuple = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Dict = processor(images=_a , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_torch def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [torch.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : str = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : List[Any] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : Any = processor.post_process_masks(_a , _a , _a ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Dict = processor.post_process_masks( _a , torch.tensor(_a ) , torch.tensor(_a ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np SCREAMING_SNAKE_CASE__ : Dict = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks(_a , np.array(_a ) , np.array(_a ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Dict = [[1, 0], [0, 1]] with self.assertRaises(_a ): SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks(_a , np.array(_a ) , np.array(_a ) ) @require_vision @require_tf class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Optional[int] = SamImageProcessor() SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> List[str]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> int: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Any = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : int = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Tuple = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Any = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Any = processor(images=_a , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_tf def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Union[str, Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [tf.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Optional[int] = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks(_a , _a , _a , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks( _a , tf.convert_to_tensor(_a ) , tf.convert_to_tensor(_a ) , return_tensors="""tf""" , ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np SCREAMING_SNAKE_CASE__ : Optional[int] = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks( _a , np.array(_a ) , np.array(_a ) , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Any = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): SCREAMING_SNAKE_CASE__ : str = processor.post_process_masks( _a , np.array(_a ) , np.array(_a ) , return_tensors="""tf""" ) @require_vision @require_torchvision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Dict = SamImageProcessor() SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> Any: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> Union[str, Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : int = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : List[Any] = [tf.convert_to_tensor(_a )] SCREAMING_SNAKE_CASE__ : Dict = [torch.tensor(_a )] SCREAMING_SNAKE_CASE__ : Optional[int] = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : List[str] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : List[Any] = processor.post_process_masks( _a , _a , _a , return_tensors="""tf""" ) SCREAMING_SNAKE_CASE__ : List[str] = processor.post_process_masks( _a , _a , _a , return_tensors="""pt""" ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : str = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : int = image_processor(_a , return_tensors="""pt""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : Any = processor(images=_a , return_tensors="""pt""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor(_a , return_tensors="""tf""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : str = processor(images=_a , return_tensors="""tf""" )["""pixel_values"""].numpy() self.assertTrue(np.allclose(_a , _a ) ) self.assertTrue(np.allclose(_a , _a ) ) self.assertTrue(np.allclose(_a , _a ) )
680
"""simple docstring""" import argparse import logging import pickle import random import time import numpy as np from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) a :str = logging.getLogger(__name__) def _lowercase ( ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Dict = argparse.ArgumentParser( description="""Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids).""" ) parser.add_argument("""--file_path""" , type=__lowerCAmelCase , default="""data/dump.txt""" , help="""The path to the data.""" ) parser.add_argument("""--tokenizer_type""" , type=__lowerCAmelCase , default="""bert""" , choices=["""bert""", """roberta""", """gpt2"""] ) parser.add_argument("""--tokenizer_name""" , type=__lowerCAmelCase , default="""bert-base-uncased""" , help="""The tokenizer to use.""" ) parser.add_argument("""--dump_file""" , type=__lowerCAmelCase , default="""data/dump""" , help="""The dump file prefix.""" ) SCREAMING_SNAKE_CASE__ : str = parser.parse_args() logger.info(F'''Loading Tokenizer ({args.tokenizer_name})''' ) if args.tokenizer_type == "bert": SCREAMING_SNAKE_CASE__ : List[str] = BertTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : str = tokenizer.special_tokens_map["""cls_token"""] # `[CLS]` SCREAMING_SNAKE_CASE__ : str = tokenizer.special_tokens_map["""sep_token"""] # `[SEP]` elif args.tokenizer_type == "roberta": SCREAMING_SNAKE_CASE__ : List[Any] = RobertaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.special_tokens_map["""cls_token"""] # `<s>` SCREAMING_SNAKE_CASE__ : Dict = tokenizer.special_tokens_map["""sep_token"""] # `</s>` elif args.tokenizer_type == "gpt2": SCREAMING_SNAKE_CASE__ : List[Any] = GPTaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.special_tokens_map["""bos_token"""] # `<|endoftext|>` SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.special_tokens_map["""eos_token"""] # `<|endoftext|>` logger.info(F'''Loading text from {args.file_path}''' ) with open(args.file_path , """r""" , encoding="""utf8""" ) as fp: SCREAMING_SNAKE_CASE__ : int = fp.readlines() logger.info("""Start encoding""" ) logger.info(F'''{len(__lowerCAmelCase )} examples to process.''' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1_0000 SCREAMING_SNAKE_CASE__ : Dict = time.time() for text in data: SCREAMING_SNAKE_CASE__ : Dict = F'''{bos} {text.strip()} {sep}''' SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) rslt.append(__lowerCAmelCase ) iter += 1 if iter % interval == 0: SCREAMING_SNAKE_CASE__ : str = time.time() logger.info(F'''{iter} examples processed. - {(end-start):.2f}s/{interval}expl''' ) SCREAMING_SNAKE_CASE__ : Tuple = time.time() logger.info("""Finished binarization""" ) logger.info(F'''{len(__lowerCAmelCase )} examples processed.''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = F'''{args.dump_file}.{args.tokenizer_name}.pickle''' SCREAMING_SNAKE_CASE__ : Dict = tokenizer.vocab_size if vocab_size < (1 << 16): SCREAMING_SNAKE_CASE__ : Tuple = [np.uintaa(__lowerCAmelCase ) for d in rslt] else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [np.intaa(__lowerCAmelCase ) for d in rslt] random.shuffle(rslt_ ) logger.info(F'''Dump to {dp_file}''' ) with open(__lowerCAmelCase , """wb""" ) as handle: pickle.dump(rslt_ , __lowerCAmelCase , protocol=pickle.HIGHEST_PROTOCOL ) if __name__ == "__main__": main()
680
1
"""simple docstring""" import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask a :List[str] = logging.getLogger(__name__) class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , _a=-1 ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = label_idx def _a ( self , _a , _a ) -> List[InputExample]: """simple docstring""" if isinstance(_a , _a ): SCREAMING_SNAKE_CASE__ : List[str] = mode.value SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(_a , f'''{mode}.txt''' ) SCREAMING_SNAKE_CASE__ : List[str] = 1 SCREAMING_SNAKE_CASE__ : Tuple = [] with open(_a , encoding="""utf-8""" ) as f: SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : List[str] = [] for line in f: if line.startswith("""-DOCSTART-""" ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=f'''{mode}-{guid_index}''' , words=_a , labels=_a ) ) guid_index += 1 SCREAMING_SNAKE_CASE__ : Optional[Any] = [] SCREAMING_SNAKE_CASE__ : Any = [] else: SCREAMING_SNAKE_CASE__ : str = line.split(""" """ ) words.append(splits[0] ) if len(_a ) > 1: labels.append(splits[self.label_idx].replace("""\n""" , """""" ) ) else: # Examples could have no label for mode = "test" labels.append("""O""" ) if words: examples.append(InputExample(guid=f'''{mode}-{guid_index}''' , words=_a , labels=_a ) ) return examples def _a ( self , _a , _a , _a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = 0 for line in test_input_reader: if line.startswith("""-DOCSTART-""" ) or line == "" or line == "\n": writer.write(_a ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: SCREAMING_SNAKE_CASE__ : Union[str, Any] = line.split()[0] + """ """ + preds_list[example_id].pop(0 ) + """\n""" writer.write(_a ) else: logger.warning("""Maximum sequence length exceeded: No prediction for '%s'.""" , line.split()[0] ) def _a ( self , _a ) -> List[str]: """simple docstring""" if path: with open(_a , """r""" ) as f: SCREAMING_SNAKE_CASE__ : int = f.read().splitlines() if "O" not in labels: SCREAMING_SNAKE_CASE__ : List[Any] = ["""O"""] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class __a (UpperCamelCase_): '''simple docstring''' def __init__( self ) -> Optional[Any]: """simple docstring""" super().__init__(label_idx=-2 ) def _a ( self , _a ) -> List[str]: """simple docstring""" if path: with open(_a , """r""" ) as f: SCREAMING_SNAKE_CASE__ : Any = f.read().splitlines() if "O" not in labels: SCREAMING_SNAKE_CASE__ : Any = ["""O"""] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class __a (UpperCamelCase_): '''simple docstring''' def _a ( self , _a , _a ) -> List[InputExample]: """simple docstring""" if isinstance(_a , _a ): SCREAMING_SNAKE_CASE__ : List[str] = mode.value SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.join(_a , f'''{mode}.txt''' ) SCREAMING_SNAKE_CASE__ : List[Any] = 1 SCREAMING_SNAKE_CASE__ : int = [] with open(_a , encoding="""utf-8""" ) as f: for sentence in parse_incr(_a ): SCREAMING_SNAKE_CASE__ : Tuple = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] for token in sentence: words.append(token["""form"""] ) labels.append(token["""upos"""] ) assert len(_a ) == len(_a ) if words: examples.append(InputExample(guid=f'''{mode}-{guid_index}''' , words=_a , labels=_a ) ) guid_index += 1 return examples def _a ( self , _a , _a , _a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = 0 for sentence in parse_incr(_a ): SCREAMING_SNAKE_CASE__ : Optional[Any] = preds_list[example_id] SCREAMING_SNAKE_CASE__ : List[str] = """""" for token in sentence: out += f'''{token['form']} ({token['upos']}|{s_p.pop(0 )}) ''' out += "\n" writer.write(_a ) example_id += 1 def _a ( self , _a ) -> List[str]: """simple docstring""" if path: with open(_a , """r""" ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
680
"""simple docstring""" import glob import os import random from string import ascii_lowercase, digits import cva a :List[Any] = "" a :Union[str, Any] = "" a :List[str] = "" a :str = 1 # (0 is vertical, 1 is horizontal) def _lowercase ( ) -> None: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = get_dataset(__lowerCAmelCase , __lowerCAmelCase ) print("""Processing...""" ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = update_image_and_anno(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) for index, image in enumerate(__lowerCAmelCase ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' SCREAMING_SNAKE_CASE__ : List[Any] = random_chars(32 ) SCREAMING_SNAKE_CASE__ : List[str] = paths[index].split(os.sep )[-1].rsplit(""".""" , 1 )[0] SCREAMING_SNAKE_CASE__ : List[str] = F'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(F'''/{file_root}.jpg''' , __lowerCAmelCase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F'''Success {index+1}/{len(__lowerCAmelCase )} with {file_name}''' ) SCREAMING_SNAKE_CASE__ : int = [] for anno in new_annos[index]: SCREAMING_SNAKE_CASE__ : Tuple = F'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(__lowerCAmelCase ) with open(F'''/{file_root}.txt''' , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> tuple[list, list]: SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] for label_file in glob.glob(os.path.join(__lowerCAmelCase , """*.txt""" ) ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(__lowerCAmelCase ) as in_file: SCREAMING_SNAKE_CASE__ : Dict = in_file.readlines() SCREAMING_SNAKE_CASE__ : int = os.path.join(__lowerCAmelCase , F'''{label_name}.jpg''' ) SCREAMING_SNAKE_CASE__ : int = [] for obj_list in obj_lists: SCREAMING_SNAKE_CASE__ : Optional[int] = obj_list.rstrip("""\n""" ).split(""" """ ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(__lowerCAmelCase ) labels.append(__lowerCAmelCase ) return img_paths, labels def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = 1 ) -> tuple[list, list, list]: SCREAMING_SNAKE_CASE__ : Dict = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [] for idx in range(len(__lowerCAmelCase ) ): SCREAMING_SNAKE_CASE__ : List[str] = [] SCREAMING_SNAKE_CASE__ : str = img_list[idx] path_list.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = anno_list[idx] SCREAMING_SNAKE_CASE__ : Tuple = cva.imread(__lowerCAmelCase ) if flip_type == 1: SCREAMING_SNAKE_CASE__ : int = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: SCREAMING_SNAKE_CASE__ : Optional[int] = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: SCREAMING_SNAKE_CASE__ : Any = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: SCREAMING_SNAKE_CASE__ : List[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(__lowerCAmelCase ) new_imgs_list.append(__lowerCAmelCase ) return new_imgs_list, new_annos_lists, path_list def _lowercase ( __lowerCAmelCase = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" SCREAMING_SNAKE_CASE__ : List[str] = ascii_lowercase + digits return "".join(random.choice(__lowerCAmelCase ) for _ in range(__lowerCAmelCase ) ) if __name__ == "__main__": main() print("DONE ✅")
680
1
"""simple docstring""" from sklearn.metrics import recall_score import datasets a :Optional[int] = "\nRecall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation:\nRecall = TP / (TP + FN)\nWhere TP is the true positives and FN is the false negatives.\n" a :Optional[Any] = "\nArgs:\n- **predictions** (`list` of `int`): The predicted labels.\n- **references** (`list` of `int`): The ground truth labels.\n- **labels** (`list` of `int`): The set of labels to include when `average` is not set to `binary`, and their order when average is `None`. Labels present in the data can be excluded in this input, for example to calculate a multiclass average ignoring a majority negative class, while 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 y_true and y_pred are used in sorted order. Defaults to None.\n- **pos_label** (`int`): The class label to use as the 'positive class' when calculating the recall. Defaults to `1`.\n- **average** (`string`): This parameter is required for multiclass/multilabel targets. If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.\n - `'binary'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions are binary.\n - `'micro'`: Calculate metrics globally by counting the total true positives, false negatives, and false positives.\n - `'macro'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n - `'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. Note that it can result in an F-score that is not between precision and recall.\n - `'samples'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n- **sample_weight** (`list` of `float`): Sample weights Defaults to `None`.\n- **zero_division** (): Sets the value to return when there is a zero division. Defaults to .\n - `'warn'`: If there is a zero division, the return value is `0`, but warnings are also raised.\n - `0`: If there is a zero division, the return value is `0`.\n - `1`: If there is a zero division, the return value is `1`.\n\nReturns:\n- **recall** (`float`, or `array` of `float`): Either the general recall score, or the recall scores for individual classes, depending on the values input to `labels` and `average`. Minimum possible value is 0. Maximum possible value is 1. A higher recall means that more of the positive examples have been labeled correctly. Therefore, a higher recall is generally considered better.\n\nExamples:\n\n Example 1-A simple example with some errors\n >>> recall_metric = datasets.load_metric('recall')\n >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1])\n >>> print(results)\n {'recall': 0.6666666666666666}\n\n Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`.\n >>> recall_metric = datasets.load_metric('recall')\n >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0)\n >>> print(results)\n {'recall': 0.5}\n\n Example 3-The same example as Example 1, but with `sample_weight` included.\n >>> recall_metric = datasets.load_metric('recall')\n >>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8]\n >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight)\n >>> print(results)\n {'recall': 0.55}\n\n Example 4-A multiclass example, using different averages.\n >>> recall_metric = datasets.load_metric('recall')\n >>> predictions = [0, 2, 1, 0, 0, 1]\n >>> references = [0, 1, 2, 0, 1, 2]\n >>> results = recall_metric.compute(predictions=predictions, references=references, average='macro')\n >>> print(results)\n {'recall': 0.3333333333333333}\n >>> results = recall_metric.compute(predictions=predictions, references=references, average='micro')\n >>> print(results)\n {'recall': 0.3333333333333333}\n >>> results = recall_metric.compute(predictions=predictions, references=references, average='weighted')\n >>> print(results)\n {'recall': 0.3333333333333333}\n >>> results = recall_metric.compute(predictions=predictions, references=references, average=None)\n >>> print(results)\n {'recall': array([1., 0., 0.])}\n" a :Dict = "\n@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}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class __a (datasets.Metric): '''simple docstring''' def _a ( self ) -> List[Any]: """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.recall_score.html"""] , ) def _a ( self , _a , _a , _a=None , _a=1 , _a="binary" , _a=None , _a="warn" , ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = recall_score( _a , _a , labels=_a , pos_label=_a , average=_a , sample_weight=_a , zero_division=_a , ) return {"recall": float(_a ) if score.size == 1 else score}
680
"""simple docstring""" import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class __a (enum.Enum): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = 0 _SCREAMING_SNAKE_CASE :List[Any] = 1 _SCREAMING_SNAKE_CASE :Dict = 2 @add_end_docstrings(UpperCamelCase_) class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = """ In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision and denounces one of the men as a horse thief. Although his father initially slaps him for making such an accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop, begging for his blessing. <eod> </s> <eos> """ def __init__( self , *_a , **_a ) -> Tuple: """simple docstring""" super().__init__(*_a , **_a ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == """tf""" else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. SCREAMING_SNAKE_CASE__ : Any = None if self.model.config.prefix is not None: SCREAMING_SNAKE_CASE__ : List[str] = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. SCREAMING_SNAKE_CASE__ : Optional[Any] = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self._sanitize_parameters(prefix=_a , **self._forward_params ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {**self._preprocess_params, **preprocess_params} SCREAMING_SNAKE_CASE__ : Optional[Any] = {**self._forward_params, **forward_params} def _a ( self , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , **_a , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = {} if prefix is not None: SCREAMING_SNAKE_CASE__ : Dict = prefix if prefix: SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer( _a , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Tuple = prefix_inputs["""input_ids"""].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( f'''{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected''' """ [None, 'hole']""" ) SCREAMING_SNAKE_CASE__ : int = handle_long_generation preprocess_params.update(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs SCREAMING_SNAKE_CASE__ : int = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_full_text`""" ) if return_tensors is not None: raise ValueError("""`return_full_text` is mutually exclusive with `return_tensors`""" ) SCREAMING_SNAKE_CASE__ : List[Any] = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_tensors`""" ) SCREAMING_SNAKE_CASE__ : Tuple = ReturnType.TENSORS if return_type is not None: SCREAMING_SNAKE_CASE__ : int = return_type if clean_up_tokenization_spaces is not None: SCREAMING_SNAKE_CASE__ : List[str] = clean_up_tokenization_spaces if stop_sequence is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.encode(_a , add_special_tokens=_a ) if len(_a ) > 1: warnings.warn( """Stopping on a multiple token sequence is not yet supported on transformers. The first token of""" """ the stop sequence will be used as the stop sequence string in the interim.""" ) SCREAMING_SNAKE_CASE__ : List[Any] = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def _a ( self , *_a , **_a ) -> Any: """simple docstring""" if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({"""add_space_before_punct_symbol""": True} ) return super()._parse_and_tokenize(*_a , **_a ) def __call__( self , _a , **_a ) -> Optional[int]: """simple docstring""" return super().__call__(_a , **_a ) def _a ( self , _a , _a="" , _a=None , **_a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer( prefix + prompt_text , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Tuple = prompt_text if handle_long_generation == "hole": SCREAMING_SNAKE_CASE__ : List[Any] = inputs["""input_ids"""].shape[-1] if "max_new_tokens" in generate_kwargs: SCREAMING_SNAKE_CASE__ : Union[str, Any] = generate_kwargs["""max_new_tokens"""] else: SCREAMING_SNAKE_CASE__ : Tuple = generate_kwargs.get("""max_length""" , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError("""We cannot infer how many new tokens are expected""" ) if cur_len + new_tokens > self.tokenizer.model_max_length: SCREAMING_SNAKE_CASE__ : str = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( """We cannot use `hole` to handle this generation the number of desired tokens exceeds the""" """ models max length""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs["""input_ids"""][:, -keep_length:] if "attention_mask" in inputs: SCREAMING_SNAKE_CASE__ : Optional[int] = inputs["""attention_mask"""][:, -keep_length:] return inputs def _a ( self , _a , **_a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_inputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : Optional[int] = model_inputs.get("""attention_mask""" , _a ) # Allow empty prompts if input_ids.shape[1] == 0: SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : List[Any] = None SCREAMING_SNAKE_CASE__ : List[str] = 1 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.shape[0] SCREAMING_SNAKE_CASE__ : Tuple = model_inputs.pop("""prompt_text""" ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs.pop("""prefix_length""" , 0 ) if prefix_length > 0: SCREAMING_SNAKE_CASE__ : List[str] = """max_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].max_new_tokens is not None ) if not has_max_new_tokens: SCREAMING_SNAKE_CASE__ : int = generate_kwargs.get("""max_length""" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length SCREAMING_SNAKE_CASE__ : Dict = """min_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL SCREAMING_SNAKE_CASE__ : Tuple = self.model.generate(input_ids=_a , attention_mask=_a , **_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = generated_sequence.shape[0] if self.framework == "pt": SCREAMING_SNAKE_CASE__ : str = generated_sequence.reshape(_a , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.reshape(_a , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def _a ( self , _a , _a=ReturnType.FULL_TEXT , _a=True ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = model_outputs["""generated_sequence"""][0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_outputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : str = model_outputs["""prompt_text"""] SCREAMING_SNAKE_CASE__ : Any = generated_sequence.numpy().tolist() SCREAMING_SNAKE_CASE__ : List[Any] = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: SCREAMING_SNAKE_CASE__ : Tuple = {"""generated_token_ids""": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.decode( _a , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: SCREAMING_SNAKE_CASE__ : Dict = 0 else: SCREAMING_SNAKE_CASE__ : Optional[int] = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) ) if return_type == ReturnType.FULL_TEXT: SCREAMING_SNAKE_CASE__ : Tuple = prompt_text + text[prompt_length:] else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = text[prompt_length:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {"""generated_text""": all_text} records.append(_a ) return records
680
1
"""simple docstring""" a :Optional[Any] = { "Pillow": "Pillow", "accelerate": "accelerate>=0.11.0", "compel": "compel==0.1.8", "black": "black~=23.1", "datasets": "datasets", "filelock": "filelock", "flax": "flax>=0.4.1", "hf-doc-builder": "hf-doc-builder>=0.3.0", "huggingface-hub": "huggingface-hub>=0.13.2", "requests-mock": "requests-mock==1.10.0", "importlib_metadata": "importlib_metadata", "invisible-watermark": "invisible-watermark", "isort": "isort>=5.5.4", "jax": "jax>=0.2.8,!=0.3.2", "jaxlib": "jaxlib>=0.1.65", "Jinja2": "Jinja2", "k-diffusion": "k-diffusion>=0.0.12", "torchsde": "torchsde", "note_seq": "note_seq", "librosa": "librosa", "numpy": "numpy", "omegaconf": "omegaconf", "parameterized": "parameterized", "protobuf": "protobuf>=3.20.3,<4", "pytest": "pytest", "pytest-timeout": "pytest-timeout", "pytest-xdist": "pytest-xdist", "ruff": "ruff>=0.0.241", "safetensors": "safetensors", "sentencepiece": "sentencepiece>=0.1.91,!=0.1.92", "scipy": "scipy", "onnx": "onnx", "regex": "regex!=2019.12.17", "requests": "requests", "tensorboard": "tensorboard", "torch": "torch>=1.4", "torchvision": "torchvision", "transformers": "transformers>=4.25.1", "urllib3": "urllib3<=2.0.0", }
680
"""simple docstring""" from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> list[float]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = coefficient_matrix.shape SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE__ : Tuple = F'''Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if colsa != 1: SCREAMING_SNAKE_CASE__ : str = F'''Constant matrix must be nx1 but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if rowsa != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Coefficient and constant matrices dimensions must be nxn and nx1 but """ F'''received {rowsa}x{colsa} and {rowsa}x{colsa}''' ) raise ValueError(__lowerCAmelCase ) if len(__lowerCAmelCase ) != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Number of initial values must be equal to number of rows in coefficient """ F'''matrix but received {len(__lowerCAmelCase )} and {rowsa}''' ) raise ValueError(__lowerCAmelCase ) if iterations <= 0: raise ValueError("""Iterations must be at least 1""" ) SCREAMING_SNAKE_CASE__ : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = table.shape strictly_diagonally_dominant(__lowerCAmelCase ) # Iterates the whole matrix for given number of times for _ in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = [] for row in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = 0 for col in range(__lowerCAmelCase ): if col == row: SCREAMING_SNAKE_CASE__ : int = table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE__ : Any = (temp + val) / denom new_val.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = new_val return [float(__lowerCAmelCase ) for i in new_val] def _lowercase ( __lowerCAmelCase ) -> bool: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = table.shape SCREAMING_SNAKE_CASE__ : str = True for i in range(0 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("""Coefficient matrix is not strictly diagonally dominant""" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
680
1
"""simple docstring""" from ..utils import DummyObject, requires_backends class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[int] = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Tuple = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[int] = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> List[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Dict = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> Any: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> Union[str, Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[int] = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> List[str]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[int] = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> List[str]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> Any: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[int] = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> Optional[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :str = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> Union[str, Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> Optional[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> Dict: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Tuple = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> Tuple: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> Tuple: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :int = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> List[str]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Any = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> Tuple: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :str = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> Any: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :int = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> List[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> Dict: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> List[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :str = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> Dict: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[int] = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> List[str]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Tuple = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[str] = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> Tuple: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Tuple = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> Dict: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> Optional[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> List[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = ["""sentencepiece"""] def __init__( self , *_a , **_a ) -> Union[str, Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] )
680
"""simple docstring""" import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Union[str, Path]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = True _SCREAMING_SNAKE_CASE :Optional[int] = None _SCREAMING_SNAKE_CASE :int = 1 _SCREAMING_SNAKE_CASE :Optional[Union[str, bool]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None def _a ( self ) -> "DownloadConfig": """simple docstring""" return self.__class__(**{k: copy.deepcopy(_a ) for k, v in self.__dict__.items()} )
680
1
"""simple docstring""" import os import unicodedata 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 SPIECE_UNDERLINE, logging a :int = logging.get_logger(__name__) a :Any = {"vocab_file": "spiece.model"} a :Optional[Any] = { "vocab_file": { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model", } } a :str = { "xlnet-base-cased": None, "xlnet-large-cased": None, } # Segments (not really needed) a :Any = 0 a :Optional[int] = 1 a :Union[str, Any] = 2 a :str = 3 a :Union[str, Any] = 4 class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :int = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE :Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE :str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE :Union[str, Any] = """left""" def __init__( self , _a , _a=False , _a=True , _a=False , _a="<s>" , _a="</s>" , _a="<unk>" , _a="<sep>" , _a="<pad>" , _a="<cls>" , _a="<mask>" , _a=["<eop>", "<eod>"] , _a = None , **_a , ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token SCREAMING_SNAKE_CASE__ : Dict = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=_a , remove_space=_a , keep_accents=_a , bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , pad_token=_a , cls_token=_a , mask_token=_a , additional_special_tokens=_a , sp_model_kwargs=self.sp_model_kwargs , **_a , ) SCREAMING_SNAKE_CASE__ : Optional[int] = 3 SCREAMING_SNAKE_CASE__ : Optional[int] = do_lower_case SCREAMING_SNAKE_CASE__ : Union[str, Any] = remove_space SCREAMING_SNAKE_CASE__ : Optional[Any] = keep_accents SCREAMING_SNAKE_CASE__ : Dict = vocab_file SCREAMING_SNAKE_CASE__ : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_a ) @property def _a ( self ) -> Optional[Any]: """simple docstring""" return len(self.sp_model ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = {self.convert_ids_to_tokens(_a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.__dict__.copy() SCREAMING_SNAKE_CASE__ : Dict = None return state def __setstate__( self , _a ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): SCREAMING_SNAKE_CASE__ : Any = {} SCREAMING_SNAKE_CASE__ : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _a ( self , _a ) -> str: """simple docstring""" if self.remove_space: SCREAMING_SNAKE_CASE__ : List[str] = """ """.join(inputs.strip().split() ) else: SCREAMING_SNAKE_CASE__ : List[str] = inputs SCREAMING_SNAKE_CASE__ : Any = outputs.replace("""``""" , """\"""" ).replace("""''""" , """\"""" ) if not self.keep_accents: SCREAMING_SNAKE_CASE__ : int = unicodedata.normalize("""NFKD""" , _a ) SCREAMING_SNAKE_CASE__ : List[Any] = """""".join([c for c in outputs if not unicodedata.combining(_a )] ) if self.do_lower_case: SCREAMING_SNAKE_CASE__ : Tuple = outputs.lower() return outputs def _a ( self , _a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.preprocess_text(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = self.sp_model.encode(_a , out_type=_a ) SCREAMING_SNAKE_CASE__ : Tuple = [] for piece in pieces: if len(_a ) > 1 and piece[-1] == str(""",""" ) and piece[-2].isdigit(): SCREAMING_SNAKE_CASE__ : str = self.sp_model.EncodeAsPieces(piece[:-1].replace(_a , """""" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: SCREAMING_SNAKE_CASE__ : str = cur_pieces[1:] else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(_a ) else: new_pieces.append(_a ) return new_pieces def _a ( self , _a ) -> Optional[Any]: """simple docstring""" return self.sp_model.PieceToId(_a ) def _a ( self , _a ) -> List[str]: """simple docstring""" return self.sp_model.IdToPiece(_a ) def _a ( self , _a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = """""".join(_a ).replace(_a , """ """ ).strip() return out_string def _a ( self , _a , _a = False , _a = None , _a = True , **_a , ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = kwargs.pop("""use_source_tokenizer""" , _a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.convert_ids_to_tokens(_a , skip_special_tokens=_a ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 SCREAMING_SNAKE_CASE__ : int = [] SCREAMING_SNAKE_CASE__ : List[str] = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(_a ) ) SCREAMING_SNAKE_CASE__ : int = [] sub_texts.append(_a ) else: current_sub_text.append(_a ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(_a ) ) # Mimic the behavior of the Rust tokenizer: # By default, there are no spaces between special tokens SCREAMING_SNAKE_CASE__ : Optional[int] = """""".join(_a ) SCREAMING_SNAKE_CASE__ : str = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: SCREAMING_SNAKE_CASE__ : Optional[int] = self.clean_up_tokenization(_a ) return clean_text else: return text def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : List[str] = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def _a ( self , _a , _a = None , _a = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a , token_ids_a=_a , already_has_special_tokens=_a ) if token_ids_a is not None: return ([0] * len(_a )) + [1] + ([0] * len(_a )) + [1, 1] return ([0] * len(_a )) + [1, 1] def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : int = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def _a ( self , _a , _a = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE__ : int = 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: SCREAMING_SNAKE_CASE__ : Optional[Any] = self.sp_model.serialized_model_proto() fi.write(_a ) return (out_vocab_file,)
680
"""simple docstring""" import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger a :Optional[Any] = "<<<<<<< This should probably be modified because it mentions: " a :Tuple = "=======\n>>>>>>>\n" a :str = [ "TextEncoderConfig", "ByteTextEncoder", "SubwordTextEncoder", "encoder_config", "maybe_build_from_corpus", "manual_dir", ] a :Union[str, Any] = [ # (pattern, replacement) # Order is important here for some replacements (r"tfds\.core", r"datasets"), (r"tf\.io\.gfile\.GFile", r"open"), (r"tf\.([\w\d]+)", r"datasets.Value('\1')"), (r"tfds\.features\.Text\(\)", r"datasets.Value('string')"), (r"tfds\.features\.Text\(", r"datasets.Value('string'),"), (r"features\s*=\s*tfds.features.FeaturesDict\(", r"features=datasets.Features("), (r"tfds\.features\.FeaturesDict\(", r"dict("), (r"The TensorFlow Datasets Authors", r"The TensorFlow Datasets Authors and the HuggingFace Datasets Authors"), (r"tfds\.", r"datasets."), (r"dl_manager\.manual_dir", r"self.config.data_dir"), (r"self\.builder_config", r"self.config"), ] def _lowercase ( __lowerCAmelCase ) -> int: return ConvertCommand(args.tfds_path , args.datasets_directory ) class __a (UpperCamelCase_): '''simple docstring''' @staticmethod def _a ( _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.add_parser( """convert""" , help="""Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.""" , ) train_parser.add_argument( """--tfds_path""" , type=_a , required=_a , help="""Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.""" , ) train_parser.add_argument( """--datasets_directory""" , type=_a , required=_a , help="""Path to the HuggingFace Datasets folder.""" ) train_parser.set_defaults(func=_a ) def __init__( self , _a , _a , *_a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = get_logger("""datasets-cli/converting""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tfds_path SCREAMING_SNAKE_CASE__ : List[Any] = datasets_directory def _a ( self ) -> List[str]: """simple docstring""" if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.abspath(self._tfds_path ) elif os.path.isfile(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Tuple = os.path.dirname(self._tfds_path ) else: raise ValueError("""--tfds_path is neither a directory nor a file. Please check path.""" ) SCREAMING_SNAKE_CASE__ : Dict = os.path.abspath(self._datasets_directory ) self._logger.info(f'''Converting datasets from {abs_tfds_path} to {abs_datasets_path}''' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : List[Any] = {} if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.listdir(_a ) else: SCREAMING_SNAKE_CASE__ : List[Any] = [os.path.basename(self._tfds_path )] for f_name in file_names: self._logger.info(f'''Looking at file {f_name}''' ) SCREAMING_SNAKE_CASE__ : int = os.path.join(_a , _a ) SCREAMING_SNAKE_CASE__ : Dict = os.path.join(_a , _a ) if not os.path.isfile(_a ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info("""Skipping file""" ) continue with open(_a , encoding="""utf-8""" ) as f: SCREAMING_SNAKE_CASE__ : List[str] = f.readlines() SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = False SCREAMING_SNAKE_CASE__ : Optional[int] = False SCREAMING_SNAKE_CASE__ : Dict = [] for line in lines: SCREAMING_SNAKE_CASE__ : List[str] = line # Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: SCREAMING_SNAKE_CASE__ : List[Any] = """import datasets\n""" elif "import tensorflow" in out_line: # order is important here SCREAMING_SNAKE_CASE__ : Optional[Any] = """""" continue elif "from absl import logging" in out_line: SCREAMING_SNAKE_CASE__ : Any = """from datasets import logging\n""" elif "getLogger" in out_line: SCREAMING_SNAKE_CASE__ : Optional[int] = out_line.replace("""getLogger""" , """get_logger""" ) elif any(expression in out_line for expression in TO_HIGHLIGHT ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Tuple = list(filter(lambda _a : e in out_line , _a ) ) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(_a ) + """\n""" ) out_lines.append(_a ) out_lines.append(_a ) continue else: for pattern, replacement in TO_CONVERT: SCREAMING_SNAKE_CASE__ : int = re.sub(_a , _a , _a ) # Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: SCREAMING_SNAKE_CASE__ : Dict = re.match(r"""from\stensorflow_datasets.*import\s([^\.\r\n]+)""" , _a ) tfds_imports.extend(imp.strip() for imp in match.group(1 ).split(""",""" ) ) SCREAMING_SNAKE_CASE__ : Dict = """from . import """ + match.group(1 ) # Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(f'''Error converting {out_line.strip()}''' ) if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line: SCREAMING_SNAKE_CASE__ : Union[str, Any] = True out_lines.append(_a ) if is_builder or "wmt" in f_name: # We create a new directory for each dataset SCREAMING_SNAKE_CASE__ : Union[str, Any] = f_name.replace(""".py""" , """""" ) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(_a , _a ) SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(_a , _a ) os.makedirs(_a , exist_ok=_a ) self._logger.info(f'''Adding directory {output_dir}''' ) imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} ) else: # Utilities will be moved at the end utils_files.append(_a ) if needs_manual_update: with_manual_update.append(_a ) with open(_a , """w""" , encoding="""utf-8""" ) as f: f.writelines(_a ) self._logger.info(f'''Converted in {output_file}''' ) for utils_file in utils_files: try: SCREAMING_SNAKE_CASE__ : str = os.path.basename(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = imports_to_builder_map[f_name.replace(""".py""" , """""" )] self._logger.info(f'''Moving {dest_folder} to {utils_file}''' ) shutil.copy(_a , _a ) except KeyError: self._logger.error(f'''Cannot find destination folder for {utils_file}. Please copy manually.''' ) if with_manual_update: for file_path in with_manual_update: self._logger.warning( f'''You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.''' )
680
1
"""simple docstring""" import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=UpperCamelCase_) class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :str = field(default="""automatic-speech-recognition""" , metadata={"""include_in_asdict_even_if_is_default""": True}) _SCREAMING_SNAKE_CASE :ClassVar[Features] = Features({"""audio""": Audio()}) _SCREAMING_SNAKE_CASE :ClassVar[Features] = Features({"""transcription""": Value("""string""")}) _SCREAMING_SNAKE_CASE :str = "audio" _SCREAMING_SNAKE_CASE :str = "transcription" def _a ( self , _a ) -> List[str]: """simple docstring""" if self.audio_column not in features: raise ValueError(f'''Column {self.audio_column} is not present in features.''' ) if not isinstance(features[self.audio_column] , _a ): raise ValueError(f'''Column {self.audio_column} is not an Audio type.''' ) SCREAMING_SNAKE_CASE__ : Dict = copy.deepcopy(self ) SCREAMING_SNAKE_CASE__ : str = self.input_schema.copy() SCREAMING_SNAKE_CASE__ : Union[str, Any] = features[self.audio_column] SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_schema return task_template @property def _a ( self ) -> Dict[str, str]: """simple docstring""" return {self.audio_column: "audio", self.transcription_column: "transcription"}
680
"""simple docstring""" from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance a :str = 637_8137.0 a :Optional[Any] = 635_6752.31_4245 a :List[Any] = 6_378_137 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> float: SCREAMING_SNAKE_CASE__ : Dict = (AXIS_A - AXIS_B) / AXIS_A # Parametric latitudes # https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) # Compute central angle between two points # using haversine theta. sigma = haversine_distance / equatorial radius SCREAMING_SNAKE_CASE__ : Tuple = haversine_distance(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) / EQUATORIAL_RADIUS # Intermediate P and Q values SCREAMING_SNAKE_CASE__ : List[str] = (b_lata + b_lata) / 2 SCREAMING_SNAKE_CASE__ : Dict = (b_lata - b_lata) / 2 # Intermediate X value # X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2) SCREAMING_SNAKE_CASE__ : Tuple = (sin(__lowerCAmelCase ) ** 2) * (cos(__lowerCAmelCase ) ** 2) SCREAMING_SNAKE_CASE__ : str = cos(sigma / 2 ) ** 2 SCREAMING_SNAKE_CASE__ : List[str] = (sigma - sin(__lowerCAmelCase )) * (x_numerator / x_demonimator) # Intermediate Y value # Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2) SCREAMING_SNAKE_CASE__ : int = (cos(__lowerCAmelCase ) ** 2) * (sin(__lowerCAmelCase ) ** 2) SCREAMING_SNAKE_CASE__ : int = sin(sigma / 2 ) ** 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = (sigma + sin(__lowerCAmelCase )) * (y_numerator / y_denominator) return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value))) if __name__ == "__main__": import doctest doctest.testmod()
680
1
"""simple docstring""" from manim import * class __a (UpperCamelCase_): '''simple docstring''' def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = Rectangle(height=0.5 , width=0.5 ) SCREAMING_SNAKE_CASE__ : int = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) SCREAMING_SNAKE_CASE__ : Any = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE__ : List[str] = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE__ : Tuple = VGroup(*_a ).arrange(_a , buff=0 ) SCREAMING_SNAKE_CASE__ : Dict = VGroup(*_a ).arrange(_a , buff=0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = VGroup(_a , _a ).arrange(_a , buff=0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = Text("""CPU""" , font_size=24 ) SCREAMING_SNAKE_CASE__ : Any = Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a ) cpu.move_to([-2.5, -0.5, 0] ) self.add(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [mem.copy() for i in range(1 )] SCREAMING_SNAKE_CASE__ : Any = VGroup(*_a ).arrange(_a , buff=0 ) SCREAMING_SNAKE_CASE__ : List[Any] = Text("""GPU""" , font_size=24 ) SCREAMING_SNAKE_CASE__ : List[str] = Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a ) gpu.align_to(_a , _a ) gpu.set_x(gpu.get_x() - 1 ) self.add(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE__ : Any = VGroup(*_a ).arrange(_a , buff=0 ) SCREAMING_SNAKE_CASE__ : List[str] = Text("""Model""" , font_size=24 ) SCREAMING_SNAKE_CASE__ : List[Any] = Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a ) model.move_to([3, -1.0, 0] ) self.play( Create(_a , run_time=1 ) , Create(_a , run_time=1 ) , Create(_a , run_time=1 ) , ) SCREAMING_SNAKE_CASE__ : str = MarkupText( f'''First, an empty model skeleton is loaded\ninto <span fgcolor=\'{YELLOW}\'>memory</span> without using much RAM.''' , font_size=24 , ) SCREAMING_SNAKE_CASE__ : List[Any] = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) SCREAMING_SNAKE_CASE__ : Optional[int] = MarkupText( f'''<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model''' , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) step_a.move_to([2, 2, 0] ) self.play(Write(_a , run_time=2.5 ) , Write(_a ) , Write(_a ) ) self.add(_a ) SCREAMING_SNAKE_CASE__ : Tuple = [] SCREAMING_SNAKE_CASE__ : Optional[Any] = [] SCREAMING_SNAKE_CASE__ : List[Any] = [] for i, rect in enumerate(_a ): SCREAMING_SNAKE_CASE__ : Tuple = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0.0 ).set_fill(_a , opacity=0.7 ) cpu_target.move_to(_a ) cpu_target.generate_target() SCREAMING_SNAKE_CASE__ : Any = 0.46 / 4 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0.46 / 3 if i == 0: cpu_target.target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=_a ) cpu_target.target.set_x(cpu_target.target.get_x() + 0.1 ) elif i == 3: cpu_target.target.next_to(cpu_targs[0].target , direction=_a , buff=0.0 ) else: cpu_target.target.next_to(cpu_targs[i - 1].target , direction=_a , buff=0.0 ) cpu_targs.append(_a ) first_animations.append(rect.animate(run_time=0.5 ).set_stroke(_a ) ) second_animations.append(MoveToTarget(_a , run_time=1.5 ) ) self.play(*_a ) self.play(*_a ) self.wait()
680
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision.transforms import functional as F from transformers import DetrImageProcessor, TableTransformerConfig, TableTransformerForObjectDetection from transformers.utils import logging logging.set_verbosity_info() a :Any = logging.get_logger(__name__) # here we list all keys to be renamed (original name on the left, our name on the right) a :str = [] for i in range(6): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (f'transformer.encoder.layers.{i}.self_attn.out_proj.weight', f'encoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (f'transformer.encoder.layers.{i}.self_attn.out_proj.bias', f'encoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append((f'transformer.encoder.layers.{i}.linear1.weight', f'encoder.layers.{i}.fc1.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.linear1.bias', f'encoder.layers.{i}.fc1.bias')) rename_keys.append((f'transformer.encoder.layers.{i}.linear2.weight', f'encoder.layers.{i}.fc2.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.linear2.bias', f'encoder.layers.{i}.fc2.bias')) rename_keys.append( (f'transformer.encoder.layers.{i}.norm1.weight', f'encoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((f'transformer.encoder.layers.{i}.norm1.bias', f'encoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append((f'transformer.encoder.layers.{i}.norm2.weight', f'encoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.norm2.bias', f'encoder.layers.{i}.final_layer_norm.bias')) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( (f'transformer.decoder.layers.{i}.self_attn.out_proj.weight', f'decoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (f'transformer.decoder.layers.{i}.self_attn.out_proj.bias', f'decoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append( ( f'transformer.decoder.layers.{i}.multihead_attn.out_proj.weight', f'decoder.layers.{i}.encoder_attn.out_proj.weight', ) ) rename_keys.append( ( f'transformer.decoder.layers.{i}.multihead_attn.out_proj.bias', f'decoder.layers.{i}.encoder_attn.out_proj.bias', ) ) rename_keys.append((f'transformer.decoder.layers.{i}.linear1.weight', f'decoder.layers.{i}.fc1.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.linear1.bias', f'decoder.layers.{i}.fc1.bias')) rename_keys.append((f'transformer.decoder.layers.{i}.linear2.weight', f'decoder.layers.{i}.fc2.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.linear2.bias', f'decoder.layers.{i}.fc2.bias')) rename_keys.append( (f'transformer.decoder.layers.{i}.norm1.weight', f'decoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((f'transformer.decoder.layers.{i}.norm1.bias', f'decoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append( (f'transformer.decoder.layers.{i}.norm2.weight', f'decoder.layers.{i}.encoder_attn_layer_norm.weight') ) rename_keys.append( (f'transformer.decoder.layers.{i}.norm2.bias', f'decoder.layers.{i}.encoder_attn_layer_norm.bias') ) rename_keys.append((f'transformer.decoder.layers.{i}.norm3.weight', f'decoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.norm3.bias', f'decoder.layers.{i}.final_layer_norm.bias')) # convolutional projection + query embeddings + layernorm of encoder + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ("input_proj.weight", "input_projection.weight"), ("input_proj.bias", "input_projection.bias"), ("query_embed.weight", "query_position_embeddings.weight"), ("transformer.encoder.norm.weight", "encoder.layernorm.weight"), ("transformer.encoder.norm.bias", "encoder.layernorm.bias"), ("transformer.decoder.norm.weight", "decoder.layernorm.weight"), ("transformer.decoder.norm.bias", "decoder.layernorm.bias"), ("class_embed.weight", "class_labels_classifier.weight"), ("class_embed.bias", "class_labels_classifier.bias"), ("bbox_embed.layers.0.weight", "bbox_predictor.layers.0.weight"), ("bbox_embed.layers.0.bias", "bbox_predictor.layers.0.bias"), ("bbox_embed.layers.1.weight", "bbox_predictor.layers.1.weight"), ("bbox_embed.layers.1.bias", "bbox_predictor.layers.1.bias"), ("bbox_embed.layers.2.weight", "bbox_predictor.layers.2.weight"), ("bbox_embed.layers.2.bias", "bbox_predictor.layers.2.bias"), ] ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Tuple = state_dict.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = val def _lowercase ( __lowerCAmelCase ) -> Tuple: SCREAMING_SNAKE_CASE__ : str = OrderedDict() for key, value in state_dict.items(): if "backbone.0.body" in key: SCREAMING_SNAKE_CASE__ : List[Any] = key.replace("""backbone.0.body""" , """backbone.conv_encoder.model""" ) SCREAMING_SNAKE_CASE__ : Dict = value else: SCREAMING_SNAKE_CASE__ : Tuple = value return new_state_dict def _lowercase ( __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : str = """""" # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : int = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : int = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE__ : Any = in_proj_bias[:256] SCREAMING_SNAKE_CASE__ : Dict = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[256:512] SCREAMING_SNAKE_CASE__ : int = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[-256:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6 ): # read in weights + bias of input projection layer of self-attention SCREAMING_SNAKE_CASE__ : List[str] = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : Tuple = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Any = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[:256] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[256:512] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias[-256:] # read in weights + bias of input projection layer of cross-attention SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop( F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : List[Any] = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) of cross-attention to the state dict SCREAMING_SNAKE_CASE__ : int = in_proj_weight_cross_attn[:256, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias_cross_attn[:256] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight_cross_attn[256:512, :] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_bias_cross_attn[256:512] SCREAMING_SNAKE_CASE__ : int = in_proj_weight_cross_attn[-256:, :] SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias_cross_attn[-256:] def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = image.size SCREAMING_SNAKE_CASE__ : Optional[Any] = max(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = 800 if """detection""" in checkpoint_url else 1000 SCREAMING_SNAKE_CASE__ : List[str] = target_max_size / current_max_size SCREAMING_SNAKE_CASE__ : str = image.resize((int(round(scale * width ) ), int(round(scale * height ) )) ) return resized_image def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[int] = F.to_tensor(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = F.normalize(__lowerCAmelCase , mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ) return image @torch.no_grad() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Optional[Any]: logger.info("""Converting model...""" ) # load original state dict SCREAMING_SNAKE_CASE__ : str = torch.hub.load_state_dict_from_url(__lowerCAmelCase , map_location="""cpu""" ) # rename keys for src, dest in rename_keys: rename_key(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = rename_backbone_keys(__lowerCAmelCase ) # query, key and value matrices need special treatment read_in_q_k_v(__lowerCAmelCase ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them SCREAMING_SNAKE_CASE__ : Optional[int] = """model.""" for key in state_dict.copy().keys(): if not key.startswith("""class_labels_classifier""" ) and not key.startswith("""bbox_predictor""" ): SCREAMING_SNAKE_CASE__ : Optional[int] = state_dict.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = val # create HuggingFace model and load state dict SCREAMING_SNAKE_CASE__ : Tuple = TableTransformerConfig( backbone="""resnet18""" , mask_loss_coefficient=1 , dice_loss_coefficient=1 , ce_loss_coefficient=1 , bbox_loss_coefficient=5 , giou_loss_coefficient=2 , eos_coefficient=0.4 , class_cost=1 , bbox_cost=5 , giou_cost=2 , ) if "detection" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] = 15 SCREAMING_SNAKE_CASE__ : Any = 2 SCREAMING_SNAKE_CASE__ : str = {0: """table""", 1: """table rotated"""} SCREAMING_SNAKE_CASE__ : Union[str, Any] = idalabel SCREAMING_SNAKE_CASE__ : List[str] = {v: k for k, v in idalabel.items()} else: SCREAMING_SNAKE_CASE__ : Tuple = 125 SCREAMING_SNAKE_CASE__ : str = 6 SCREAMING_SNAKE_CASE__ : List[Any] = { 0: """table""", 1: """table column""", 2: """table row""", 3: """table column header""", 4: """table projected row header""", 5: """table spanning cell""", } SCREAMING_SNAKE_CASE__ : Any = idalabel SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Dict = DetrImageProcessor( format="""coco_detection""" , max_size=800 if """detection""" in checkpoint_url else 1000 ) SCREAMING_SNAKE_CASE__ : Tuple = TableTransformerForObjectDetection(__lowerCAmelCase ) model.load_state_dict(__lowerCAmelCase ) model.eval() # verify our conversion SCREAMING_SNAKE_CASE__ : Dict = """example_pdf.png""" if """detection""" in checkpoint_url else """example_table.png""" SCREAMING_SNAKE_CASE__ : Tuple = hf_hub_download(repo_id="""nielsr/example-pdf""" , repo_type="""dataset""" , filename=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = Image.open(__lowerCAmelCase ).convert("""RGB""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = normalize(resize(__lowerCAmelCase , __lowerCAmelCase ) ).unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : Dict = model(__lowerCAmelCase ) if "detection" in checkpoint_url: SCREAMING_SNAKE_CASE__ : List[Any] = (1, 15, 3) SCREAMING_SNAKE_CASE__ : str = torch.tensor( [[-6.7_897, -16.9_985, 6.7_937], [-8.0_186, -22.2_192, 6.9_677], [-7.3_117, -21.0_708, 7.4_055]] ) SCREAMING_SNAKE_CASE__ : str = torch.tensor([[0.4_867, 0.1_767, 0.6_732], [0.6_718, 0.4_479, 0.3_830], [0.4_716, 0.1_760, 0.6_364]] ) else: SCREAMING_SNAKE_CASE__ : Dict = (1, 125, 7) SCREAMING_SNAKE_CASE__ : Any = torch.tensor( [[-18.1_430, -8.3_214, 4.8_274], [-18.4_685, -7.1_361, -4.2_667], [-26.3_693, -9.3_429, -4.9_962]] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([[0.4_983, 0.5_595, 0.9_440], [0.4_916, 0.6_315, 0.5_954], [0.6_108, 0.8_637, 0.1_135]] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(F'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(__lowerCAmelCase ).mkdir(exist_ok=__lowerCAmelCase ) model.save_pretrained(__lowerCAmelCase ) image_processor.save_pretrained(__lowerCAmelCase ) if push_to_hub: # Push model to HF hub logger.info("""Pushing model to the hub...""" ) SCREAMING_SNAKE_CASE__ : List[Any] = ( """microsoft/table-transformer-detection""" if """detection""" in checkpoint_url else """microsoft/table-transformer-structure-recognition""" ) model.push_to_hub(__lowerCAmelCase ) image_processor.push_to_hub(__lowerCAmelCase ) if __name__ == "__main__": a :Any = argparse.ArgumentParser() parser.add_argument( "--checkpoint_url", default="https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth", type=str, choices=[ "https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth", "https://pubtables1m.blob.core.windows.net/model/pubtables1m_structure_detr_r18.pth", ], help="URL of the Table Transformer checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) a :int = parser.parse_args() convert_table_transformer_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
680
1
"""simple docstring""" import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from xgboost import XGBClassifier def _lowercase ( __lowerCAmelCase ) -> tuple: return (data["data"], data["target"]) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> XGBClassifier: SCREAMING_SNAKE_CASE__ : Optional[int] = XGBClassifier() classifier.fit(__lowerCAmelCase , __lowerCAmelCase ) return classifier def _lowercase ( ) -> None: SCREAMING_SNAKE_CASE__ : int = load_iris() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = data_handling(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = train_test_split( __lowerCAmelCase , __lowerCAmelCase , test_size=0.25 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = iris["""target_names"""] # Create an XGBoost Classifier from the training data SCREAMING_SNAKE_CASE__ : Tuple = xgboost(__lowerCAmelCase , __lowerCAmelCase ) # Display the confusion matrix of the classifier with both training and test sets ConfusionMatrixDisplay.from_estimator( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , display_labels=__lowerCAmelCase , cmap="""Blues""" , normalize="""true""" , ) plt.title("""Normalized Confusion Matrix - IRIS Dataset""" ) plt.show() if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
680
"""simple docstring""" from __future__ import annotations import unittest from transformers import 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, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers import ( TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, BertConfig, DPRConfig, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) class __a : '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=2 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , _a=0 , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : str = seq_length SCREAMING_SNAKE_CASE__ : List[str] = is_training SCREAMING_SNAKE_CASE__ : List[str] = use_input_mask SCREAMING_SNAKE_CASE__ : Dict = use_token_type_ids SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE__ : Dict = hidden_size SCREAMING_SNAKE_CASE__ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE__ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : str = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Any = type_vocab_size SCREAMING_SNAKE_CASE__ : int = type_sequence_label_size SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : Any = num_labels SCREAMING_SNAKE_CASE__ : Dict = num_choices SCREAMING_SNAKE_CASE__ : Any = scope SCREAMING_SNAKE_CASE__ : int = projection_dim def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : str = None if self.use_input_mask: # follow test_modeling_tf_ctrl.py SCREAMING_SNAKE_CASE__ : str = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : Any = BertConfig( 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 , ) SCREAMING_SNAKE_CASE__ : str = DPRConfig(projection_dim=self.projection_dim , **config.to_dict() ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRContextEncoder(config=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , attention_mask=_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : str = model(_a ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = TFDPRQuestionEncoder(config=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_a , attention_mask=_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : List[str] = model(_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(_a ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = TFDPRReader(config=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , attention_mask=_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) ) self.parent.assertEqual(result.relevance_logits.shape , (self.batch_size,) ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE__ : int = {"""input_ids""": input_ids} return config, inputs_dict @require_tf class __a (UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = ( ( TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) if is_tf_available() else () ) _SCREAMING_SNAKE_CASE :int = {"""feature-extraction""": TFDPRQuestionEncoder} if is_tf_available() else {} _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = False _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :Dict = False def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFDPRModelTester(self ) SCREAMING_SNAKE_CASE__ : List[str] = ConfigTester(self , config_class=_a , hidden_size=37 ) def _a ( self ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_context_encoder(*_a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_question_encoder(*_a ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_reader(*_a ) @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRContextEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[int] = TFDPRContextEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = TFDPRQuestionEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRReader.from_pretrained(_a ) self.assertIsNotNone(_a ) @require_tf class __a (unittest.TestCase): '''simple docstring''' @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFDPRQuestionEncoder.from_pretrained("""facebook/dpr-question_encoder-single-nq-base""" ) SCREAMING_SNAKE_CASE__ : List[Any] = tf.constant( [[101, 7_592, 1_010, 2_003, 2_026, 3_899, 10_140, 1_029, 102]] ) # [CLS] hello, is my dog cute? [SEP] SCREAMING_SNAKE_CASE__ : Tuple = model(_a )[0] # embedding shape = (1, 768) # compare the actual values for a slice. SCREAMING_SNAKE_CASE__ : Any = tf.constant( [ [ 0.03_236_253, 0.12_753_335, 0.16_818_509, 0.00_279_786, 0.3_896_933, 0.24_264_945, 0.2_178_971, -0.02_335_227, -0.08_481_959, -0.14_324_117, ] ] ) self.assertTrue(numpy.allclose(output[:, :10].numpy() , expected_slice.numpy() , atol=1E-4 ) )
680
1
"""simple docstring""" import re import string import numpy as np import datasets a :List[str] = "\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n" a :Optional[Any] = "\nArgs:\n predictions: List of predicted texts.\n references: List of reference texts.\n regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n ignore when calculating the exact matches. Note: these regexes are removed\n from the input data before the changes based on the options below (e.g. ignore_case,\n ignore_punctuation, ignore_numbers) are applied.\n ignore_case: Boolean, defaults to False. If true, turns everything\n to lowercase so that capitalization differences are ignored.\n ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\n ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\nReturns:\n exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results[\"exact_match\"], 1))\n 25.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results[\"exact_match\"], 1))\n 50.0\n\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results[\"exact_match\"], 1))\n 75.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n >>> print(round(results[\"exact_match\"], 1))\n 100.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"The cat sat on the mat.\", \"Theaters are great.\", \"It's like comparing oranges and apples.\"]\n >>> preds = [\"The cat sat on the mat?\", \"Theaters are great.\", \"It's like comparing apples and oranges.\"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results[\"exact_match\"], 1))\n 33.3\n\n" a :Tuple = "\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class __a (datasets.Metric): '''simple docstring''' def _a ( self ) -> 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""" ), } ) , reference_urls=[] , ) def _a ( self , _a , _a , _a=None , _a=False , _a=False , _a=False , ) -> Tuple: """simple docstring""" if regexes_to_ignore is not None: for s in regexes_to_ignore: SCREAMING_SNAKE_CASE__ : Optional[int] = np.array([re.sub(_a , """""" , _a ) for x in predictions] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([re.sub(_a , """""" , _a ) for x in references] ) else: SCREAMING_SNAKE_CASE__ : str = np.asarray(_a ) SCREAMING_SNAKE_CASE__ : str = np.asarray(_a ) if ignore_case: SCREAMING_SNAKE_CASE__ : Optional[int] = np.char.lower(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.char.lower(_a ) if ignore_punctuation: SCREAMING_SNAKE_CASE__ : Optional[int] = string.punctuation.maketrans("""""" , """""" , string.punctuation ) SCREAMING_SNAKE_CASE__ : Any = np.char.translate(_a , table=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = np.char.translate(_a , table=_a ) if ignore_numbers: SCREAMING_SNAKE_CASE__ : List[Any] = string.digits.maketrans("""""" , """""" , string.digits ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.char.translate(_a , table=_a ) SCREAMING_SNAKE_CASE__ : List[str] = np.char.translate(_a , table=_a ) SCREAMING_SNAKE_CASE__ : Any = predictions == references return {"exact_match": np.mean(_a ) * 100}
680
"""simple docstring""" # DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion # and https://github.com/hojonathanho/diffusion import math from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.schedulers.scheduling_utils import SchedulerMixin from diffusers.utils import BaseOutput, deprecate @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :torch.FloatTensor _SCREAMING_SNAKE_CASE :Optional[torch.FloatTensor] = None def _lowercase ( __lowerCAmelCase , __lowerCAmelCase=0.999 , __lowerCAmelCase="cosine" , ) -> Union[str, Any]: if alpha_transform_type == "cosine": def alpha_bar_fn(__lowerCAmelCase ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(__lowerCAmelCase ): return math.exp(t * -12.0 ) else: raise ValueError(F'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) SCREAMING_SNAKE_CASE__ : List[Any] = [] for i in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = i / num_diffusion_timesteps SCREAMING_SNAKE_CASE__ : int = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(__lowerCAmelCase ) / alpha_bar_fn(__lowerCAmelCase ) , __lowerCAmelCase ) ) return torch.tensor(__lowerCAmelCase , dtype=torch.floataa ) class __a (UpperCamelCase_ , UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = 1 @register_to_config def __init__( self , _a = 1_000 , _a = 0.0_001 , _a = 0.02 , _a = "linear" , _a = None , _a = True , _a = True , _a = 0 , _a = "epsilon" , _a = 1.0 , **_a , ) -> Dict: """simple docstring""" if kwargs.get("""set_alpha_to_one""" , _a ) is not None: SCREAMING_SNAKE_CASE__ : Tuple = ( """The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead.""" ) deprecate("""set_alpha_to_one""" , """1.0.0""" , _a , standard_warn=_a ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs["""set_alpha_to_one"""] if trained_betas is not None: SCREAMING_SNAKE_CASE__ : Dict = torch.tensor(_a , dtype=torch.floataa ) elif beta_schedule == "linear": SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.linspace(_a , _a , _a , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. SCREAMING_SNAKE_CASE__ : Optional[int] = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , _a , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule SCREAMING_SNAKE_CASE__ : Tuple = betas_for_alpha_bar(_a ) else: raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = 1.0 - self.betas SCREAMING_SNAKE_CASE__ : List[Any] = torch.cumprod(self.alphas , dim=0 ) # At every step in inverted ddim, we are looking into the next alphas_cumprod # For the final step, there is no next alphas_cumprod, and the index is out of bounds # `set_alpha_to_zero` decides whether we set this parameter simply to zero # in this case, self.step() just output the predicted noise # or whether we use the final alpha of the "non-previous" one. SCREAMING_SNAKE_CASE__ : Any = torch.tensor(0.0 ) if set_alpha_to_zero else self.alphas_cumprod[-1] # standard deviation of the initial noise distribution SCREAMING_SNAKE_CASE__ : Tuple = 1.0 # setable values SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : List[str] = torch.from_numpy(np.arange(0 , _a ).copy().astype(np.intaa ) ) def _a ( self , _a , _a = None ) -> torch.FloatTensor: """simple docstring""" return sample def _a ( self , _a , _a = None ) -> Optional[int]: """simple docstring""" if num_inference_steps > self.config.num_train_timesteps: raise ValueError( f'''`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:''' f''' {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle''' f''' maximal {self.config.num_train_timesteps} timesteps.''' ) SCREAMING_SNAKE_CASE__ : List[str] = num_inference_steps SCREAMING_SNAKE_CASE__ : Optional[Any] = self.config.num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 SCREAMING_SNAKE_CASE__ : str = (np.arange(0 , _a ) * step_ratio).round().copy().astype(np.intaa ) SCREAMING_SNAKE_CASE__ : Tuple = torch.from_numpy(_a ).to(_a ) self.timesteps += self.config.steps_offset def _a ( self , _a , _a , _a , _a = 0.0 , _a = False , _a = None , _a = True , ) -> Union[DDIMSchedulerOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = timestep + self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas # change original implementation to exactly match noise levels for analogous forward process SCREAMING_SNAKE_CASE__ : Optional[int] = self.alphas_cumprod[timestep] SCREAMING_SNAKE_CASE__ : Optional[int] = ( self.alphas_cumprod[prev_timestep] if prev_timestep < self.config.num_train_timesteps else self.final_alpha_cumprod ) SCREAMING_SNAKE_CASE__ : Any = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf if self.config.prediction_type == "epsilon": SCREAMING_SNAKE_CASE__ : int = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 SCREAMING_SNAKE_CASE__ : List[Any] = model_output elif self.config.prediction_type == "sample": SCREAMING_SNAKE_CASE__ : Dict = model_output SCREAMING_SNAKE_CASE__ : int = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 elif self.config.prediction_type == "v_prediction": SCREAMING_SNAKE_CASE__ : Dict = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output SCREAMING_SNAKE_CASE__ : str = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or''' """ `v_prediction`""" ) # 4. Clip or threshold "predicted x_0" if self.config.clip_sample: SCREAMING_SNAKE_CASE__ : Tuple = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : Any = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : Dict = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if not return_dict: return (prev_sample, pred_original_sample) return DDIMSchedulerOutput(prev_sample=_a , pred_original_sample=_a ) def __len__( self ) -> Dict: """simple docstring""" return self.config.num_train_timesteps
680
1
"""simple docstring""" from __future__ import annotations import unittest from transformers import 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, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers import ( TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, BertConfig, DPRConfig, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) class __a : '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=2 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , _a=0 , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : str = seq_length SCREAMING_SNAKE_CASE__ : List[str] = is_training SCREAMING_SNAKE_CASE__ : List[str] = use_input_mask SCREAMING_SNAKE_CASE__ : Dict = use_token_type_ids SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE__ : Dict = hidden_size SCREAMING_SNAKE_CASE__ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE__ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : str = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Any = type_vocab_size SCREAMING_SNAKE_CASE__ : int = type_sequence_label_size SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : Any = num_labels SCREAMING_SNAKE_CASE__ : Dict = num_choices SCREAMING_SNAKE_CASE__ : Any = scope SCREAMING_SNAKE_CASE__ : int = projection_dim def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : str = None if self.use_input_mask: # follow test_modeling_tf_ctrl.py SCREAMING_SNAKE_CASE__ : str = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : Any = BertConfig( 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 , ) SCREAMING_SNAKE_CASE__ : str = DPRConfig(projection_dim=self.projection_dim , **config.to_dict() ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRContextEncoder(config=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , attention_mask=_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : str = model(_a ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = TFDPRQuestionEncoder(config=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_a , attention_mask=_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : List[str] = model(_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(_a ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = TFDPRReader(config=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , attention_mask=_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) ) self.parent.assertEqual(result.relevance_logits.shape , (self.batch_size,) ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE__ : int = {"""input_ids""": input_ids} return config, inputs_dict @require_tf class __a (UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = ( ( TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) if is_tf_available() else () ) _SCREAMING_SNAKE_CASE :int = {"""feature-extraction""": TFDPRQuestionEncoder} if is_tf_available() else {} _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = False _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :Dict = False def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFDPRModelTester(self ) SCREAMING_SNAKE_CASE__ : List[str] = ConfigTester(self , config_class=_a , hidden_size=37 ) def _a ( self ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_context_encoder(*_a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_question_encoder(*_a ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_reader(*_a ) @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRContextEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[int] = TFDPRContextEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = TFDPRQuestionEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRReader.from_pretrained(_a ) self.assertIsNotNone(_a ) @require_tf class __a (unittest.TestCase): '''simple docstring''' @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFDPRQuestionEncoder.from_pretrained("""facebook/dpr-question_encoder-single-nq-base""" ) SCREAMING_SNAKE_CASE__ : List[Any] = tf.constant( [[101, 7_592, 1_010, 2_003, 2_026, 3_899, 10_140, 1_029, 102]] ) # [CLS] hello, is my dog cute? [SEP] SCREAMING_SNAKE_CASE__ : Tuple = model(_a )[0] # embedding shape = (1, 768) # compare the actual values for a slice. SCREAMING_SNAKE_CASE__ : Any = tf.constant( [ [ 0.03_236_253, 0.12_753_335, 0.16_818_509, 0.00_279_786, 0.3_896_933, 0.24_264_945, 0.2_178_971, -0.02_335_227, -0.08_481_959, -0.14_324_117, ] ] ) self.assertTrue(numpy.allclose(output[:, :10].numpy() , expected_slice.numpy() , atol=1E-4 ) )
680
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) a :Union[str, Any] = { "configuration_speecht5": [ "SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP", "SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP", "SpeechT5Config", "SpeechT5HifiGanConfig", ], "feature_extraction_speecht5": ["SpeechT5FeatureExtractor"], "processing_speecht5": ["SpeechT5Processor"], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = ["SpeechT5Tokenizer"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST", "SpeechT5ForSpeechToText", "SpeechT5ForSpeechToSpeech", "SpeechT5ForTextToSpeech", "SpeechT5Model", "SpeechT5PreTrainedModel", "SpeechT5HifiGan", ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys a :Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
1
"""simple docstring""" import numpy as np import torch from torch.utils.data import Dataset from utils import logger class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , _a , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = params SCREAMING_SNAKE_CASE__ : Dict = np.array(_a ) SCREAMING_SNAKE_CASE__ : Dict = np.array([len(_a ) for t in data] ) self.check() self.remove_long_sequences() self.remove_empty_sequences() self.remove_unknown_sequences() self.check() self.print_statistics() def __getitem__( self , _a ) -> Optional[int]: """simple docstring""" return (self.token_ids[index], self.lengths[index]) def __len__( self ) -> Any: """simple docstring""" return len(self.lengths ) def _a ( self ) -> List[Any]: """simple docstring""" assert len(self.token_ids ) == len(self.lengths ) assert all(self.lengths[i] == len(self.token_ids[i] ) for i in range(len(self.lengths ) ) ) def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.params.max_model_input_size SCREAMING_SNAKE_CASE__ : int = self.lengths > max_len logger.info(f'''Splitting {sum(_a )} too long sequences.''' ) def divide_chunks(_a , _a ): return [l[i : i + n] for i in range(0 , len(_a ) , _a )] SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] if self.params.mlm: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.params.special_tok_ids["""cls_token"""], self.params.special_tok_ids["""sep_token"""] else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = self.params.special_tok_ids["""bos_token"""], self.params.special_tok_ids["""eos_token"""] for seq_, len_ in zip(self.token_ids , self.lengths ): assert (seq_[0] == cls_id) and (seq_[-1] == sep_id), seq_ if len_ <= max_len: new_tok_ids.append(seq_ ) new_lengths.append(len_ ) else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] for sub_s in divide_chunks(seq_ , max_len - 2 ): if sub_s[0] != cls_id: SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.insert(_a , 0 , _a ) if sub_s[-1] != sep_id: SCREAMING_SNAKE_CASE__ : Dict = np.insert(_a , len(_a ) , _a ) assert len(_a ) <= max_len assert (sub_s[0] == cls_id) and (sub_s[-1] == sep_id), sub_s sub_seqs.append(_a ) new_tok_ids.extend(_a ) new_lengths.extend([len(_a ) for l in sub_seqs] ) SCREAMING_SNAKE_CASE__ : int = np.array(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array(_a ) def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = len(self ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.lengths > 11 SCREAMING_SNAKE_CASE__ : List[str] = self.token_ids[indices] SCREAMING_SNAKE_CASE__ : Tuple = self.lengths[indices] SCREAMING_SNAKE_CASE__ : Tuple = len(self ) logger.info(f'''Remove {init_size - new_size} too short (<=11 tokens) sequences.''' ) def _a ( self ) -> Union[str, Any]: """simple docstring""" if "unk_token" not in self.params.special_tok_ids: return else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.params.special_tok_ids["""unk_token"""] SCREAMING_SNAKE_CASE__ : str = len(self ) SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([np.count_nonzero(a == unk_token_id ) for a in self.token_ids] ) SCREAMING_SNAKE_CASE__ : List[Any] = (unk_occs / self.lengths) < 0.5 SCREAMING_SNAKE_CASE__ : Dict = self.token_ids[indices] SCREAMING_SNAKE_CASE__ : List[str] = self.lengths[indices] SCREAMING_SNAKE_CASE__ : int = len(self ) logger.info(f'''Remove {init_size - new_size} sequences with a high level of unknown tokens (50%).''' ) def _a ( self ) -> Optional[Any]: """simple docstring""" if not self.params.is_master: return logger.info(f'''{len(self )} sequences''' ) # data_len = sum(self.lengths) # nb_unique_tokens = len(Counter(list(chain(*self.token_ids)))) # logger.info(f'{data_len} tokens ({nb_unique_tokens} unique)') # unk_idx = self.params.special_tok_ids['unk_token'] # nb_unknown = sum([(t==unk_idx).sum() for t in self.token_ids]) # logger.info(f'{nb_unknown} unknown tokens (covering {100*nb_unknown/data_len:.2f}% of the data)') def _a ( self , _a ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = [t[0] for t in batch] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [t[1] for t in batch] assert len(_a ) == len(_a ) # Max for paddings SCREAMING_SNAKE_CASE__ : Union[str, Any] = max(_a ) # Pad token ids if self.params.mlm: SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.params.special_tok_ids["""pad_token"""] else: SCREAMING_SNAKE_CASE__ : int = self.params.special_tok_ids["""unk_token"""] SCREAMING_SNAKE_CASE__ : List[Any] = [list(t.astype(_a ) ) + [pad_idx] * (max_seq_len_ - len(_a )) for t in token_ids] assert len(tk_ ) == len(_a ) assert all(len(_a ) == max_seq_len_ for t in tk_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor(tk_ ) # (bs, max_seq_len_) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor(_a ) # (bs) return tk_t, lg_t
680
"""simple docstring""" import math import os import sys def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Union[str, Any] = """""" try: with open(__lowerCAmelCase , """rb""" ) as binary_file: SCREAMING_SNAKE_CASE__ : Optional[int] = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Dict = F'''{dat:08b}''' result += curr_byte return result except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> None: lexicon.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = last_match_id if math.loga(__lowerCAmelCase ).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE__ : Dict = """0""" + lexicon[curr_key] SCREAMING_SNAKE_CASE__ : str = bin(__lowerCAmelCase )[2:] def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Dict = {"""0""": """0""", """1""": """1"""} SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = """""", """""" SCREAMING_SNAKE_CASE__ : Any = len(__lowerCAmelCase ) for i in range(len(__lowerCAmelCase ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon[curr_string] result += last_match_id add_key_to_lexicon(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) index += 1 SCREAMING_SNAKE_CASE__ : List[str] = """""" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE__ : List[Any] = lexicon[curr_string] result += last_match_id return result def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Any = os.path.getsize(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = bin(__lowerCAmelCase )[2:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = len(__lowerCAmelCase ) return "0" * (length_length - 1) + file_length_binary + compressed def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Optional[int] = 8 try: with open(__lowerCAmelCase , """wb""" ) as opened_file: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ to_write[i : i + byte_length] for i in range(0 , len(__lowerCAmelCase ) , __lowerCAmelCase ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("""10000000""" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(__lowerCAmelCase , 2 ).to_bytes(1 , byteorder="""big""" ) ) except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Dict = read_file_binary(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = compress_data(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = add_file_length(__lowerCAmelCase , __lowerCAmelCase ) write_file_binary(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
680
1
"""simple docstring""" import functools from typing import Any def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> bool: # Validation if not isinstance(__lowerCAmelCase , __lowerCAmelCase ) or len(__lowerCAmelCase ) == 0: raise ValueError("""the string should be not empty string""" ) if not isinstance(__lowerCAmelCase , __lowerCAmelCase ) or not all( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and len(__lowerCAmelCase ) > 0 for item in words ): raise ValueError("""the words should be a list of non-empty strings""" ) # Build trie SCREAMING_SNAKE_CASE__ : dict[str, Any] = {} SCREAMING_SNAKE_CASE__ : Optional[Any] = """WORD_KEEPER""" for word in words: SCREAMING_SNAKE_CASE__ : Tuple = trie for c in word: if c not in trie_node: SCREAMING_SNAKE_CASE__ : str = {} SCREAMING_SNAKE_CASE__ : Optional[int] = trie_node[c] SCREAMING_SNAKE_CASE__ : Dict = True SCREAMING_SNAKE_CASE__ : List[Any] = len(__lowerCAmelCase ) # Dynamic programming method @functools.cache def is_breakable(__lowerCAmelCase ) -> bool: if index == len_string: return True SCREAMING_SNAKE_CASE__ : str = trie for i in range(__lowerCAmelCase , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Optional[int] = trie_node.get(string[i] , __lowerCAmelCase ) if trie_node is None: return False if trie_node.get(__lowerCAmelCase , __lowerCAmelCase ) and is_breakable(i + 1 ): return True return False return is_breakable(0 ) if __name__ == "__main__": import doctest doctest.testmod()
680
"""simple docstring""" import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Tuple = SamImageProcessor() SCREAMING_SNAKE_CASE__ : List[str] = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> Union[str, Any]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> Tuple: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Tuple = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Dict = processor(images=_a , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_torch def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [torch.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : str = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : List[Any] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : Any = processor.post_process_masks(_a , _a , _a ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Dict = processor.post_process_masks( _a , torch.tensor(_a ) , torch.tensor(_a ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np SCREAMING_SNAKE_CASE__ : Dict = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks(_a , np.array(_a ) , np.array(_a ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Dict = [[1, 0], [0, 1]] with self.assertRaises(_a ): SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks(_a , np.array(_a ) , np.array(_a ) ) @require_vision @require_tf class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Optional[int] = SamImageProcessor() SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> List[str]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> int: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Any = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : int = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Tuple = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Any = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Any = processor(images=_a , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_tf def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Union[str, Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [tf.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Optional[int] = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks(_a , _a , _a , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks( _a , tf.convert_to_tensor(_a ) , tf.convert_to_tensor(_a ) , return_tensors="""tf""" , ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np SCREAMING_SNAKE_CASE__ : Optional[int] = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks( _a , np.array(_a ) , np.array(_a ) , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Any = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): SCREAMING_SNAKE_CASE__ : str = processor.post_process_masks( _a , np.array(_a ) , np.array(_a ) , return_tensors="""tf""" ) @require_vision @require_torchvision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Dict = SamImageProcessor() SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> Any: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> Union[str, Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : int = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : List[Any] = [tf.convert_to_tensor(_a )] SCREAMING_SNAKE_CASE__ : Dict = [torch.tensor(_a )] SCREAMING_SNAKE_CASE__ : Optional[int] = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : List[str] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : List[Any] = processor.post_process_masks( _a , _a , _a , return_tensors="""tf""" ) SCREAMING_SNAKE_CASE__ : List[str] = processor.post_process_masks( _a , _a , _a , return_tensors="""pt""" ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : str = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : int = image_processor(_a , return_tensors="""pt""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : Any = processor(images=_a , return_tensors="""pt""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor(_a , return_tensors="""tf""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : str = processor(images=_a , return_tensors="""tf""" )["""pixel_values"""].numpy() self.assertTrue(np.allclose(_a , _a ) ) self.assertTrue(np.allclose(_a , _a ) ) self.assertTrue(np.allclose(_a , _a ) )
680
1
"""simple docstring""" from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional from packaging import version if TYPE_CHECKING: from ... import PreTrainedTokenizer, TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import is_torch_available, logging a :int = logging.get_logger(__name__) a :List[Any] = { "bigscience/bloom": "https://huggingface.co/bigscience/bloom/resolve/main/config.json", "bigscience/bloom-560m": "https://huggingface.co/bigscience/bloom-560m/blob/main/config.json", "bigscience/bloom-1b1": "https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json", "bigscience/bloom-1b7": "https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json", "bigscience/bloom-3b": "https://huggingface.co/bigscience/bloom-3b/blob/main/config.json", "bigscience/bloom-7b1": "https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json", } class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Dict = """bloom""" _SCREAMING_SNAKE_CASE :Optional[Any] = ["""past_key_values"""] _SCREAMING_SNAKE_CASE :Union[str, Any] = { """num_hidden_layers""": """n_layer""", """num_attention_heads""": """n_head""", } def __init__( self , _a=250_880 , _a=64 , _a=2 , _a=8 , _a=1E-5 , _a=0.02 , _a=True , _a=1 , _a=2 , _a=False , _a=0.0 , _a=0.0 , _a=1 , _a=False , **_a , ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = vocab_size # Backward compatibility with n_embed kwarg SCREAMING_SNAKE_CASE__ : Union[str, Any] = kwargs.pop("""n_embed""" , _a ) SCREAMING_SNAKE_CASE__ : Tuple = hidden_size if n_embed is None else n_embed SCREAMING_SNAKE_CASE__ : Optional[Any] = n_layer SCREAMING_SNAKE_CASE__ : Any = n_head SCREAMING_SNAKE_CASE__ : List[Any] = layer_norm_epsilon SCREAMING_SNAKE_CASE__ : List[Any] = initializer_range SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_cache SCREAMING_SNAKE_CASE__ : Optional[Any] = pretraining_tp SCREAMING_SNAKE_CASE__ : List[str] = apply_residual_connection_post_layernorm SCREAMING_SNAKE_CASE__ : List[Any] = hidden_dropout SCREAMING_SNAKE_CASE__ : List[Any] = attention_dropout SCREAMING_SNAKE_CASE__ : Optional[int] = bos_token_id SCREAMING_SNAKE_CASE__ : Union[str, Any] = eos_token_id SCREAMING_SNAKE_CASE__ : List[str] = slow_but_exact super().__init__(bos_token_id=_a , eos_token_id=_a , **_a ) class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = version.parse("""1.12""") def __init__( self , _a , _a = "default" , _a = None , _a = False , ) -> Tuple: """simple docstring""" super().__init__(_a , task=_a , patching_specs=_a , use_past=_a ) if not getattr(self._config , """pad_token_id""" , _a ): # TODO: how to do that better? SCREAMING_SNAKE_CASE__ : List[Any] = 0 @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}} ) if self.use_past: # BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344 self.fill_with_past_key_values_(_a , direction="""inputs""" , inverted_values_shape=_a ) SCREAMING_SNAKE_CASE__ : List[str] = {0: """batch""", 1: """past_sequence + sequence"""} else: SCREAMING_SNAKE_CASE__ : Dict = {0: """batch""", 1: """sequence"""} return common_inputs @property def _a ( self ) -> int: """simple docstring""" return self._config.n_layer @property def _a ( self ) -> int: """simple docstring""" return self._config.n_head @property def _a ( self ) -> float: """simple docstring""" return 1E-3 def _a ( self , _a , _a = -1 , _a = -1 , _a = False , _a = None , ) -> Mapping[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = super(_a , self ).generate_dummy_inputs( _a , batch_size=_a , seq_length=_a , is_pair=_a , framework=_a ) # We need to order the input in the way they appears in the forward() SCREAMING_SNAKE_CASE__ : Optional[int] = OrderedDict({"""input_ids""": common_inputs["""input_ids"""]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = common_inputs["""input_ids"""].shape # Not using the same length for past_key_values SCREAMING_SNAKE_CASE__ : Tuple = seqlen + 2 SCREAMING_SNAKE_CASE__ : str = self._config.hidden_size // self.num_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] = ( batch * self.num_attention_heads, head_dim, past_key_values_length, ) SCREAMING_SNAKE_CASE__ : List[Any] = ( batch * self.num_attention_heads, past_key_values_length, head_dim, ) SCREAMING_SNAKE_CASE__ : Tuple = [ (torch.zeros(_a ), torch.zeros(_a )) for _ in range(self.num_layers ) ] SCREAMING_SNAKE_CASE__ : Union[str, Any] = common_inputs["""attention_mask"""] if self.use_past: SCREAMING_SNAKE_CASE__ : Tuple = ordered_inputs["""attention_mask"""].dtype SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat( [ordered_inputs["""attention_mask"""], torch.ones(_a , _a , dtype=_a )] , dim=1 ) return ordered_inputs @property def _a ( self ) -> int: """simple docstring""" return 13
680
"""simple docstring""" import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __a (UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = LayoutLMTokenizer _SCREAMING_SNAKE_CASE :Optional[int] = LayoutLMTokenizerFast _SCREAMING_SNAKE_CASE :str = True _SCREAMING_SNAKE_CASE :Optional[int] = True def _a ( self ) -> Tuple: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : List[str] = [ """[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] SCREAMING_SNAKE_CASE__ : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def _a ( self , **_a ) -> Optional[int]: """simple docstring""" return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **_a ) def _a ( self , _a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = """UNwant\u00E9d,running""" SCREAMING_SNAKE_CASE__ : Optional[Any] = """unwanted, running""" return input_text, output_text def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(_a , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_a ) , [7, 4, 5, 10, 8, 9] ) def _a ( self ) -> Optional[int]: """simple docstring""" pass
680
1
"""simple docstring""" import argparse import glob import logging import os import time from argparse import Namespace import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from torch.utils.data import DataLoader, TensorDataset from transformers import glue_compute_metrics as compute_metrics from transformers import glue_convert_examples_to_features as convert_examples_to_features from transformers import glue_output_modes, glue_tasks_num_labels from transformers import glue_processors as processors a :Union[str, Any] = logging.getLogger(__name__) class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = """sequence-classification""" def __init__( self , _a ) -> str: """simple docstring""" if type(_a ) == dict: SCREAMING_SNAKE_CASE__ : Dict = Namespace(**_a ) SCREAMING_SNAKE_CASE__ : Dict = glue_output_modes[hparams.task] SCREAMING_SNAKE_CASE__ : Optional[Any] = glue_tasks_num_labels[hparams.task] super().__init__(_a , _a , self.mode ) def _a ( self , **_a ) -> str: """simple docstring""" return self.model(**_a ) def _a ( self , _a , _a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = {"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]} if self.config.model_type not in ["distilbert", "bart"]: SCREAMING_SNAKE_CASE__ : Any = batch[2] if self.config.model_type in ["""bert""", """xlnet""", """albert"""] else None SCREAMING_SNAKE_CASE__ : int = self(**_a ) SCREAMING_SNAKE_CASE__ : str = outputs[0] SCREAMING_SNAKE_CASE__ : Dict = self.trainer.lr_schedulers[0]["""scheduler"""] SCREAMING_SNAKE_CASE__ : int = {"""loss""": loss, """rate""": lr_scheduler.get_last_lr()[-1]} return {"loss": loss, "log": tensorboard_logs} def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.hparams SCREAMING_SNAKE_CASE__ : Optional[int] = processors[args.task]() SCREAMING_SNAKE_CASE__ : Dict = processor.get_labels() for mode in ["train", "dev"]: SCREAMING_SNAKE_CASE__ : Tuple = self._feature_file(_a ) if os.path.exists(_a ) and not args.overwrite_cache: logger.info("""Loading features from cached file %s""" , _a ) else: logger.info("""Creating features from dataset file at %s""" , args.data_dir ) SCREAMING_SNAKE_CASE__ : Dict = ( processor.get_dev_examples(args.data_dir ) if mode == """dev""" else processor.get_train_examples(args.data_dir ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = convert_examples_to_features( _a , self.tokenizer , max_length=args.max_seq_length , label_list=self.labels , output_mode=args.glue_output_mode , ) logger.info("""Saving features into cached file %s""" , _a ) torch.save(_a , _a ) def _a ( self , _a , _a , _a = False ) -> DataLoader: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = """dev""" if mode == """test""" else mode SCREAMING_SNAKE_CASE__ : Tuple = self._feature_file(_a ) logger.info("""Loading features from cached file %s""" , _a ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.load(_a ) SCREAMING_SNAKE_CASE__ : str = torch.tensor([f.input_ids for f in features] , dtype=torch.long ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([f.attention_mask for f in features] , dtype=torch.long ) SCREAMING_SNAKE_CASE__ : str = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long ) if self.hparams.glue_output_mode == "classification": SCREAMING_SNAKE_CASE__ : Dict = torch.tensor([f.label for f in features] , dtype=torch.long ) elif self.hparams.glue_output_mode == "regression": SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor([f.label for f in features] , dtype=torch.float ) return DataLoader( TensorDataset(_a , _a , _a , _a ) , batch_size=_a , shuffle=_a , ) def _a ( self , _a , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = {"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]} if self.config.model_type not in ["distilbert", "bart"]: SCREAMING_SNAKE_CASE__ : Tuple = batch[2] if self.config.model_type in ["""bert""", """xlnet""", """albert"""] else None SCREAMING_SNAKE_CASE__ : Dict = self(**_a ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = outputs[:2] SCREAMING_SNAKE_CASE__ : Optional[Any] = logits.detach().cpu().numpy() SCREAMING_SNAKE_CASE__ : List[Any] = inputs["""labels"""].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def _a ( self , _a ) -> tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = torch.stack([x["""val_loss"""] for x in outputs] ).mean().detach().cpu().item() SCREAMING_SNAKE_CASE__ : int = np.concatenate([x["""pred"""] for x in outputs] , axis=0 ) if self.hparams.glue_output_mode == "classification": SCREAMING_SNAKE_CASE__ : Optional[Any] = np.argmax(_a , axis=1 ) elif self.hparams.glue_output_mode == "regression": SCREAMING_SNAKE_CASE__ : str = np.squeeze(_a ) SCREAMING_SNAKE_CASE__ : Dict = np.concatenate([x["""target"""] for x in outputs] , axis=0 ) SCREAMING_SNAKE_CASE__ : Tuple = [[] for _ in range(out_label_ids.shape[0] )] SCREAMING_SNAKE_CASE__ : str = [[] for _ in range(out_label_ids.shape[0] )] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {**{"""val_loss""": val_loss_mean}, **compute_metrics(self.hparams.task , _a , _a )} SCREAMING_SNAKE_CASE__ : int = dict(results.items() ) SCREAMING_SNAKE_CASE__ : str = results return ret, preds_list, out_label_list def _a ( self , _a ) -> dict: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = self._eval_end(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ret["""log"""] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def _a ( self , _a ) -> dict: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = self._eval_end(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ret["""log"""] # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss` return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs} @staticmethod def _a ( _a , _a ) -> Tuple: """simple docstring""" BaseTransformer.add_model_specific_args(_a , _a ) parser.add_argument( """--max_seq_length""" , default=128 , type=_a , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument( """--task""" , default="""""" , type=_a , required=_a , help="""The GLUE task to run""" , ) parser.add_argument( """--gpus""" , default=0 , type=_a , help="""The number of GPUs allocated for this, it is by default 0 meaning none""" , ) parser.add_argument( """--overwrite_cache""" , action="""store_true""" , help="""Overwrite the cached training and evaluation sets""" ) return parser def _lowercase ( ) -> str: SCREAMING_SNAKE_CASE__ : List[str] = argparse.ArgumentParser() add_generic_args(__lowerCAmelCase , os.getcwd() ) SCREAMING_SNAKE_CASE__ : str = GLUETransformer.add_model_specific_args(__lowerCAmelCase , os.getcwd() ) SCREAMING_SNAKE_CASE__ : Optional[int] = parser.parse_args() # If output_dir not provided, a folder will be generated in pwd if args.output_dir is None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.path.join( """./results""" , F'''{args.task}_{time.strftime('%Y%m%d_%H%M%S' )}''' , ) os.makedirs(args.output_dir ) SCREAMING_SNAKE_CASE__ : Any = GLUETransformer(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = generic_train(__lowerCAmelCase , __lowerCAmelCase ) # Optionally, predict on dev set and write to output_dir if args.do_predict: SCREAMING_SNAKE_CASE__ : List[Any] = sorted(glob.glob(os.path.join(args.output_dir , """checkpoint-epoch=*.ckpt""" ) , recursive=__lowerCAmelCase ) ) SCREAMING_SNAKE_CASE__ : int = model.load_from_checkpoint(checkpoints[-1] ) return trainer.test(__lowerCAmelCase ) if __name__ == "__main__": main()
680
"""simple docstring""" import argparse import os import evaluate import torch from datasets import load_dataset 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 # and perform gradient accumulation # # 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 run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a :str = 16 a :Union[str, Any] = 32 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase = 16 ) -> Tuple: SCREAMING_SNAKE_CASE__ : int = AutoTokenizer.from_pretrained("""bert-base-cased""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__lowerCAmelCase ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__lowerCAmelCase , max_length=__lowerCAmelCase ) 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(): SCREAMING_SNAKE_CASE__ : List[str] = datasets.map( __lowerCAmelCase , batched=__lowerCAmelCase , 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 SCREAMING_SNAKE_CASE__ : Any = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__lowerCAmelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE__ : int = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE__ : str = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE__ : Dict = 8 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = None return tokenizer.pad( __lowerCAmelCase , padding="""longest""" , max_length=__lowerCAmelCase , pad_to_multiple_of=__lowerCAmelCase , return_tensors="""pt""" , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE__ : int = DataLoader( tokenized_datasets["""train"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = DataLoader( tokenized_datasets["""validation"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": from accelerate.test_utils.training import mocked_dataloaders a :Dict = mocked_dataloaders # noqa: F811 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , __lowerCAmelCase ) == "1": SCREAMING_SNAKE_CASE__ : Optional[int] = 2 # New Code # SCREAMING_SNAKE_CASE__ : Optional[int] = int(args.gradient_accumulation_steps ) # Initialize accelerator SCREAMING_SNAKE_CASE__ : Optional[Any] = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=__lowerCAmelCase ) if accelerator.distributed_type == DistributedType.TPU and gradient_accumulation_steps > 1: raise NotImplementedError( """Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE__ : Any = config["""lr"""] SCREAMING_SNAKE_CASE__ : str = int(config["""num_epochs"""] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = int(config["""seed"""] ) SCREAMING_SNAKE_CASE__ : List[str] = int(config["""batch_size"""] ) SCREAMING_SNAKE_CASE__ : Any = evaluate.load("""glue""" , """mrpc""" ) set_seed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = get_dataloaders(__lowerCAmelCase , __lowerCAmelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE__ : int = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=__lowerCAmelCase ) # 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). SCREAMING_SNAKE_CASE__ : int = model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE__ : Union[str, Any] = AdamW(params=model.parameters() , lr=__lowerCAmelCase ) # Instantiate scheduler SCREAMING_SNAKE_CASE__ : Any = get_linear_schedule_with_warmup( optimizer=__lowerCAmelCase , num_warmup_steps=100 , num_training_steps=(len(__lowerCAmelCase ) * num_epochs) , ) # 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. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = accelerator.prepare( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Now we train the model for epoch in range(__lowerCAmelCase ): model.train() for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = output.loss accelerator.backward(__lowerCAmelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=__lowerCAmelCase , references=__lowerCAmelCase , ) SCREAMING_SNAKE_CASE__ : List[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , __lowerCAmelCase ) def _lowercase ( ) -> Any: SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=__lowerCAmelCase , default=__lowerCAmelCase , 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.""" , ) # New Code # parser.add_argument( """--gradient_accumulation_steps""" , type=__lowerCAmelCase , default=1 , help="""The number of minibatches to be ran before gradients are accumulated.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : int = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": main()
680
1
"""simple docstring""" def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> str: if not isinstance(__lowerCAmelCase , __lowerCAmelCase ): raise ValueError("""iterations must be defined as integers""" ) if not isinstance(__lowerCAmelCase , __lowerCAmelCase ) or not number >= 1: raise ValueError( """starting number must be and integer and be more than 0""" ) if not iterations >= 1: raise ValueError("""Iterations must be done more than 0 times to play FizzBuzz""" ) SCREAMING_SNAKE_CASE__ : List[Any] = """""" while number <= iterations: if number % 3 == 0: out += "Fizz" if number % 5 == 0: out += "Buzz" if 0 not in (number % 3, number % 5): out += str(__lowerCAmelCase ) # print(out) number += 1 out += " " return out if __name__ == "__main__": import doctest doctest.testmod()
680
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available a :str = { "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST", "ErnieForCausalLM", "ErnieForMaskedLM", "ErnieForMultipleChoice", "ErnieForNextSentencePrediction", "ErnieForPreTraining", "ErnieForQuestionAnswering", "ErnieForSequenceClassification", "ErnieForTokenClassification", "ErnieModel", "ErniePreTrainedModel", ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys a :Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
1
"""simple docstring""" import importlib import shutil import threading import warnings from typing import List import fsspec import fsspec.asyn from . import compression from .hffilesystem import HfFileSystem a :int = importlib.util.find_spec("s3fs") is not None if _has_safs: from .safilesystem import SaFileSystem # noqa: F401 a :List[compression.BaseCompressedFileFileSystem] = [ compression.BzaFileSystem, compression.GzipFileSystem, compression.LzaFileSystem, compression.XzFileSystem, compression.ZstdFileSystem, ] # Register custom filesystems for fs_class in COMPRESSION_FILESYSTEMS + [HfFileSystem]: if fs_class.protocol in fsspec.registry and fsspec.registry[fs_class.protocol] is not fs_class: warnings.warn(f'A filesystem protocol was already set for {fs_class.protocol} and will be overwritten.') fsspec.register_implementation(fs_class.protocol, fs_class, clobber=True) def _lowercase ( __lowerCAmelCase ) -> str: if "://" in dataset_path: SCREAMING_SNAKE_CASE__ : Dict = dataset_path.split("""://""" )[1] return dataset_path def _lowercase ( __lowerCAmelCase ) -> bool: if fs is not None and fs.protocol != "file": return True else: return False def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Optional[Any] = not is_remote_filesystem(__lowerCAmelCase ) if is_local: # LocalFileSystem.mv does copy + rm, it is more efficient to simply move a local directory shutil.move(fs._strip_protocol(__lowerCAmelCase ) , fs._strip_protocol(__lowerCAmelCase ) ) else: fs.mv(__lowerCAmelCase , __lowerCAmelCase , recursive=__lowerCAmelCase ) def _lowercase ( ) -> None: if hasattr(fsspec.asyn , """reset_lock""" ): # for future fsspec>2022.05.0 fsspec.asyn.reset_lock() else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : int = threading.Lock()
680
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> int: assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and number_of_steps > 0 ), F'''number_of_steps needs to be positive integer, your input {number_of_steps}''' if number_of_steps == 1: return 1 SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = 1, 1 for _ in range(number_of_steps - 1 ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = current + previous, current return current if __name__ == "__main__": import doctest doctest.testmod()
680
1
"""simple docstring""" import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ConvNextConfig, UperNetConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import UperNetForSemanticSegmentation from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __a : '''simple docstring''' def __init__( self , _a , _a=13 , _a=32 , _a=3 , _a=4 , _a=[10, 20, 30, 40] , _a=[2, 2, 3, 2] , _a=True , _a=True , _a=37 , _a="gelu" , _a=10 , _a=0.02 , _a=["stage2", "stage3", "stage4"] , _a=3 , _a=None , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = parent SCREAMING_SNAKE_CASE__ : Dict = batch_size SCREAMING_SNAKE_CASE__ : Tuple = image_size SCREAMING_SNAKE_CASE__ : List[str] = num_channels SCREAMING_SNAKE_CASE__ : List[str] = num_stages SCREAMING_SNAKE_CASE__ : str = hidden_sizes SCREAMING_SNAKE_CASE__ : Union[str, Any] = depths SCREAMING_SNAKE_CASE__ : Optional[int] = is_training SCREAMING_SNAKE_CASE__ : List[Any] = use_labels SCREAMING_SNAKE_CASE__ : List[Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE__ : int = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Optional[Any] = initializer_range SCREAMING_SNAKE_CASE__ : Tuple = out_features SCREAMING_SNAKE_CASE__ : int = num_labels SCREAMING_SNAKE_CASE__ : Dict = scope SCREAMING_SNAKE_CASE__ : Dict = num_stages def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Dict = self.get_config() return config, pixel_values, labels def _a ( self ) -> Tuple: """simple docstring""" return ConvNextConfig( num_channels=self.num_channels , num_stages=self.num_stages , hidden_sizes=self.hidden_sizes , depths=self.depths , is_training=self.is_training , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , out_features=self.out_features , ) def _a ( self ) -> Tuple: """simple docstring""" return UperNetConfig( backbone_config=self.get_backbone_config() , hidden_size=512 , pool_scales=[1, 2, 3, 6] , use_auxiliary_head=_a , auxiliary_loss_weight=0.4 , auxiliary_in_channels=40 , auxiliary_channels=256 , auxiliary_num_convs=1 , auxiliary_concat_input=_a , loss_ignore_index=255 , num_labels=self.num_labels , ) def _a ( self , _a , _a , _a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = UperNetForSemanticSegmentation(config=_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : str = model(_a ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : str = config_and_inputs SCREAMING_SNAKE_CASE__ : List[str] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class __a (UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :int = (UperNetForSemanticSegmentation,) if is_torch_available() else () _SCREAMING_SNAKE_CASE :List[Any] = {"""image-segmentation""": UperNetForSemanticSegmentation} if is_torch_available() else {} _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :int = False _SCREAMING_SNAKE_CASE :Tuple = False _SCREAMING_SNAKE_CASE :List[Any] = False _SCREAMING_SNAKE_CASE :int = False _SCREAMING_SNAKE_CASE :Optional[int] = False def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = UperNetModelTester(self ) SCREAMING_SNAKE_CASE__ : Tuple = ConfigTester(self , config_class=_a , has_text_modality=_a , hidden_size=37 ) def _a ( self ) -> Optional[int]: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _a ( self ) -> Any: """simple docstring""" return def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_class(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : Optional[int] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Tuple = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _a ) def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_a ) @unittest.skip(reason="""UperNet does not use inputs_embeds""" ) def _a ( self ) -> Tuple: """simple docstring""" pass @unittest.skip(reason="""UperNet does not support input and output embeddings""" ) def _a ( self ) -> Optional[Any]: """simple docstring""" pass @unittest.skip(reason="""UperNet does not have a base model""" ) def _a ( self ) -> Dict: """simple docstring""" pass @unittest.skip(reason="""UperNet does not have a base model""" ) def _a ( self ) -> int: """simple docstring""" pass @require_torch_multi_gpu @unittest.skip(reason="""UperNet has some layers using `add_module` which doesn't work well with `nn.DataParallel`""" ) def _a ( self ) -> str: """simple docstring""" pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def _a ( self ) -> Dict: """simple docstring""" pass def _a ( self ) -> int: """simple docstring""" def check_hidden_states_output(_a , _a , _a ): SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[Any] = model(**self._prepare_for_class(_a , _a ) ) SCREAMING_SNAKE_CASE__ : Dict = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.num_stages self.assertEqual(len(_a ) , expected_num_stages + 1 ) # ConvNext's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[str] = True check_hidden_states_output(_a , _a , _a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : Dict = True check_hidden_states_output(_a , _a , _a ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Any = _config_zero_init(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = _config_zero_init(configs_no_init.backbone_config ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[Any] = model_class(config=_a ) for name, param in model.named_parameters(): if 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''' , ) @unittest.skip(reason="""UperNet does not have tied weights""" ) def _a ( self ) -> List[Any]: """simple docstring""" pass @slow def _a ( self ) -> str: """simple docstring""" for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : int = UperNetForSemanticSegmentation.from_pretrained(_a ) self.assertIsNotNone(_a ) def _lowercase ( ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : Optional[int] = hf_hub_download( repo_id="""hf-internal-testing/fixtures_ade20k""" , repo_type="""dataset""" , filename="""ADE_val_00000001.jpg""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = Image.open(__lowerCAmelCase ).convert("""RGB""" ) return image @require_torch @require_vision @slow class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = AutoImageProcessor.from_pretrained("""openmmlab/upernet-swin-tiny""" ) SCREAMING_SNAKE_CASE__ : Any = UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-swin-tiny""" ).to(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = prepare_img() SCREAMING_SNAKE_CASE__ : int = processor(images=_a , return_tensors="""pt""" ).to(_a ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[int] = model(**_a ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , _a ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor( [[-7.5_958, -7.5_958, -7.4_302], [-7.5_958, -7.5_958, -7.4_302], [-7.4_797, -7.4_797, -7.3_068]] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , _a , atol=1E-4 ) ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = AutoImageProcessor.from_pretrained("""openmmlab/upernet-convnext-tiny""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-convnext-tiny""" ).to(_a ) SCREAMING_SNAKE_CASE__ : Tuple = prepare_img() SCREAMING_SNAKE_CASE__ : str = processor(images=_a , return_tensors="""pt""" ).to(_a ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any = model(**_a ) SCREAMING_SNAKE_CASE__ : str = torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , _a ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor( [[-8.8_110, -8.8_110, -8.6_521], [-8.8_110, -8.8_110, -8.6_521], [-8.7_746, -8.7_746, -8.6_130]] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , _a , atol=1E-4 ) )
680
"""simple docstring""" from math import factorial def _lowercase ( __lowerCAmelCase = 100 ) -> int: return sum(int(__lowerCAmelCase ) for x in str(factorial(__lowerCAmelCase ) ) ) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
680
1
"""simple docstring""" from random import randint from tempfile import TemporaryFile import numpy as np def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[int] = 0 if start < end: SCREAMING_SNAKE_CASE__ : Any = randint(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = a[end] SCREAMING_SNAKE_CASE__ : Union[str, Any] = a[pivot] SCREAMING_SNAKE_CASE__ : Optional[int] = temp SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = _in_place_partition(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) count += _in_place_quick_sort(__lowerCAmelCase , __lowerCAmelCase , p - 1 ) count += _in_place_quick_sort(__lowerCAmelCase , p + 1 , __lowerCAmelCase ) return count def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : str = 0 SCREAMING_SNAKE_CASE__ : Dict = randint(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = a[end] SCREAMING_SNAKE_CASE__ : Dict = a[pivot] SCREAMING_SNAKE_CASE__ : Tuple = temp SCREAMING_SNAKE_CASE__ : int = start - 1 for index in range(__lowerCAmelCase , __lowerCAmelCase ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value SCREAMING_SNAKE_CASE__ : List[str] = new_pivot_index + 1 SCREAMING_SNAKE_CASE__ : List[str] = a[new_pivot_index] SCREAMING_SNAKE_CASE__ : Optional[int] = a[index] SCREAMING_SNAKE_CASE__ : Any = temp SCREAMING_SNAKE_CASE__ : Optional[Any] = a[new_pivot_index + 1] SCREAMING_SNAKE_CASE__ : Optional[int] = a[end] SCREAMING_SNAKE_CASE__ : Dict = temp return new_pivot_index + 1, count a :List[Any] = TemporaryFile() a :Tuple = 100 # 1000 elements are to be sorted a ,a :Tuple = 0, 1 # mean and standard deviation a :Any = np.random.normal(mu, sigma, p) np.save(outfile, X) print("The array is") print(X) outfile.seek(0) # using the same array a :str = np.load(outfile) a :Any = len(M) - 1 a :Tuple = _in_place_quick_sort(M, 0, r) print( "No of Comparisons for 100 elements selected from a standard normal distribution" "is :" ) print(z)
680
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from typing import List from unittest.mock import Mock import torch from torch.utils.data import DataLoader, IterableDataset, TensorDataset from accelerate.accelerator import Accelerator from accelerate.utils.dataclasses import DistributedType class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = data def __iter__( self ) -> Tuple: """simple docstring""" for element in self.data: yield element def _lowercase ( __lowerCAmelCase=True ) -> str: SCREAMING_SNAKE_CASE__ : str = Accelerator(even_batches=__lowerCAmelCase ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = False ) -> Optional[int]: if iterable: SCREAMING_SNAKE_CASE__ : int = DummyIterableDataset(torch.as_tensor(range(__lowerCAmelCase ) ) ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = TensorDataset(torch.as_tensor(range(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : str = DataLoader(__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = accelerator.prepare(__lowerCAmelCase ) return dl def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> Tuple: SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(accelerator=__lowerCAmelCase , dataset_size=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = [len(batch[0] ) for batch in dl] if accelerator.process_index == 0: assert batch_sizes == process_0_expected_batch_sizes elif accelerator.process_index == 1: assert batch_sizes == process_1_expected_batch_sizes def _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Tuple = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1, 1] , ) # without padding, we would expect the same number of batches, but different sizes verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_accelerator(even_batches=__lowerCAmelCase ) verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , ) verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , ) def _lowercase ( ) -> str: SCREAMING_SNAKE_CASE__ : List[str] = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) SCREAMING_SNAKE_CASE__ : int = [] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Optional[Any] = ddp_model(batch[0].float() ) SCREAMING_SNAKE_CASE__ : List[Any] = output.sum() loss.backward() batch_idxs.append(__lowerCAmelCase ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: with warnings.catch_warnings(record=__lowerCAmelCase ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category , __lowerCAmelCase ) assert "only supported for multi-GPU" in str(w[-1].message ) def _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = False SCREAMING_SNAKE_CASE__ : Any = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerator.prepare(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) SCREAMING_SNAKE_CASE__ : List[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[Any] = train_dl.batch_sampler.even_batches SCREAMING_SNAKE_CASE__ : str = valid_dl.batch_sampler.even_batches assert train_dl_overridden_value == overridden_even_batches assert valid_dl_overridden_value == overridden_even_batches assert train_dl.batch_sampler.even_batches == default_even_batches assert valid_dl.batch_sampler.even_batches == default_even_batches def _lowercase ( ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[Any] = True SCREAMING_SNAKE_CASE__ : List[Any] = False SCREAMING_SNAKE_CASE__ : int = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : str = accelerator.prepare(__lowerCAmelCase ) create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings("""ignore""" ) try: with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = batch_dl.batch_sampler.even_batches except AttributeError: # ensure attribute error is not raised when processing iterable dl raise AssertionError assert batch_dl_overridden_value == overridden_even_batches assert batch_dl.batch_sampler.even_batches == default_even_batches def _lowercase ( ) -> List[str]: SCREAMING_SNAKE_CASE__ : str = create_accelerator() SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase ) create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase ) with warnings.catch_warnings(record=__lowerCAmelCase ) as w: with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): pass assert issubclass(w[-1].category , __lowerCAmelCase ) assert "only supported for map-style datasets" in str(w[-1].message ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_accelerator() accelerator.print("""Test that even_batches variable ensures uniform batches across processes""" ) test_default_ensures_even_batch_sizes() accelerator.print("""Run tests with even_batches disabled""" ) test_can_disable_even_batches() accelerator.print("""Test joining uneven inputs""" ) test_can_join_uneven_inputs() accelerator.print("""Test overriding even_batches when joining uneven inputs""" ) test_join_can_override_even_batches() accelerator.print("""Test overriding even_batches for mixed dataloader types""" ) test_join_can_override_for_mixed_type_dataloaders() accelerator.print("""Test overriding even_batches raises a warning for iterable dataloaders""" ) test_join_raises_warning_for_iterable_when_overriding_even_batches() accelerator.print("""Test join with non DDP distributed raises warning""" ) SCREAMING_SNAKE_CASE__ : Dict = accelerator.state.distributed_type SCREAMING_SNAKE_CASE__ : Optional[int] = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = original_state if __name__ == "__main__": main()
680
1
"""simple docstring""" from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging a :Union[str, Any] = logging.get_logger(__name__) a :Dict = { "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 __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = """informer""" _SCREAMING_SNAKE_CASE :str = { """hidden_size""": """d_model""", """num_attention_heads""": """encoder_attention_heads""", """num_hidden_layers""": """encoder_layers""", } def __init__( self , _a = None , _a = None , _a = "student_t" , _a = "nll" , _a = 1 , _a = None , _a = "mean" , _a = 0 , _a = 0 , _a = 0 , _a = 0 , _a = None , _a = None , _a = 64 , _a = 32 , _a = 32 , _a = 2 , _a = 2 , _a = 2 , _a = 2 , _a = True , _a = "gelu" , _a = 0.05 , _a = 0.1 , _a = 0.1 , _a = 0.1 , _a = 0.1 , _a = 100 , _a = 0.02 , _a=True , _a = "prob" , _a = 5 , _a = True , **_a , ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = prediction_length SCREAMING_SNAKE_CASE__ : int = context_length or prediction_length SCREAMING_SNAKE_CASE__ : Any = distribution_output SCREAMING_SNAKE_CASE__ : List[str] = loss SCREAMING_SNAKE_CASE__ : int = input_size SCREAMING_SNAKE_CASE__ : List[Any] = num_time_features SCREAMING_SNAKE_CASE__ : Optional[int] = lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7] SCREAMING_SNAKE_CASE__ : List[str] = scaling SCREAMING_SNAKE_CASE__ : Tuple = num_dynamic_real_features SCREAMING_SNAKE_CASE__ : List[str] = num_static_real_features SCREAMING_SNAKE_CASE__ : Optional[int] = 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`""" ) SCREAMING_SNAKE_CASE__ : str = cardinality else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [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`""" ) SCREAMING_SNAKE_CASE__ : Dict = embedding_dimension else: SCREAMING_SNAKE_CASE__ : List[Any] = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] SCREAMING_SNAKE_CASE__ : str = num_parallel_samples # Transformer architecture configuration SCREAMING_SNAKE_CASE__ : Any = input_size * len(self.lags_sequence ) + self._number_of_features SCREAMING_SNAKE_CASE__ : List[Any] = d_model SCREAMING_SNAKE_CASE__ : Union[str, Any] = encoder_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] = decoder_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] = encoder_ffn_dim SCREAMING_SNAKE_CASE__ : int = decoder_ffn_dim SCREAMING_SNAKE_CASE__ : Union[str, Any] = encoder_layers SCREAMING_SNAKE_CASE__ : Dict = decoder_layers SCREAMING_SNAKE_CASE__ : Any = dropout SCREAMING_SNAKE_CASE__ : Union[str, Any] = attention_dropout SCREAMING_SNAKE_CASE__ : Optional[int] = activation_dropout SCREAMING_SNAKE_CASE__ : str = encoder_layerdrop SCREAMING_SNAKE_CASE__ : int = decoder_layerdrop SCREAMING_SNAKE_CASE__ : Union[str, Any] = activation_function SCREAMING_SNAKE_CASE__ : List[Any] = init_std SCREAMING_SNAKE_CASE__ : List[str] = use_cache # Informer SCREAMING_SNAKE_CASE__ : Any = attention_type SCREAMING_SNAKE_CASE__ : str = sampling_factor SCREAMING_SNAKE_CASE__ : Dict = distil super().__init__(is_encoder_decoder=_a , **_a ) @property def _a ( self ) -> int: """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 )
680
"""simple docstring""" def _lowercase ( __lowerCAmelCase = 200_0000 ) -> int: SCREAMING_SNAKE_CASE__ : int = [0 for i in range(n + 1 )] SCREAMING_SNAKE_CASE__ : str = 1 SCREAMING_SNAKE_CASE__ : str = 1 for i in range(2 , int(n**0.5 ) + 1 ): if primality_list[i] == 0: for j in range(i * i , n + 1 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 for i in range(__lowerCAmelCase ): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(f'{solution() = }')
680
1
"""simple docstring""" import copy import os from typing import TYPE_CHECKING, List, Union if TYPE_CHECKING: pass from ...configuration_utils import PretrainedConfig from ...utils import logging a :Optional[Any] = logging.get_logger(__name__) a :str = { "kakaobrain/align-base": "https://huggingface.co/kakaobrain/align-base/resolve/main/config.json", } class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Dict = """align_text_model""" def __init__( self , _a=30_522 , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=2 , _a=0.02 , _a=1E-1_2 , _a=0 , _a="absolute" , _a=True , **_a , ) -> Any: """simple docstring""" super().__init__(**_a ) SCREAMING_SNAKE_CASE__ : List[Any] = vocab_size SCREAMING_SNAKE_CASE__ : Any = hidden_size SCREAMING_SNAKE_CASE__ : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE__ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_act SCREAMING_SNAKE_CASE__ : int = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Dict = type_vocab_size SCREAMING_SNAKE_CASE__ : Tuple = initializer_range SCREAMING_SNAKE_CASE__ : Optional[int] = layer_norm_eps SCREAMING_SNAKE_CASE__ : Any = position_embedding_type SCREAMING_SNAKE_CASE__ : Optional[int] = use_cache SCREAMING_SNAKE_CASE__ : Dict = pad_token_id @classmethod def _a ( cls , _a , **_a ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(_a ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = cls.get_config_dict(_a , **_a ) # get the text config dict if we are loading from AlignConfig if config_dict.get("""model_type""" ) == "align": SCREAMING_SNAKE_CASE__ : Optional[int] = config_dict["""text_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(_a , **_a ) class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = """align_vision_model""" def __init__( self , _a = 3 , _a = 600 , _a = 2.0 , _a = 3.1 , _a = 8 , _a = [3, 3, 5, 3, 5, 5, 3] , _a = [32, 16, 24, 40, 80, 112, 192] , _a = [16, 24, 40, 80, 112, 192, 320] , _a = [] , _a = [1, 2, 2, 2, 1, 2, 1] , _a = [1, 2, 2, 3, 3, 4, 1] , _a = [1, 6, 6, 6, 6, 6, 6] , _a = 0.25 , _a = "swish" , _a = 2_560 , _a = "mean" , _a = 0.02 , _a = 0.001 , _a = 0.99 , _a = 0.2 , **_a , ) -> Tuple: """simple docstring""" super().__init__(**_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = num_channels SCREAMING_SNAKE_CASE__ : int = image_size SCREAMING_SNAKE_CASE__ : Dict = width_coefficient SCREAMING_SNAKE_CASE__ : Dict = depth_coefficient SCREAMING_SNAKE_CASE__ : Union[str, Any] = depth_divisor SCREAMING_SNAKE_CASE__ : Union[str, Any] = kernel_sizes SCREAMING_SNAKE_CASE__ : Dict = in_channels SCREAMING_SNAKE_CASE__ : int = out_channels SCREAMING_SNAKE_CASE__ : Dict = depthwise_padding SCREAMING_SNAKE_CASE__ : str = strides SCREAMING_SNAKE_CASE__ : Any = num_block_repeats SCREAMING_SNAKE_CASE__ : Dict = expand_ratios SCREAMING_SNAKE_CASE__ : int = squeeze_expansion_ratio SCREAMING_SNAKE_CASE__ : Dict = hidden_act SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_dim SCREAMING_SNAKE_CASE__ : int = pooling_type SCREAMING_SNAKE_CASE__ : Union[str, Any] = initializer_range SCREAMING_SNAKE_CASE__ : Dict = batch_norm_eps SCREAMING_SNAKE_CASE__ : Any = batch_norm_momentum SCREAMING_SNAKE_CASE__ : List[Any] = drop_connect_rate SCREAMING_SNAKE_CASE__ : int = sum(_a ) * 4 @classmethod def _a ( cls , _a , **_a ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(_a ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = cls.get_config_dict(_a , **_a ) # get the vision config dict if we are loading from AlignConfig if config_dict.get("""model_type""" ) == "align": SCREAMING_SNAKE_CASE__ : Dict = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(_a , **_a ) class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :int = """align""" _SCREAMING_SNAKE_CASE :int = True def __init__( self , _a=None , _a=None , _a=640 , _a=1.0 , _a=0.02 , **_a , ) -> Tuple: """simple docstring""" super().__init__(**_a ) if text_config is None: SCREAMING_SNAKE_CASE__ : List[Any] = {} logger.info("""text_config is None. Initializing the AlignTextConfig with default values.""" ) if vision_config is None: SCREAMING_SNAKE_CASE__ : Optional[Any] = {} logger.info("""vision_config is None. Initializing the AlignVisionConfig with default values.""" ) SCREAMING_SNAKE_CASE__ : Dict = AlignTextConfig(**_a ) SCREAMING_SNAKE_CASE__ : Dict = AlignVisionConfig(**_a ) SCREAMING_SNAKE_CASE__ : List[str] = projection_dim SCREAMING_SNAKE_CASE__ : List[str] = temperature_init_value SCREAMING_SNAKE_CASE__ : Dict = initializer_range @classmethod def _a ( cls , _a , _a , **_a ) -> str: """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **_a ) def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.text_config.to_dict() SCREAMING_SNAKE_CASE__ : Any = self.vision_config.to_dict() SCREAMING_SNAKE_CASE__ : Dict = self.__class__.model_type return output
680
"""simple docstring""" import numpy as np import qiskit def _lowercase ( __lowerCAmelCase = 8 , __lowerCAmelCase = None ) -> str: SCREAMING_SNAKE_CASE__ : List[Any] = np.random.default_rng(seed=__lowerCAmelCase ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. SCREAMING_SNAKE_CASE__ : List[str] = 6 * key_len # Measurement basis for Alice's qubits. SCREAMING_SNAKE_CASE__ : List[Any] = rng.integers(2 , size=__lowerCAmelCase ) # The set of states Alice will prepare. SCREAMING_SNAKE_CASE__ : Optional[Any] = rng.integers(2 , size=__lowerCAmelCase ) # Measurement basis for Bob's qubits. SCREAMING_SNAKE_CASE__ : str = rng.integers(2 , size=__lowerCAmelCase ) # Quantum Circuit to simulate BB84 SCREAMING_SNAKE_CASE__ : Union[str, Any] = qiskit.QuantumCircuit(__lowerCAmelCase , name="""BB84""" ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(__lowerCAmelCase ): if alice_state[index] == 1: bbaa_circ.x(__lowerCAmelCase ) if alice_basis[index] == 1: bbaa_circ.h(__lowerCAmelCase ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(__lowerCAmelCase ): if bob_basis[index] == 1: bbaa_circ.h(__lowerCAmelCase ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. SCREAMING_SNAKE_CASE__ : str = qiskit.Aer.get_backend("""aer_simulator""" ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. SCREAMING_SNAKE_CASE__ : Optional[int] = qiskit.execute(__lowerCAmelCase , __lowerCAmelCase , shots=1 , seed_simulator=__lowerCAmelCase ) # Returns the result of measurement. SCREAMING_SNAKE_CASE__ : int = job.result().get_counts(__lowerCAmelCase ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. SCREAMING_SNAKE_CASE__ : Optional[Any] = """""".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. SCREAMING_SNAKE_CASE__ : Optional[int] = gen_key[:key_len] if len(__lowerCAmelCase ) >= key_len else gen_key.ljust(__lowerCAmelCase , """0""" ) return key if __name__ == "__main__": print(f'The generated key is : {bbaa(8, seed=0)}') from doctest import testmod testmod()
680
1
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> float: if edge <= 0 or not isinstance(__lowerCAmelCase , __lowerCAmelCase ): raise ValueError("""Length must be a positive.""" ) return 3 * ((25 + 10 * (5 ** (1 / 2))) ** (1 / 2)) * (edge**2) def _lowercase ( __lowerCAmelCase ) -> float: if edge <= 0 or not isinstance(__lowerCAmelCase , __lowerCAmelCase ): raise ValueError("""Length must be a positive.""" ) return ((15 + (7 * (5 ** (1 / 2)))) / 4) * (edge**3) if __name__ == "__main__": import doctest doctest.testmod()
680
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __a (UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :str = StableDiffusionInpaintPipeline _SCREAMING_SNAKE_CASE :Any = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS _SCREAMING_SNAKE_CASE :Dict = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS _SCREAMING_SNAKE_CASE :Optional[int] = frozenset( []) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _SCREAMING_SNAKE_CASE :Dict = frozenset([]) def _a ( self ) -> Dict: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , 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 , ) SCREAMING_SNAKE_CASE__ : List[str] = PNDMScheduler(skip_prk_steps=_a ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = 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 ) SCREAMING_SNAKE_CASE__ : int = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) SCREAMING_SNAKE_CASE__ : int = CLIPTextModel(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) SCREAMING_SNAKE_CASE__ : int = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def _a ( self , _a , _a=0 ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = floats_tensor((1, 3, 32, 32) , rng=random.Random(_a ) ).to(_a ) SCREAMING_SNAKE_CASE__ : Tuple = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : Any = Image.fromarray(np.uinta(_a ) ).convert("""RGB""" ).resize((64, 64) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(_a ).startswith("""mps""" ): SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(_a ) else: SCREAMING_SNAKE_CASE__ : str = torch.Generator(device=_a ).manual_seed(_a ) SCREAMING_SNAKE_CASE__ : Tuple = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInpaintPipeline(**_a ) SCREAMING_SNAKE_CASE__ : Any = sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : int = self.get_dummy_inputs(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe(**_a ).images SCREAMING_SNAKE_CASE__ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : str = np.array([0.4_727, 0.5_735, 0.3_941, 0.5_446, 0.5_926, 0.4_394, 0.5_062, 0.4_654, 0.4_476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _a ( self ) -> Optional[int]: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : Any = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : Any = StableDiffusionInpaintPipeline.from_pretrained(_a , safety_checker=_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : int = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Tuple = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : int = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) SCREAMING_SNAKE_CASE__ : List[str] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInpaintPipeline.from_pretrained( _a , torch_dtype=torch.floataa , safety_checker=_a , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Any = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Tuple = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def _a ( self ) -> Tuple: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE__ : Dict = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : str = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : List[str] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : Dict = PNDMScheduler.from_pretrained(_a , subfolder="""scheduler""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = StableDiffusionInpaintPipeline.from_pretrained( _a , safety_checker=_a , scheduler=_a , torch_dtype=torch.floataa , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE__ : Union[str, Any] = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , num_inference_steps=2 , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : List[str] = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
680
1
"""simple docstring""" import re def _lowercase ( __lowerCAmelCase ) -> str: if len(re.findall("""[ATCG]""" , __lowerCAmelCase ) ) != len(__lowerCAmelCase ): raise ValueError("""Invalid Strand""" ) return dna.translate(dna.maketrans("""ATCG""" , """TAGC""" ) ) if __name__ == "__main__": import doctest doctest.testmod()
680
"""simple docstring""" import argparse import logging import pickle import random import time import numpy as np from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) a :str = logging.getLogger(__name__) def _lowercase ( ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Dict = argparse.ArgumentParser( description="""Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids).""" ) parser.add_argument("""--file_path""" , type=__lowerCAmelCase , default="""data/dump.txt""" , help="""The path to the data.""" ) parser.add_argument("""--tokenizer_type""" , type=__lowerCAmelCase , default="""bert""" , choices=["""bert""", """roberta""", """gpt2"""] ) parser.add_argument("""--tokenizer_name""" , type=__lowerCAmelCase , default="""bert-base-uncased""" , help="""The tokenizer to use.""" ) parser.add_argument("""--dump_file""" , type=__lowerCAmelCase , default="""data/dump""" , help="""The dump file prefix.""" ) SCREAMING_SNAKE_CASE__ : str = parser.parse_args() logger.info(F'''Loading Tokenizer ({args.tokenizer_name})''' ) if args.tokenizer_type == "bert": SCREAMING_SNAKE_CASE__ : List[str] = BertTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : str = tokenizer.special_tokens_map["""cls_token"""] # `[CLS]` SCREAMING_SNAKE_CASE__ : str = tokenizer.special_tokens_map["""sep_token"""] # `[SEP]` elif args.tokenizer_type == "roberta": SCREAMING_SNAKE_CASE__ : List[Any] = RobertaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.special_tokens_map["""cls_token"""] # `<s>` SCREAMING_SNAKE_CASE__ : Dict = tokenizer.special_tokens_map["""sep_token"""] # `</s>` elif args.tokenizer_type == "gpt2": SCREAMING_SNAKE_CASE__ : List[Any] = GPTaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.special_tokens_map["""bos_token"""] # `<|endoftext|>` SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.special_tokens_map["""eos_token"""] # `<|endoftext|>` logger.info(F'''Loading text from {args.file_path}''' ) with open(args.file_path , """r""" , encoding="""utf8""" ) as fp: SCREAMING_SNAKE_CASE__ : int = fp.readlines() logger.info("""Start encoding""" ) logger.info(F'''{len(__lowerCAmelCase )} examples to process.''' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1_0000 SCREAMING_SNAKE_CASE__ : Dict = time.time() for text in data: SCREAMING_SNAKE_CASE__ : Dict = F'''{bos} {text.strip()} {sep}''' SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) rslt.append(__lowerCAmelCase ) iter += 1 if iter % interval == 0: SCREAMING_SNAKE_CASE__ : str = time.time() logger.info(F'''{iter} examples processed. - {(end-start):.2f}s/{interval}expl''' ) SCREAMING_SNAKE_CASE__ : Tuple = time.time() logger.info("""Finished binarization""" ) logger.info(F'''{len(__lowerCAmelCase )} examples processed.''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = F'''{args.dump_file}.{args.tokenizer_name}.pickle''' SCREAMING_SNAKE_CASE__ : Dict = tokenizer.vocab_size if vocab_size < (1 << 16): SCREAMING_SNAKE_CASE__ : Tuple = [np.uintaa(__lowerCAmelCase ) for d in rslt] else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [np.intaa(__lowerCAmelCase ) for d in rslt] random.shuffle(rslt_ ) logger.info(F'''Dump to {dp_file}''' ) with open(__lowerCAmelCase , """wb""" ) as handle: pickle.dump(rslt_ , __lowerCAmelCase , protocol=pickle.HIGHEST_PROTOCOL ) if __name__ == "__main__": main()
680
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) a :Union[str, Any] = { "configuration_speecht5": [ "SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP", "SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP", "SpeechT5Config", "SpeechT5HifiGanConfig", ], "feature_extraction_speecht5": ["SpeechT5FeatureExtractor"], "processing_speecht5": ["SpeechT5Processor"], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = ["SpeechT5Tokenizer"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST", "SpeechT5ForSpeechToText", "SpeechT5ForSpeechToSpeech", "SpeechT5ForTextToSpeech", "SpeechT5Model", "SpeechT5PreTrainedModel", "SpeechT5HifiGan", ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys a :Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
"""simple docstring""" import glob import os import random from string import ascii_lowercase, digits import cva a :List[Any] = "" a :Union[str, Any] = "" a :List[str] = "" a :str = 1 # (0 is vertical, 1 is horizontal) def _lowercase ( ) -> None: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = get_dataset(__lowerCAmelCase , __lowerCAmelCase ) print("""Processing...""" ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = update_image_and_anno(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) for index, image in enumerate(__lowerCAmelCase ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' SCREAMING_SNAKE_CASE__ : List[Any] = random_chars(32 ) SCREAMING_SNAKE_CASE__ : List[str] = paths[index].split(os.sep )[-1].rsplit(""".""" , 1 )[0] SCREAMING_SNAKE_CASE__ : List[str] = F'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(F'''/{file_root}.jpg''' , __lowerCAmelCase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F'''Success {index+1}/{len(__lowerCAmelCase )} with {file_name}''' ) SCREAMING_SNAKE_CASE__ : int = [] for anno in new_annos[index]: SCREAMING_SNAKE_CASE__ : Tuple = F'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(__lowerCAmelCase ) with open(F'''/{file_root}.txt''' , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> tuple[list, list]: SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] for label_file in glob.glob(os.path.join(__lowerCAmelCase , """*.txt""" ) ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(__lowerCAmelCase ) as in_file: SCREAMING_SNAKE_CASE__ : Dict = in_file.readlines() SCREAMING_SNAKE_CASE__ : int = os.path.join(__lowerCAmelCase , F'''{label_name}.jpg''' ) SCREAMING_SNAKE_CASE__ : int = [] for obj_list in obj_lists: SCREAMING_SNAKE_CASE__ : Optional[int] = obj_list.rstrip("""\n""" ).split(""" """ ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(__lowerCAmelCase ) labels.append(__lowerCAmelCase ) return img_paths, labels def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = 1 ) -> tuple[list, list, list]: SCREAMING_SNAKE_CASE__ : Dict = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [] for idx in range(len(__lowerCAmelCase ) ): SCREAMING_SNAKE_CASE__ : List[str] = [] SCREAMING_SNAKE_CASE__ : str = img_list[idx] path_list.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = anno_list[idx] SCREAMING_SNAKE_CASE__ : Tuple = cva.imread(__lowerCAmelCase ) if flip_type == 1: SCREAMING_SNAKE_CASE__ : int = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: SCREAMING_SNAKE_CASE__ : Optional[int] = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: SCREAMING_SNAKE_CASE__ : Any = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: SCREAMING_SNAKE_CASE__ : List[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(__lowerCAmelCase ) new_imgs_list.append(__lowerCAmelCase ) return new_imgs_list, new_annos_lists, path_list def _lowercase ( __lowerCAmelCase = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" SCREAMING_SNAKE_CASE__ : List[str] = ascii_lowercase + digits return "".join(random.choice(__lowerCAmelCase ) for _ in range(__lowerCAmelCase ) ) if __name__ == "__main__": main() print("DONE ✅")
680
1
"""simple docstring""" import torch from diffusers import DiffusionPipeline class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , _a , _a ) -> Optional[Any]: """simple docstring""" super().__init__() self.register_modules(unet=_a , scheduler=_a ) def __call__( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.randn( (1, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = 1 SCREAMING_SNAKE_CASE__ : List[Any] = self.unet(_a , _a ).sample SCREAMING_SNAKE_CASE__ : str = self.scheduler.step(_a , _a , _a ).prev_sample SCREAMING_SNAKE_CASE__ : Union[str, Any] = scheduler_output - scheduler_output + torch.ones_like(_a ) return result
680
"""simple docstring""" import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class __a (enum.Enum): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = 0 _SCREAMING_SNAKE_CASE :List[Any] = 1 _SCREAMING_SNAKE_CASE :Dict = 2 @add_end_docstrings(UpperCamelCase_) class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = """ In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision and denounces one of the men as a horse thief. Although his father initially slaps him for making such an accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop, begging for his blessing. <eod> </s> <eos> """ def __init__( self , *_a , **_a ) -> Tuple: """simple docstring""" super().__init__(*_a , **_a ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == """tf""" else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. SCREAMING_SNAKE_CASE__ : Any = None if self.model.config.prefix is not None: SCREAMING_SNAKE_CASE__ : List[str] = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. SCREAMING_SNAKE_CASE__ : Optional[Any] = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self._sanitize_parameters(prefix=_a , **self._forward_params ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {**self._preprocess_params, **preprocess_params} SCREAMING_SNAKE_CASE__ : Optional[Any] = {**self._forward_params, **forward_params} def _a ( self , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , **_a , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = {} if prefix is not None: SCREAMING_SNAKE_CASE__ : Dict = prefix if prefix: SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer( _a , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Tuple = prefix_inputs["""input_ids"""].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( f'''{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected''' """ [None, 'hole']""" ) SCREAMING_SNAKE_CASE__ : int = handle_long_generation preprocess_params.update(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs SCREAMING_SNAKE_CASE__ : int = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_full_text`""" ) if return_tensors is not None: raise ValueError("""`return_full_text` is mutually exclusive with `return_tensors`""" ) SCREAMING_SNAKE_CASE__ : List[Any] = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_tensors`""" ) SCREAMING_SNAKE_CASE__ : Tuple = ReturnType.TENSORS if return_type is not None: SCREAMING_SNAKE_CASE__ : int = return_type if clean_up_tokenization_spaces is not None: SCREAMING_SNAKE_CASE__ : List[str] = clean_up_tokenization_spaces if stop_sequence is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.encode(_a , add_special_tokens=_a ) if len(_a ) > 1: warnings.warn( """Stopping on a multiple token sequence is not yet supported on transformers. The first token of""" """ the stop sequence will be used as the stop sequence string in the interim.""" ) SCREAMING_SNAKE_CASE__ : List[Any] = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def _a ( self , *_a , **_a ) -> Any: """simple docstring""" if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({"""add_space_before_punct_symbol""": True} ) return super()._parse_and_tokenize(*_a , **_a ) def __call__( self , _a , **_a ) -> Optional[int]: """simple docstring""" return super().__call__(_a , **_a ) def _a ( self , _a , _a="" , _a=None , **_a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer( prefix + prompt_text , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Tuple = prompt_text if handle_long_generation == "hole": SCREAMING_SNAKE_CASE__ : List[Any] = inputs["""input_ids"""].shape[-1] if "max_new_tokens" in generate_kwargs: SCREAMING_SNAKE_CASE__ : Union[str, Any] = generate_kwargs["""max_new_tokens"""] else: SCREAMING_SNAKE_CASE__ : Tuple = generate_kwargs.get("""max_length""" , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError("""We cannot infer how many new tokens are expected""" ) if cur_len + new_tokens > self.tokenizer.model_max_length: SCREAMING_SNAKE_CASE__ : str = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( """We cannot use `hole` to handle this generation the number of desired tokens exceeds the""" """ models max length""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs["""input_ids"""][:, -keep_length:] if "attention_mask" in inputs: SCREAMING_SNAKE_CASE__ : Optional[int] = inputs["""attention_mask"""][:, -keep_length:] return inputs def _a ( self , _a , **_a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_inputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : Optional[int] = model_inputs.get("""attention_mask""" , _a ) # Allow empty prompts if input_ids.shape[1] == 0: SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : List[Any] = None SCREAMING_SNAKE_CASE__ : List[str] = 1 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.shape[0] SCREAMING_SNAKE_CASE__ : Tuple = model_inputs.pop("""prompt_text""" ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs.pop("""prefix_length""" , 0 ) if prefix_length > 0: SCREAMING_SNAKE_CASE__ : List[str] = """max_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].max_new_tokens is not None ) if not has_max_new_tokens: SCREAMING_SNAKE_CASE__ : int = generate_kwargs.get("""max_length""" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length SCREAMING_SNAKE_CASE__ : Dict = """min_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL SCREAMING_SNAKE_CASE__ : Tuple = self.model.generate(input_ids=_a , attention_mask=_a , **_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = generated_sequence.shape[0] if self.framework == "pt": SCREAMING_SNAKE_CASE__ : str = generated_sequence.reshape(_a , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.reshape(_a , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def _a ( self , _a , _a=ReturnType.FULL_TEXT , _a=True ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = model_outputs["""generated_sequence"""][0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_outputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : str = model_outputs["""prompt_text"""] SCREAMING_SNAKE_CASE__ : Any = generated_sequence.numpy().tolist() SCREAMING_SNAKE_CASE__ : List[Any] = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: SCREAMING_SNAKE_CASE__ : Tuple = {"""generated_token_ids""": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.decode( _a , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: SCREAMING_SNAKE_CASE__ : Dict = 0 else: SCREAMING_SNAKE_CASE__ : Optional[int] = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) ) if return_type == ReturnType.FULL_TEXT: SCREAMING_SNAKE_CASE__ : Tuple = prompt_text + text[prompt_length:] else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = text[prompt_length:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {"""generated_text""": all_text} records.append(_a ) return records
680
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a :str = logging.get_logger(__name__) a :Union[str, Any] = { "junnyu/roformer_chinese_small": "https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json", "junnyu/roformer_chinese_base": "https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json", "junnyu/roformer_chinese_char_small": ( "https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json" ), "junnyu/roformer_chinese_char_base": ( "https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json" ), "junnyu/roformer_small_discriminator": ( "https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json" ), "junnyu/roformer_small_generator": ( "https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json" ), # See all RoFormer models at https://huggingface.co/models?filter=roformer } class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Any = """roformer""" def __init__( self , _a=50_000 , _a=None , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.1 , _a=0.1 , _a=1_536 , _a=2 , _a=0.02 , _a=1E-1_2 , _a=0 , _a=False , _a=True , **_a , ) -> List[str]: """simple docstring""" super().__init__(pad_token_id=_a , **_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = vocab_size SCREAMING_SNAKE_CASE__ : int = hidden_size if embedding_size is None else embedding_size SCREAMING_SNAKE_CASE__ : List[str] = hidden_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE__ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Tuple = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : int = type_vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = initializer_range SCREAMING_SNAKE_CASE__ : Optional[Any] = layer_norm_eps SCREAMING_SNAKE_CASE__ : Optional[Any] = rotary_value SCREAMING_SNAKE_CASE__ : str = use_cache class __a (UpperCamelCase_): '''simple docstring''' @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE__ : List[str] = {0: """batch""", 1: """choice""", 2: """sequence"""} else: SCREAMING_SNAKE_CASE__ : int = {0: """batch""", 1: """sequence"""} SCREAMING_SNAKE_CASE__ : Optional[int] = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
680
"""simple docstring""" from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> list[float]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = coefficient_matrix.shape SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE__ : Tuple = F'''Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if colsa != 1: SCREAMING_SNAKE_CASE__ : str = F'''Constant matrix must be nx1 but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if rowsa != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Coefficient and constant matrices dimensions must be nxn and nx1 but """ F'''received {rowsa}x{colsa} and {rowsa}x{colsa}''' ) raise ValueError(__lowerCAmelCase ) if len(__lowerCAmelCase ) != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Number of initial values must be equal to number of rows in coefficient """ F'''matrix but received {len(__lowerCAmelCase )} and {rowsa}''' ) raise ValueError(__lowerCAmelCase ) if iterations <= 0: raise ValueError("""Iterations must be at least 1""" ) SCREAMING_SNAKE_CASE__ : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = table.shape strictly_diagonally_dominant(__lowerCAmelCase ) # Iterates the whole matrix for given number of times for _ in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = [] for row in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = 0 for col in range(__lowerCAmelCase ): if col == row: SCREAMING_SNAKE_CASE__ : int = table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE__ : Any = (temp + val) / denom new_val.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = new_val return [float(__lowerCAmelCase ) for i in new_val] def _lowercase ( __lowerCAmelCase ) -> bool: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = table.shape SCREAMING_SNAKE_CASE__ : str = True for i in range(0 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("""Coefficient matrix is not strictly diagonally dominant""" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
680
1
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision.transforms import functional as F from transformers import DetrImageProcessor, TableTransformerConfig, TableTransformerForObjectDetection from transformers.utils import logging logging.set_verbosity_info() a :Any = logging.get_logger(__name__) # here we list all keys to be renamed (original name on the left, our name on the right) a :str = [] for i in range(6): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (f'transformer.encoder.layers.{i}.self_attn.out_proj.weight', f'encoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (f'transformer.encoder.layers.{i}.self_attn.out_proj.bias', f'encoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append((f'transformer.encoder.layers.{i}.linear1.weight', f'encoder.layers.{i}.fc1.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.linear1.bias', f'encoder.layers.{i}.fc1.bias')) rename_keys.append((f'transformer.encoder.layers.{i}.linear2.weight', f'encoder.layers.{i}.fc2.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.linear2.bias', f'encoder.layers.{i}.fc2.bias')) rename_keys.append( (f'transformer.encoder.layers.{i}.norm1.weight', f'encoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((f'transformer.encoder.layers.{i}.norm1.bias', f'encoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append((f'transformer.encoder.layers.{i}.norm2.weight', f'encoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.norm2.bias', f'encoder.layers.{i}.final_layer_norm.bias')) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( (f'transformer.decoder.layers.{i}.self_attn.out_proj.weight', f'decoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (f'transformer.decoder.layers.{i}.self_attn.out_proj.bias', f'decoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append( ( f'transformer.decoder.layers.{i}.multihead_attn.out_proj.weight', f'decoder.layers.{i}.encoder_attn.out_proj.weight', ) ) rename_keys.append( ( f'transformer.decoder.layers.{i}.multihead_attn.out_proj.bias', f'decoder.layers.{i}.encoder_attn.out_proj.bias', ) ) rename_keys.append((f'transformer.decoder.layers.{i}.linear1.weight', f'decoder.layers.{i}.fc1.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.linear1.bias', f'decoder.layers.{i}.fc1.bias')) rename_keys.append((f'transformer.decoder.layers.{i}.linear2.weight', f'decoder.layers.{i}.fc2.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.linear2.bias', f'decoder.layers.{i}.fc2.bias')) rename_keys.append( (f'transformer.decoder.layers.{i}.norm1.weight', f'decoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((f'transformer.decoder.layers.{i}.norm1.bias', f'decoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append( (f'transformer.decoder.layers.{i}.norm2.weight', f'decoder.layers.{i}.encoder_attn_layer_norm.weight') ) rename_keys.append( (f'transformer.decoder.layers.{i}.norm2.bias', f'decoder.layers.{i}.encoder_attn_layer_norm.bias') ) rename_keys.append((f'transformer.decoder.layers.{i}.norm3.weight', f'decoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.norm3.bias', f'decoder.layers.{i}.final_layer_norm.bias')) # convolutional projection + query embeddings + layernorm of encoder + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ("input_proj.weight", "input_projection.weight"), ("input_proj.bias", "input_projection.bias"), ("query_embed.weight", "query_position_embeddings.weight"), ("transformer.encoder.norm.weight", "encoder.layernorm.weight"), ("transformer.encoder.norm.bias", "encoder.layernorm.bias"), ("transformer.decoder.norm.weight", "decoder.layernorm.weight"), ("transformer.decoder.norm.bias", "decoder.layernorm.bias"), ("class_embed.weight", "class_labels_classifier.weight"), ("class_embed.bias", "class_labels_classifier.bias"), ("bbox_embed.layers.0.weight", "bbox_predictor.layers.0.weight"), ("bbox_embed.layers.0.bias", "bbox_predictor.layers.0.bias"), ("bbox_embed.layers.1.weight", "bbox_predictor.layers.1.weight"), ("bbox_embed.layers.1.bias", "bbox_predictor.layers.1.bias"), ("bbox_embed.layers.2.weight", "bbox_predictor.layers.2.weight"), ("bbox_embed.layers.2.bias", "bbox_predictor.layers.2.bias"), ] ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Tuple = state_dict.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = val def _lowercase ( __lowerCAmelCase ) -> Tuple: SCREAMING_SNAKE_CASE__ : str = OrderedDict() for key, value in state_dict.items(): if "backbone.0.body" in key: SCREAMING_SNAKE_CASE__ : List[Any] = key.replace("""backbone.0.body""" , """backbone.conv_encoder.model""" ) SCREAMING_SNAKE_CASE__ : Dict = value else: SCREAMING_SNAKE_CASE__ : Tuple = value return new_state_dict def _lowercase ( __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : str = """""" # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : int = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : int = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE__ : Any = in_proj_bias[:256] SCREAMING_SNAKE_CASE__ : Dict = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[256:512] SCREAMING_SNAKE_CASE__ : int = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[-256:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6 ): # read in weights + bias of input projection layer of self-attention SCREAMING_SNAKE_CASE__ : List[str] = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : Tuple = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Any = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[:256] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[256:512] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias[-256:] # read in weights + bias of input projection layer of cross-attention SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop( F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : List[Any] = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) of cross-attention to the state dict SCREAMING_SNAKE_CASE__ : int = in_proj_weight_cross_attn[:256, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias_cross_attn[:256] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight_cross_attn[256:512, :] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_bias_cross_attn[256:512] SCREAMING_SNAKE_CASE__ : int = in_proj_weight_cross_attn[-256:, :] SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias_cross_attn[-256:] def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = image.size SCREAMING_SNAKE_CASE__ : Optional[Any] = max(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = 800 if """detection""" in checkpoint_url else 1000 SCREAMING_SNAKE_CASE__ : List[str] = target_max_size / current_max_size SCREAMING_SNAKE_CASE__ : str = image.resize((int(round(scale * width ) ), int(round(scale * height ) )) ) return resized_image def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[int] = F.to_tensor(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = F.normalize(__lowerCAmelCase , mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ) return image @torch.no_grad() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Optional[Any]: logger.info("""Converting model...""" ) # load original state dict SCREAMING_SNAKE_CASE__ : str = torch.hub.load_state_dict_from_url(__lowerCAmelCase , map_location="""cpu""" ) # rename keys for src, dest in rename_keys: rename_key(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = rename_backbone_keys(__lowerCAmelCase ) # query, key and value matrices need special treatment read_in_q_k_v(__lowerCAmelCase ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them SCREAMING_SNAKE_CASE__ : Optional[int] = """model.""" for key in state_dict.copy().keys(): if not key.startswith("""class_labels_classifier""" ) and not key.startswith("""bbox_predictor""" ): SCREAMING_SNAKE_CASE__ : Optional[int] = state_dict.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = val # create HuggingFace model and load state dict SCREAMING_SNAKE_CASE__ : Tuple = TableTransformerConfig( backbone="""resnet18""" , mask_loss_coefficient=1 , dice_loss_coefficient=1 , ce_loss_coefficient=1 , bbox_loss_coefficient=5 , giou_loss_coefficient=2 , eos_coefficient=0.4 , class_cost=1 , bbox_cost=5 , giou_cost=2 , ) if "detection" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] = 15 SCREAMING_SNAKE_CASE__ : Any = 2 SCREAMING_SNAKE_CASE__ : str = {0: """table""", 1: """table rotated"""} SCREAMING_SNAKE_CASE__ : Union[str, Any] = idalabel SCREAMING_SNAKE_CASE__ : List[str] = {v: k for k, v in idalabel.items()} else: SCREAMING_SNAKE_CASE__ : Tuple = 125 SCREAMING_SNAKE_CASE__ : str = 6 SCREAMING_SNAKE_CASE__ : List[Any] = { 0: """table""", 1: """table column""", 2: """table row""", 3: """table column header""", 4: """table projected row header""", 5: """table spanning cell""", } SCREAMING_SNAKE_CASE__ : Any = idalabel SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Dict = DetrImageProcessor( format="""coco_detection""" , max_size=800 if """detection""" in checkpoint_url else 1000 ) SCREAMING_SNAKE_CASE__ : Tuple = TableTransformerForObjectDetection(__lowerCAmelCase ) model.load_state_dict(__lowerCAmelCase ) model.eval() # verify our conversion SCREAMING_SNAKE_CASE__ : Dict = """example_pdf.png""" if """detection""" in checkpoint_url else """example_table.png""" SCREAMING_SNAKE_CASE__ : Tuple = hf_hub_download(repo_id="""nielsr/example-pdf""" , repo_type="""dataset""" , filename=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = Image.open(__lowerCAmelCase ).convert("""RGB""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = normalize(resize(__lowerCAmelCase , __lowerCAmelCase ) ).unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : Dict = model(__lowerCAmelCase ) if "detection" in checkpoint_url: SCREAMING_SNAKE_CASE__ : List[Any] = (1, 15, 3) SCREAMING_SNAKE_CASE__ : str = torch.tensor( [[-6.7_897, -16.9_985, 6.7_937], [-8.0_186, -22.2_192, 6.9_677], [-7.3_117, -21.0_708, 7.4_055]] ) SCREAMING_SNAKE_CASE__ : str = torch.tensor([[0.4_867, 0.1_767, 0.6_732], [0.6_718, 0.4_479, 0.3_830], [0.4_716, 0.1_760, 0.6_364]] ) else: SCREAMING_SNAKE_CASE__ : Dict = (1, 125, 7) SCREAMING_SNAKE_CASE__ : Any = torch.tensor( [[-18.1_430, -8.3_214, 4.8_274], [-18.4_685, -7.1_361, -4.2_667], [-26.3_693, -9.3_429, -4.9_962]] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([[0.4_983, 0.5_595, 0.9_440], [0.4_916, 0.6_315, 0.5_954], [0.6_108, 0.8_637, 0.1_135]] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(F'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(__lowerCAmelCase ).mkdir(exist_ok=__lowerCAmelCase ) model.save_pretrained(__lowerCAmelCase ) image_processor.save_pretrained(__lowerCAmelCase ) if push_to_hub: # Push model to HF hub logger.info("""Pushing model to the hub...""" ) SCREAMING_SNAKE_CASE__ : List[Any] = ( """microsoft/table-transformer-detection""" if """detection""" in checkpoint_url else """microsoft/table-transformer-structure-recognition""" ) model.push_to_hub(__lowerCAmelCase ) image_processor.push_to_hub(__lowerCAmelCase ) if __name__ == "__main__": a :Any = argparse.ArgumentParser() parser.add_argument( "--checkpoint_url", default="https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth", type=str, choices=[ "https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth", "https://pubtables1m.blob.core.windows.net/model/pubtables1m_structure_detr_r18.pth", ], help="URL of the Table Transformer checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) a :int = parser.parse_args() convert_table_transformer_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
680
"""simple docstring""" import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Union[str, Path]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = True _SCREAMING_SNAKE_CASE :Optional[int] = None _SCREAMING_SNAKE_CASE :int = 1 _SCREAMING_SNAKE_CASE :Optional[Union[str, bool]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None def _a ( self ) -> "DownloadConfig": """simple docstring""" return self.__class__(**{k: copy.deepcopy(_a ) for k, v in self.__dict__.items()} )
680
1
"""simple docstring""" import argparse import fairseq import torch from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging logging.set_verbosity_info() a :Optional[int] = logging.get_logger(__name__) a :Tuple = { "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", "encoder.layer_norm_for_extract": "layer_norm_for_extract", "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": "lm_head", "label_embs_concat": "label_embeddings_concat", "mask_emb": "masked_spec_embed", "spk_proj": "speaker_proj", } a :Optional[Any] = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", "label_embeddings_concat", "speaker_proj", "layer_norm_for_extract", ] def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Tuple: for attribute in key.split(""".""" ): SCREAMING_SNAKE_CASE__ : str = getattr(__lowerCAmelCase , __lowerCAmelCase ) if weight_type is not None: SCREAMING_SNAKE_CASE__ : List[str] = getattr(__lowerCAmelCase , __lowerCAmelCase ).shape else: SCREAMING_SNAKE_CASE__ : 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": SCREAMING_SNAKE_CASE__ : Any = value elif weight_type == "weight_g": SCREAMING_SNAKE_CASE__ : Any = value elif weight_type == "weight_v": SCREAMING_SNAKE_CASE__ : List[Any] = value elif weight_type == "bias": SCREAMING_SNAKE_CASE__ : Union[str, Any] = value else: SCREAMING_SNAKE_CASE__ : Optional[int] = value logger.info(F'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.''' ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> List[Any]: SCREAMING_SNAKE_CASE__ : List[str] = [] SCREAMING_SNAKE_CASE__ : int = fairseq_model.state_dict() SCREAMING_SNAKE_CASE__ : Optional[int] = hf_model.unispeech_sat.feature_extractor for name, value in fairseq_dict.items(): SCREAMING_SNAKE_CASE__ : Optional[int] = False if "conv_layers" in name: load_conv_layer( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , hf_model.config.feat_extract_norm == """group""" , ) SCREAMING_SNAKE_CASE__ : Any = True else: for key, mapped_key in MAPPING.items(): SCREAMING_SNAKE_CASE__ : Any = """unispeech_sat.""" + 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]: if "layer_norm_for_extract" in name and (".".join(name.split(""".""" )[:-1] ) != key): # special case since naming is very similar continue SCREAMING_SNAKE_CASE__ : List[Any] = True if "*" in mapped_key: SCREAMING_SNAKE_CASE__ : List[str] = name.split(__lowerCAmelCase )[0].split(""".""" )[-2] SCREAMING_SNAKE_CASE__ : Dict = mapped_key.replace("""*""" , __lowerCAmelCase ) if "weight_g" in name: SCREAMING_SNAKE_CASE__ : List[str] = """weight_g""" elif "weight_v" in name: SCREAMING_SNAKE_CASE__ : Optional[int] = """weight_v""" elif "bias" in name: SCREAMING_SNAKE_CASE__ : Any = """bias""" elif "weight" in name: # TODO: don't match quantizer.weight_proj SCREAMING_SNAKE_CASE__ : Optional[Any] = """weight""" else: SCREAMING_SNAKE_CASE__ : Optional[Any] = None set_recursively(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) continue if not is_used: unused_weights.append(__lowerCAmelCase ) logger.warning(F'''Unused weights: {unused_weights}''' ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Any: SCREAMING_SNAKE_CASE__ : Optional[int] = full_name.split("""conv_layers.""" )[-1] SCREAMING_SNAKE_CASE__ : Any = name.split(""".""" ) SCREAMING_SNAKE_CASE__ : List[Any] = int(items[0] ) SCREAMING_SNAKE_CASE__ : List[str] = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) SCREAMING_SNAKE_CASE__ : int = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 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: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor[layer_id].layer_norm.bias.data.shape} was found.''' ) SCREAMING_SNAKE_CASE__ : Tuple = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(__lowerCAmelCase ) @torch.no_grad() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=True ) -> Tuple: if config_path is not None: SCREAMING_SNAKE_CASE__ : List[str] = UniSpeechSatConfig.from_pretrained(__lowerCAmelCase ) else: SCREAMING_SNAKE_CASE__ : int = UniSpeechSatConfig() SCREAMING_SNAKE_CASE__ : Optional[int] = """""" if is_finetuned: SCREAMING_SNAKE_CASE__ : str = UniSpeechSatForCTC(__lowerCAmelCase ) else: SCREAMING_SNAKE_CASE__ : List[str] = UniSpeechSatForPreTraining(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) SCREAMING_SNAKE_CASE__ : Tuple = model[0].eval() recursively_load_weights(__lowerCAmelCase , __lowerCAmelCase ) hf_wavavec.save_pretrained(__lowerCAmelCase ) if __name__ == "__main__": a :List[str] = 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" ) a :Optional[Any] = parser.parse_args() convert_unispeech_sat_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
680
"""simple docstring""" import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger a :Optional[Any] = "<<<<<<< This should probably be modified because it mentions: " a :Tuple = "=======\n>>>>>>>\n" a :str = [ "TextEncoderConfig", "ByteTextEncoder", "SubwordTextEncoder", "encoder_config", "maybe_build_from_corpus", "manual_dir", ] a :Union[str, Any] = [ # (pattern, replacement) # Order is important here for some replacements (r"tfds\.core", r"datasets"), (r"tf\.io\.gfile\.GFile", r"open"), (r"tf\.([\w\d]+)", r"datasets.Value('\1')"), (r"tfds\.features\.Text\(\)", r"datasets.Value('string')"), (r"tfds\.features\.Text\(", r"datasets.Value('string'),"), (r"features\s*=\s*tfds.features.FeaturesDict\(", r"features=datasets.Features("), (r"tfds\.features\.FeaturesDict\(", r"dict("), (r"The TensorFlow Datasets Authors", r"The TensorFlow Datasets Authors and the HuggingFace Datasets Authors"), (r"tfds\.", r"datasets."), (r"dl_manager\.manual_dir", r"self.config.data_dir"), (r"self\.builder_config", r"self.config"), ] def _lowercase ( __lowerCAmelCase ) -> int: return ConvertCommand(args.tfds_path , args.datasets_directory ) class __a (UpperCamelCase_): '''simple docstring''' @staticmethod def _a ( _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.add_parser( """convert""" , help="""Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.""" , ) train_parser.add_argument( """--tfds_path""" , type=_a , required=_a , help="""Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.""" , ) train_parser.add_argument( """--datasets_directory""" , type=_a , required=_a , help="""Path to the HuggingFace Datasets folder.""" ) train_parser.set_defaults(func=_a ) def __init__( self , _a , _a , *_a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = get_logger("""datasets-cli/converting""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tfds_path SCREAMING_SNAKE_CASE__ : List[Any] = datasets_directory def _a ( self ) -> List[str]: """simple docstring""" if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.abspath(self._tfds_path ) elif os.path.isfile(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Tuple = os.path.dirname(self._tfds_path ) else: raise ValueError("""--tfds_path is neither a directory nor a file. Please check path.""" ) SCREAMING_SNAKE_CASE__ : Dict = os.path.abspath(self._datasets_directory ) self._logger.info(f'''Converting datasets from {abs_tfds_path} to {abs_datasets_path}''' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : List[Any] = {} if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.listdir(_a ) else: SCREAMING_SNAKE_CASE__ : List[Any] = [os.path.basename(self._tfds_path )] for f_name in file_names: self._logger.info(f'''Looking at file {f_name}''' ) SCREAMING_SNAKE_CASE__ : int = os.path.join(_a , _a ) SCREAMING_SNAKE_CASE__ : Dict = os.path.join(_a , _a ) if not os.path.isfile(_a ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info("""Skipping file""" ) continue with open(_a , encoding="""utf-8""" ) as f: SCREAMING_SNAKE_CASE__ : List[str] = f.readlines() SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = False SCREAMING_SNAKE_CASE__ : Optional[int] = False SCREAMING_SNAKE_CASE__ : Dict = [] for line in lines: SCREAMING_SNAKE_CASE__ : List[str] = line # Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: SCREAMING_SNAKE_CASE__ : List[Any] = """import datasets\n""" elif "import tensorflow" in out_line: # order is important here SCREAMING_SNAKE_CASE__ : Optional[Any] = """""" continue elif "from absl import logging" in out_line: SCREAMING_SNAKE_CASE__ : Any = """from datasets import logging\n""" elif "getLogger" in out_line: SCREAMING_SNAKE_CASE__ : Optional[int] = out_line.replace("""getLogger""" , """get_logger""" ) elif any(expression in out_line for expression in TO_HIGHLIGHT ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Tuple = list(filter(lambda _a : e in out_line , _a ) ) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(_a ) + """\n""" ) out_lines.append(_a ) out_lines.append(_a ) continue else: for pattern, replacement in TO_CONVERT: SCREAMING_SNAKE_CASE__ : int = re.sub(_a , _a , _a ) # Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: SCREAMING_SNAKE_CASE__ : Dict = re.match(r"""from\stensorflow_datasets.*import\s([^\.\r\n]+)""" , _a ) tfds_imports.extend(imp.strip() for imp in match.group(1 ).split(""",""" ) ) SCREAMING_SNAKE_CASE__ : Dict = """from . import """ + match.group(1 ) # Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(f'''Error converting {out_line.strip()}''' ) if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line: SCREAMING_SNAKE_CASE__ : Union[str, Any] = True out_lines.append(_a ) if is_builder or "wmt" in f_name: # We create a new directory for each dataset SCREAMING_SNAKE_CASE__ : Union[str, Any] = f_name.replace(""".py""" , """""" ) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(_a , _a ) SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(_a , _a ) os.makedirs(_a , exist_ok=_a ) self._logger.info(f'''Adding directory {output_dir}''' ) imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} ) else: # Utilities will be moved at the end utils_files.append(_a ) if needs_manual_update: with_manual_update.append(_a ) with open(_a , """w""" , encoding="""utf-8""" ) as f: f.writelines(_a ) self._logger.info(f'''Converted in {output_file}''' ) for utils_file in utils_files: try: SCREAMING_SNAKE_CASE__ : str = os.path.basename(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = imports_to_builder_map[f_name.replace(""".py""" , """""" )] self._logger.info(f'''Moving {dest_folder} to {utils_file}''' ) shutil.copy(_a , _a ) except KeyError: self._logger.error(f'''Cannot find destination folder for {utils_file}. Please copy manually.''' ) if with_manual_update: for file_path in with_manual_update: self._logger.warning( f'''You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.''' )
680
1
"""simple docstring""" import math from typing import Optional import numpy as np from ...configuration_utils import PretrainedConfig from ...utils import logging a :Tuple = logging.get_logger(__name__) a :Dict = { "facebook/encodec_24khz": "https://huggingface.co/facebook/encodec_24khz/resolve/main/config.json", "facebook/encodec_48khz": "https://huggingface.co/facebook/encodec_48khz/resolve/main/config.json", } class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = """encodec""" def __init__( self , _a=[1.5, 3.0, 6.0, 12.0, 24.0] , _a=24_000 , _a=1 , _a=False , _a=None , _a=None , _a=128 , _a=32 , _a=1 , _a=[8, 5, 4, 2] , _a="weight_norm" , _a=7 , _a=7 , _a=3 , _a=2 , _a=True , _a="reflect" , _a=2 , _a=2 , _a=1.0 , _a=1_024 , _a=None , _a=True , **_a , ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = target_bandwidths SCREAMING_SNAKE_CASE__ : Union[str, Any] = sampling_rate SCREAMING_SNAKE_CASE__ : Optional[Any] = audio_channels SCREAMING_SNAKE_CASE__ : Any = normalize SCREAMING_SNAKE_CASE__ : Any = chunk_length_s SCREAMING_SNAKE_CASE__ : Optional[int] = overlap SCREAMING_SNAKE_CASE__ : int = hidden_size SCREAMING_SNAKE_CASE__ : str = num_filters SCREAMING_SNAKE_CASE__ : Any = num_residual_layers SCREAMING_SNAKE_CASE__ : Optional[Any] = upsampling_ratios SCREAMING_SNAKE_CASE__ : Optional[Any] = norm_type SCREAMING_SNAKE_CASE__ : int = kernel_size SCREAMING_SNAKE_CASE__ : Dict = last_kernel_size SCREAMING_SNAKE_CASE__ : str = residual_kernel_size SCREAMING_SNAKE_CASE__ : str = dilation_growth_rate SCREAMING_SNAKE_CASE__ : List[Any] = use_causal_conv SCREAMING_SNAKE_CASE__ : Dict = pad_mode SCREAMING_SNAKE_CASE__ : Union[str, Any] = compress SCREAMING_SNAKE_CASE__ : Tuple = num_lstm_layers SCREAMING_SNAKE_CASE__ : Optional[int] = trim_right_ratio SCREAMING_SNAKE_CASE__ : List[Any] = codebook_size SCREAMING_SNAKE_CASE__ : List[str] = codebook_dim if codebook_dim is not None else hidden_size SCREAMING_SNAKE_CASE__ : Dict = use_conv_shortcut if self.norm_type not in ["weight_norm", "time_group_norm"]: raise ValueError( f'''self.norm_type must be one of `"weight_norm"`, `"time_group_norm"`), got {self.norm_type}''' ) super().__init__(**_a ) @property def _a ( self ) -> Optional[int]: """simple docstring""" if self.chunk_length_s is None: return None else: return int(self.chunk_length_s * self.sampling_rate ) @property def _a ( self ) -> Optional[int]: """simple docstring""" if self.chunk_length_s is None or self.overlap is None: return None else: return max(1 , int((1.0 - self.overlap) * self.chunk_length ) ) @property def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.prod(self.upsampling_ratios ) return math.ceil(self.sampling_rate / hop_length ) @property def _a ( self ) -> int: """simple docstring""" return int(1_000 * self.target_bandwidths[-1] // (self.frame_rate * 10) )
680
"""simple docstring""" from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance a :str = 637_8137.0 a :Optional[Any] = 635_6752.31_4245 a :List[Any] = 6_378_137 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> float: SCREAMING_SNAKE_CASE__ : Dict = (AXIS_A - AXIS_B) / AXIS_A # Parametric latitudes # https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) # Compute central angle between two points # using haversine theta. sigma = haversine_distance / equatorial radius SCREAMING_SNAKE_CASE__ : Tuple = haversine_distance(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) / EQUATORIAL_RADIUS # Intermediate P and Q values SCREAMING_SNAKE_CASE__ : List[str] = (b_lata + b_lata) / 2 SCREAMING_SNAKE_CASE__ : Dict = (b_lata - b_lata) / 2 # Intermediate X value # X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2) SCREAMING_SNAKE_CASE__ : Tuple = (sin(__lowerCAmelCase ) ** 2) * (cos(__lowerCAmelCase ) ** 2) SCREAMING_SNAKE_CASE__ : str = cos(sigma / 2 ) ** 2 SCREAMING_SNAKE_CASE__ : List[str] = (sigma - sin(__lowerCAmelCase )) * (x_numerator / x_demonimator) # Intermediate Y value # Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2) SCREAMING_SNAKE_CASE__ : int = (cos(__lowerCAmelCase ) ** 2) * (sin(__lowerCAmelCase ) ** 2) SCREAMING_SNAKE_CASE__ : int = sin(sigma / 2 ) ** 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = (sigma + sin(__lowerCAmelCase )) * (y_numerator / y_denominator) return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value))) if __name__ == "__main__": import doctest doctest.testmod()
680
1
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot import BlenderbotTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation a :Union[str, Any] = logging.get_logger(__name__) a :Optional[int] = { "vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_config_file": "tokenizer_config.json", } a :Optional[int] = { "vocab_file": {"facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json"}, "merges_file": {"facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt"}, "tokenizer_config_file": { "facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json" }, } a :List[Any] = {"facebook/blenderbot-3B": 128} class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :str = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE :List[str] = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE :Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE :Any = ["""input_ids""", """attention_mask"""] _SCREAMING_SNAKE_CASE :List[str] = BlenderbotTokenizer def __init__( self , _a=None , _a=None , _a=None , _a="replace" , _a="<s>" , _a="</s>" , _a="</s>" , _a="<s>" , _a="<unk>" , _a="<pad>" , _a="<mask>" , _a=False , _a=True , **_a , ) -> int: """simple docstring""" super().__init__( _a , _a , tokenizer_file=_a , errors=_a , bos_token=_a , eos_token=_a , sep_token=_a , cls_token=_a , unk_token=_a , pad_token=_a , mask_token=_a , add_prefix_space=_a , trim_offsets=_a , **_a , ) SCREAMING_SNAKE_CASE__ : Dict = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""" , _a ) != add_prefix_space: SCREAMING_SNAKE_CASE__ : List[str] = getattr(_a , pre_tok_state.pop("""type""" ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = add_prefix_space SCREAMING_SNAKE_CASE__ : List[str] = pre_tok_class(**_a ) SCREAMING_SNAKE_CASE__ : int = add_prefix_space SCREAMING_SNAKE_CASE__ : List[Any] = """post_processor""" SCREAMING_SNAKE_CASE__ : Optional[Any] = getattr(self.backend_tokenizer , _a , _a ) if tokenizer_component_instance: SCREAMING_SNAKE_CASE__ : Tuple = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: SCREAMING_SNAKE_CASE__ : int = tuple(state["""sep"""] ) if "cls" in state: SCREAMING_SNAKE_CASE__ : Optional[int] = tuple(state["""cls"""] ) SCREAMING_SNAKE_CASE__ : Any = False if state.get("""add_prefix_space""" , _a ) != add_prefix_space: SCREAMING_SNAKE_CASE__ : Union[str, Any] = add_prefix_space SCREAMING_SNAKE_CASE__ : Dict = True if state.get("""trim_offsets""" , _a ) != trim_offsets: SCREAMING_SNAKE_CASE__ : int = trim_offsets SCREAMING_SNAKE_CASE__ : int = True if changes_to_apply: SCREAMING_SNAKE_CASE__ : Optional[int] = getattr(_a , state.pop("""type""" ) ) SCREAMING_SNAKE_CASE__ : str = component_class(**_a ) setattr(self.backend_tokenizer , _a , _a ) @property # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast.mask_token with Roberta->Blenderbot, RoBERTa->Blenderbot def _a ( self ) -> str: """simple docstring""" if self._mask_token is None: if self.verbose: logger.error("""Using mask_token, but it is not set yet.""" ) return None return str(self._mask_token ) @mask_token.setter def _a ( self , _a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else value SCREAMING_SNAKE_CASE__ : List[Any] = value def _a ( self , *_a , **_a ) -> BatchEncoding: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = kwargs.get("""is_split_into_words""" , _a ) assert self.add_prefix_space or not is_split_into_words, ( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*_a , **_a ) def _a ( self , *_a , **_a ) -> BatchEncoding: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = kwargs.get("""is_split_into_words""" , _a ) assert self.add_prefix_space or not is_split_into_words, ( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' "to use it with pretokenized inputs." ) return super()._encode_plus(*_a , **_a ) def _a ( self , _a , _a = None ) -> Tuple[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self._tokenizer.model.save(_a , name=_a ) return tuple(_a ) def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : 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 _a ( self , _a , _a = None ) -> int: """simple docstring""" return token_ids_a + [self.eos_token_id] def _a ( self , _a ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = [] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(""" """ + text ) else: # Generated responses should contain them already. inputs.append(_a ) SCREAMING_SNAKE_CASE__ : Any = """ """.join(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.encode(_a ) if len(_a ) > self.model_max_length: SCREAMING_SNAKE_CASE__ : int = input_ids[-self.model_max_length :] logger.warning(f'''Trimmed input from conversation as it was longer than {self.model_max_length} tokens.''' ) return input_ids
680
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision.transforms import functional as F from transformers import DetrImageProcessor, TableTransformerConfig, TableTransformerForObjectDetection from transformers.utils import logging logging.set_verbosity_info() a :Any = logging.get_logger(__name__) # here we list all keys to be renamed (original name on the left, our name on the right) a :str = [] for i in range(6): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (f'transformer.encoder.layers.{i}.self_attn.out_proj.weight', f'encoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (f'transformer.encoder.layers.{i}.self_attn.out_proj.bias', f'encoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append((f'transformer.encoder.layers.{i}.linear1.weight', f'encoder.layers.{i}.fc1.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.linear1.bias', f'encoder.layers.{i}.fc1.bias')) rename_keys.append((f'transformer.encoder.layers.{i}.linear2.weight', f'encoder.layers.{i}.fc2.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.linear2.bias', f'encoder.layers.{i}.fc2.bias')) rename_keys.append( (f'transformer.encoder.layers.{i}.norm1.weight', f'encoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((f'transformer.encoder.layers.{i}.norm1.bias', f'encoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append((f'transformer.encoder.layers.{i}.norm2.weight', f'encoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.norm2.bias', f'encoder.layers.{i}.final_layer_norm.bias')) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( (f'transformer.decoder.layers.{i}.self_attn.out_proj.weight', f'decoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (f'transformer.decoder.layers.{i}.self_attn.out_proj.bias', f'decoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append( ( f'transformer.decoder.layers.{i}.multihead_attn.out_proj.weight', f'decoder.layers.{i}.encoder_attn.out_proj.weight', ) ) rename_keys.append( ( f'transformer.decoder.layers.{i}.multihead_attn.out_proj.bias', f'decoder.layers.{i}.encoder_attn.out_proj.bias', ) ) rename_keys.append((f'transformer.decoder.layers.{i}.linear1.weight', f'decoder.layers.{i}.fc1.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.linear1.bias', f'decoder.layers.{i}.fc1.bias')) rename_keys.append((f'transformer.decoder.layers.{i}.linear2.weight', f'decoder.layers.{i}.fc2.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.linear2.bias', f'decoder.layers.{i}.fc2.bias')) rename_keys.append( (f'transformer.decoder.layers.{i}.norm1.weight', f'decoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((f'transformer.decoder.layers.{i}.norm1.bias', f'decoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append( (f'transformer.decoder.layers.{i}.norm2.weight', f'decoder.layers.{i}.encoder_attn_layer_norm.weight') ) rename_keys.append( (f'transformer.decoder.layers.{i}.norm2.bias', f'decoder.layers.{i}.encoder_attn_layer_norm.bias') ) rename_keys.append((f'transformer.decoder.layers.{i}.norm3.weight', f'decoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.norm3.bias', f'decoder.layers.{i}.final_layer_norm.bias')) # convolutional projection + query embeddings + layernorm of encoder + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ("input_proj.weight", "input_projection.weight"), ("input_proj.bias", "input_projection.bias"), ("query_embed.weight", "query_position_embeddings.weight"), ("transformer.encoder.norm.weight", "encoder.layernorm.weight"), ("transformer.encoder.norm.bias", "encoder.layernorm.bias"), ("transformer.decoder.norm.weight", "decoder.layernorm.weight"), ("transformer.decoder.norm.bias", "decoder.layernorm.bias"), ("class_embed.weight", "class_labels_classifier.weight"), ("class_embed.bias", "class_labels_classifier.bias"), ("bbox_embed.layers.0.weight", "bbox_predictor.layers.0.weight"), ("bbox_embed.layers.0.bias", "bbox_predictor.layers.0.bias"), ("bbox_embed.layers.1.weight", "bbox_predictor.layers.1.weight"), ("bbox_embed.layers.1.bias", "bbox_predictor.layers.1.bias"), ("bbox_embed.layers.2.weight", "bbox_predictor.layers.2.weight"), ("bbox_embed.layers.2.bias", "bbox_predictor.layers.2.bias"), ] ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Tuple = state_dict.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = val def _lowercase ( __lowerCAmelCase ) -> Tuple: SCREAMING_SNAKE_CASE__ : str = OrderedDict() for key, value in state_dict.items(): if "backbone.0.body" in key: SCREAMING_SNAKE_CASE__ : List[Any] = key.replace("""backbone.0.body""" , """backbone.conv_encoder.model""" ) SCREAMING_SNAKE_CASE__ : Dict = value else: SCREAMING_SNAKE_CASE__ : Tuple = value return new_state_dict def _lowercase ( __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : str = """""" # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : int = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : int = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE__ : Any = in_proj_bias[:256] SCREAMING_SNAKE_CASE__ : Dict = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[256:512] SCREAMING_SNAKE_CASE__ : int = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[-256:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6 ): # read in weights + bias of input projection layer of self-attention SCREAMING_SNAKE_CASE__ : List[str] = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : Tuple = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Any = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[:256] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[256:512] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias[-256:] # read in weights + bias of input projection layer of cross-attention SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop( F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : List[Any] = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) of cross-attention to the state dict SCREAMING_SNAKE_CASE__ : int = in_proj_weight_cross_attn[:256, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias_cross_attn[:256] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight_cross_attn[256:512, :] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_bias_cross_attn[256:512] SCREAMING_SNAKE_CASE__ : int = in_proj_weight_cross_attn[-256:, :] SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias_cross_attn[-256:] def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = image.size SCREAMING_SNAKE_CASE__ : Optional[Any] = max(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = 800 if """detection""" in checkpoint_url else 1000 SCREAMING_SNAKE_CASE__ : List[str] = target_max_size / current_max_size SCREAMING_SNAKE_CASE__ : str = image.resize((int(round(scale * width ) ), int(round(scale * height ) )) ) return resized_image def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[int] = F.to_tensor(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = F.normalize(__lowerCAmelCase , mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ) return image @torch.no_grad() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Optional[Any]: logger.info("""Converting model...""" ) # load original state dict SCREAMING_SNAKE_CASE__ : str = torch.hub.load_state_dict_from_url(__lowerCAmelCase , map_location="""cpu""" ) # rename keys for src, dest in rename_keys: rename_key(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = rename_backbone_keys(__lowerCAmelCase ) # query, key and value matrices need special treatment read_in_q_k_v(__lowerCAmelCase ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them SCREAMING_SNAKE_CASE__ : Optional[int] = """model.""" for key in state_dict.copy().keys(): if not key.startswith("""class_labels_classifier""" ) and not key.startswith("""bbox_predictor""" ): SCREAMING_SNAKE_CASE__ : Optional[int] = state_dict.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = val # create HuggingFace model and load state dict SCREAMING_SNAKE_CASE__ : Tuple = TableTransformerConfig( backbone="""resnet18""" , mask_loss_coefficient=1 , dice_loss_coefficient=1 , ce_loss_coefficient=1 , bbox_loss_coefficient=5 , giou_loss_coefficient=2 , eos_coefficient=0.4 , class_cost=1 , bbox_cost=5 , giou_cost=2 , ) if "detection" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] = 15 SCREAMING_SNAKE_CASE__ : Any = 2 SCREAMING_SNAKE_CASE__ : str = {0: """table""", 1: """table rotated"""} SCREAMING_SNAKE_CASE__ : Union[str, Any] = idalabel SCREAMING_SNAKE_CASE__ : List[str] = {v: k for k, v in idalabel.items()} else: SCREAMING_SNAKE_CASE__ : Tuple = 125 SCREAMING_SNAKE_CASE__ : str = 6 SCREAMING_SNAKE_CASE__ : List[Any] = { 0: """table""", 1: """table column""", 2: """table row""", 3: """table column header""", 4: """table projected row header""", 5: """table spanning cell""", } SCREAMING_SNAKE_CASE__ : Any = idalabel SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Dict = DetrImageProcessor( format="""coco_detection""" , max_size=800 if """detection""" in checkpoint_url else 1000 ) SCREAMING_SNAKE_CASE__ : Tuple = TableTransformerForObjectDetection(__lowerCAmelCase ) model.load_state_dict(__lowerCAmelCase ) model.eval() # verify our conversion SCREAMING_SNAKE_CASE__ : Dict = """example_pdf.png""" if """detection""" in checkpoint_url else """example_table.png""" SCREAMING_SNAKE_CASE__ : Tuple = hf_hub_download(repo_id="""nielsr/example-pdf""" , repo_type="""dataset""" , filename=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = Image.open(__lowerCAmelCase ).convert("""RGB""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = normalize(resize(__lowerCAmelCase , __lowerCAmelCase ) ).unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : Dict = model(__lowerCAmelCase ) if "detection" in checkpoint_url: SCREAMING_SNAKE_CASE__ : List[Any] = (1, 15, 3) SCREAMING_SNAKE_CASE__ : str = torch.tensor( [[-6.7_897, -16.9_985, 6.7_937], [-8.0_186, -22.2_192, 6.9_677], [-7.3_117, -21.0_708, 7.4_055]] ) SCREAMING_SNAKE_CASE__ : str = torch.tensor([[0.4_867, 0.1_767, 0.6_732], [0.6_718, 0.4_479, 0.3_830], [0.4_716, 0.1_760, 0.6_364]] ) else: SCREAMING_SNAKE_CASE__ : Dict = (1, 125, 7) SCREAMING_SNAKE_CASE__ : Any = torch.tensor( [[-18.1_430, -8.3_214, 4.8_274], [-18.4_685, -7.1_361, -4.2_667], [-26.3_693, -9.3_429, -4.9_962]] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([[0.4_983, 0.5_595, 0.9_440], [0.4_916, 0.6_315, 0.5_954], [0.6_108, 0.8_637, 0.1_135]] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(F'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(__lowerCAmelCase ).mkdir(exist_ok=__lowerCAmelCase ) model.save_pretrained(__lowerCAmelCase ) image_processor.save_pretrained(__lowerCAmelCase ) if push_to_hub: # Push model to HF hub logger.info("""Pushing model to the hub...""" ) SCREAMING_SNAKE_CASE__ : List[Any] = ( """microsoft/table-transformer-detection""" if """detection""" in checkpoint_url else """microsoft/table-transformer-structure-recognition""" ) model.push_to_hub(__lowerCAmelCase ) image_processor.push_to_hub(__lowerCAmelCase ) if __name__ == "__main__": a :Any = argparse.ArgumentParser() parser.add_argument( "--checkpoint_url", default="https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth", type=str, choices=[ "https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth", "https://pubtables1m.blob.core.windows.net/model/pubtables1m_structure_detr_r18.pth", ], help="URL of the Table Transformer checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) a :int = parser.parse_args() convert_table_transformer_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
680
1
"""simple docstring""" import argparse import logging import pickle import random import time import numpy as np from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) a :str = logging.getLogger(__name__) def _lowercase ( ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Dict = argparse.ArgumentParser( description="""Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids).""" ) parser.add_argument("""--file_path""" , type=__lowerCAmelCase , default="""data/dump.txt""" , help="""The path to the data.""" ) parser.add_argument("""--tokenizer_type""" , type=__lowerCAmelCase , default="""bert""" , choices=["""bert""", """roberta""", """gpt2"""] ) parser.add_argument("""--tokenizer_name""" , type=__lowerCAmelCase , default="""bert-base-uncased""" , help="""The tokenizer to use.""" ) parser.add_argument("""--dump_file""" , type=__lowerCAmelCase , default="""data/dump""" , help="""The dump file prefix.""" ) SCREAMING_SNAKE_CASE__ : str = parser.parse_args() logger.info(F'''Loading Tokenizer ({args.tokenizer_name})''' ) if args.tokenizer_type == "bert": SCREAMING_SNAKE_CASE__ : List[str] = BertTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : str = tokenizer.special_tokens_map["""cls_token"""] # `[CLS]` SCREAMING_SNAKE_CASE__ : str = tokenizer.special_tokens_map["""sep_token"""] # `[SEP]` elif args.tokenizer_type == "roberta": SCREAMING_SNAKE_CASE__ : List[Any] = RobertaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.special_tokens_map["""cls_token"""] # `<s>` SCREAMING_SNAKE_CASE__ : Dict = tokenizer.special_tokens_map["""sep_token"""] # `</s>` elif args.tokenizer_type == "gpt2": SCREAMING_SNAKE_CASE__ : List[Any] = GPTaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.special_tokens_map["""bos_token"""] # `<|endoftext|>` SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.special_tokens_map["""eos_token"""] # `<|endoftext|>` logger.info(F'''Loading text from {args.file_path}''' ) with open(args.file_path , """r""" , encoding="""utf8""" ) as fp: SCREAMING_SNAKE_CASE__ : int = fp.readlines() logger.info("""Start encoding""" ) logger.info(F'''{len(__lowerCAmelCase )} examples to process.''' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1_0000 SCREAMING_SNAKE_CASE__ : Dict = time.time() for text in data: SCREAMING_SNAKE_CASE__ : Dict = F'''{bos} {text.strip()} {sep}''' SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) rslt.append(__lowerCAmelCase ) iter += 1 if iter % interval == 0: SCREAMING_SNAKE_CASE__ : str = time.time() logger.info(F'''{iter} examples processed. - {(end-start):.2f}s/{interval}expl''' ) SCREAMING_SNAKE_CASE__ : Tuple = time.time() logger.info("""Finished binarization""" ) logger.info(F'''{len(__lowerCAmelCase )} examples processed.''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = F'''{args.dump_file}.{args.tokenizer_name}.pickle''' SCREAMING_SNAKE_CASE__ : Dict = tokenizer.vocab_size if vocab_size < (1 << 16): SCREAMING_SNAKE_CASE__ : Tuple = [np.uintaa(__lowerCAmelCase ) for d in rslt] else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [np.intaa(__lowerCAmelCase ) for d in rslt] random.shuffle(rslt_ ) logger.info(F'''Dump to {dp_file}''' ) with open(__lowerCAmelCase , """wb""" ) as handle: pickle.dump(rslt_ , __lowerCAmelCase , protocol=pickle.HIGHEST_PROTOCOL ) if __name__ == "__main__": main()
680
"""simple docstring""" from __future__ import annotations import unittest from transformers import 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, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers import ( TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, BertConfig, DPRConfig, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) class __a : '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=2 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , _a=0 , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : str = seq_length SCREAMING_SNAKE_CASE__ : List[str] = is_training SCREAMING_SNAKE_CASE__ : List[str] = use_input_mask SCREAMING_SNAKE_CASE__ : Dict = use_token_type_ids SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE__ : Dict = hidden_size SCREAMING_SNAKE_CASE__ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE__ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : str = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Any = type_vocab_size SCREAMING_SNAKE_CASE__ : int = type_sequence_label_size SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : Any = num_labels SCREAMING_SNAKE_CASE__ : Dict = num_choices SCREAMING_SNAKE_CASE__ : Any = scope SCREAMING_SNAKE_CASE__ : int = projection_dim def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : str = None if self.use_input_mask: # follow test_modeling_tf_ctrl.py SCREAMING_SNAKE_CASE__ : str = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : Any = BertConfig( 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 , ) SCREAMING_SNAKE_CASE__ : str = DPRConfig(projection_dim=self.projection_dim , **config.to_dict() ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRContextEncoder(config=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , attention_mask=_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : str = model(_a ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = TFDPRQuestionEncoder(config=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_a , attention_mask=_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : List[str] = model(_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(_a ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = TFDPRReader(config=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , attention_mask=_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) ) self.parent.assertEqual(result.relevance_logits.shape , (self.batch_size,) ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE__ : int = {"""input_ids""": input_ids} return config, inputs_dict @require_tf class __a (UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = ( ( TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) if is_tf_available() else () ) _SCREAMING_SNAKE_CASE :int = {"""feature-extraction""": TFDPRQuestionEncoder} if is_tf_available() else {} _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = False _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :Dict = False def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFDPRModelTester(self ) SCREAMING_SNAKE_CASE__ : List[str] = ConfigTester(self , config_class=_a , hidden_size=37 ) def _a ( self ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_context_encoder(*_a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_question_encoder(*_a ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_reader(*_a ) @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRContextEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[int] = TFDPRContextEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = TFDPRQuestionEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRReader.from_pretrained(_a ) self.assertIsNotNone(_a ) @require_tf class __a (unittest.TestCase): '''simple docstring''' @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFDPRQuestionEncoder.from_pretrained("""facebook/dpr-question_encoder-single-nq-base""" ) SCREAMING_SNAKE_CASE__ : List[Any] = tf.constant( [[101, 7_592, 1_010, 2_003, 2_026, 3_899, 10_140, 1_029, 102]] ) # [CLS] hello, is my dog cute? [SEP] SCREAMING_SNAKE_CASE__ : Tuple = model(_a )[0] # embedding shape = (1, 768) # compare the actual values for a slice. SCREAMING_SNAKE_CASE__ : Any = tf.constant( [ [ 0.03_236_253, 0.12_753_335, 0.16_818_509, 0.00_279_786, 0.3_896_933, 0.24_264_945, 0.2_178_971, -0.02_335_227, -0.08_481_959, -0.14_324_117, ] ] ) self.assertTrue(numpy.allclose(output[:, :10].numpy() , expected_slice.numpy() , atol=1E-4 ) )
680
1
"""simple docstring""" from functools import lru_cache @lru_cache def _lowercase ( __lowerCAmelCase ) -> int: if num < 0: raise ValueError("""Number should not be negative.""" ) return 1 if num in (0, 1) else num * factorial(num - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
680
"""simple docstring""" # DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion # and https://github.com/hojonathanho/diffusion import math from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.schedulers.scheduling_utils import SchedulerMixin from diffusers.utils import BaseOutput, deprecate @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :torch.FloatTensor _SCREAMING_SNAKE_CASE :Optional[torch.FloatTensor] = None def _lowercase ( __lowerCAmelCase , __lowerCAmelCase=0.999 , __lowerCAmelCase="cosine" , ) -> Union[str, Any]: if alpha_transform_type == "cosine": def alpha_bar_fn(__lowerCAmelCase ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(__lowerCAmelCase ): return math.exp(t * -12.0 ) else: raise ValueError(F'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) SCREAMING_SNAKE_CASE__ : List[Any] = [] for i in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = i / num_diffusion_timesteps SCREAMING_SNAKE_CASE__ : int = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(__lowerCAmelCase ) / alpha_bar_fn(__lowerCAmelCase ) , __lowerCAmelCase ) ) return torch.tensor(__lowerCAmelCase , dtype=torch.floataa ) class __a (UpperCamelCase_ , UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = 1 @register_to_config def __init__( self , _a = 1_000 , _a = 0.0_001 , _a = 0.02 , _a = "linear" , _a = None , _a = True , _a = True , _a = 0 , _a = "epsilon" , _a = 1.0 , **_a , ) -> Dict: """simple docstring""" if kwargs.get("""set_alpha_to_one""" , _a ) is not None: SCREAMING_SNAKE_CASE__ : Tuple = ( """The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead.""" ) deprecate("""set_alpha_to_one""" , """1.0.0""" , _a , standard_warn=_a ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs["""set_alpha_to_one"""] if trained_betas is not None: SCREAMING_SNAKE_CASE__ : Dict = torch.tensor(_a , dtype=torch.floataa ) elif beta_schedule == "linear": SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.linspace(_a , _a , _a , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. SCREAMING_SNAKE_CASE__ : Optional[int] = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , _a , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule SCREAMING_SNAKE_CASE__ : Tuple = betas_for_alpha_bar(_a ) else: raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = 1.0 - self.betas SCREAMING_SNAKE_CASE__ : List[Any] = torch.cumprod(self.alphas , dim=0 ) # At every step in inverted ddim, we are looking into the next alphas_cumprod # For the final step, there is no next alphas_cumprod, and the index is out of bounds # `set_alpha_to_zero` decides whether we set this parameter simply to zero # in this case, self.step() just output the predicted noise # or whether we use the final alpha of the "non-previous" one. SCREAMING_SNAKE_CASE__ : Any = torch.tensor(0.0 ) if set_alpha_to_zero else self.alphas_cumprod[-1] # standard deviation of the initial noise distribution SCREAMING_SNAKE_CASE__ : Tuple = 1.0 # setable values SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : List[str] = torch.from_numpy(np.arange(0 , _a ).copy().astype(np.intaa ) ) def _a ( self , _a , _a = None ) -> torch.FloatTensor: """simple docstring""" return sample def _a ( self , _a , _a = None ) -> Optional[int]: """simple docstring""" if num_inference_steps > self.config.num_train_timesteps: raise ValueError( f'''`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:''' f''' {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle''' f''' maximal {self.config.num_train_timesteps} timesteps.''' ) SCREAMING_SNAKE_CASE__ : List[str] = num_inference_steps SCREAMING_SNAKE_CASE__ : Optional[Any] = self.config.num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 SCREAMING_SNAKE_CASE__ : str = (np.arange(0 , _a ) * step_ratio).round().copy().astype(np.intaa ) SCREAMING_SNAKE_CASE__ : Tuple = torch.from_numpy(_a ).to(_a ) self.timesteps += self.config.steps_offset def _a ( self , _a , _a , _a , _a = 0.0 , _a = False , _a = None , _a = True , ) -> Union[DDIMSchedulerOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = timestep + self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas # change original implementation to exactly match noise levels for analogous forward process SCREAMING_SNAKE_CASE__ : Optional[int] = self.alphas_cumprod[timestep] SCREAMING_SNAKE_CASE__ : Optional[int] = ( self.alphas_cumprod[prev_timestep] if prev_timestep < self.config.num_train_timesteps else self.final_alpha_cumprod ) SCREAMING_SNAKE_CASE__ : Any = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf if self.config.prediction_type == "epsilon": SCREAMING_SNAKE_CASE__ : int = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 SCREAMING_SNAKE_CASE__ : List[Any] = model_output elif self.config.prediction_type == "sample": SCREAMING_SNAKE_CASE__ : Dict = model_output SCREAMING_SNAKE_CASE__ : int = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 elif self.config.prediction_type == "v_prediction": SCREAMING_SNAKE_CASE__ : Dict = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output SCREAMING_SNAKE_CASE__ : str = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or''' """ `v_prediction`""" ) # 4. Clip or threshold "predicted x_0" if self.config.clip_sample: SCREAMING_SNAKE_CASE__ : Tuple = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : Any = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : Dict = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if not return_dict: return (prev_sample, pred_original_sample) return DDIMSchedulerOutput(prev_sample=_a , pred_original_sample=_a ) def __len__( self ) -> Dict: """simple docstring""" return self.config.num_train_timesteps
680
1
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging a :int = logging.get_logger(__name__) a :List[str] = { "asapp/sew-d-tiny-100k": "https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json", # See all SEW-D models at https://huggingface.co/models?filter=sew-d } class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :int = """sew-d""" def __init__( self , _a=32 , _a=768 , _a=12 , _a=12 , _a=3_072 , _a=2 , _a=512 , _a=256 , _a=True , _a=True , _a=("p2c", "c2p") , _a="layer_norm" , _a="gelu_python" , _a=0.1 , _a=0.1 , _a=0.1 , _a=0.0 , _a=0.1 , _a=0.02 , _a=1E-7 , _a=1E-5 , _a="group" , _a="gelu" , _a=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , _a=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , _a=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , _a=False , _a=128 , _a=16 , _a=True , _a=0.05 , _a=10 , _a=2 , _a=0.0 , _a=10 , _a=0 , _a="mean" , _a=False , _a=False , _a=256 , _a=0 , _a=1 , _a=2 , **_a , ) -> Optional[Any]: """simple docstring""" super().__init__(**_a , pad_token_id=_a , bos_token_id=_a , eos_token_id=_a ) SCREAMING_SNAKE_CASE__ : List[Any] = hidden_size SCREAMING_SNAKE_CASE__ : List[str] = feat_extract_norm SCREAMING_SNAKE_CASE__ : Dict = feat_extract_activation SCREAMING_SNAKE_CASE__ : Any = list(_a ) SCREAMING_SNAKE_CASE__ : Dict = list(_a ) SCREAMING_SNAKE_CASE__ : str = list(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = conv_bias SCREAMING_SNAKE_CASE__ : Optional[int] = num_conv_pos_embeddings SCREAMING_SNAKE_CASE__ : Any = num_conv_pos_embedding_groups SCREAMING_SNAKE_CASE__ : List[Any] = len(self.conv_dim ) SCREAMING_SNAKE_CASE__ : List[str] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Optional[Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Any = squeeze_factor SCREAMING_SNAKE_CASE__ : List[str] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Dict = position_buckets SCREAMING_SNAKE_CASE__ : str = share_att_key SCREAMING_SNAKE_CASE__ : Tuple = relative_attention SCREAMING_SNAKE_CASE__ : List[Any] = norm_rel_ebd SCREAMING_SNAKE_CASE__ : int = list(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE__ : Dict = num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_dropout SCREAMING_SNAKE_CASE__ : Dict = attention_dropout SCREAMING_SNAKE_CASE__ : int = activation_dropout SCREAMING_SNAKE_CASE__ : str = feat_proj_dropout SCREAMING_SNAKE_CASE__ : List[str] = final_dropout SCREAMING_SNAKE_CASE__ : List[Any] = layer_norm_eps SCREAMING_SNAKE_CASE__ : List[str] = feature_layer_norm_eps SCREAMING_SNAKE_CASE__ : Any = initializer_range SCREAMING_SNAKE_CASE__ : str = vocab_size 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)`,""" f'''but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)''' f'''= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 SCREAMING_SNAKE_CASE__ : Optional[int] = apply_spec_augment SCREAMING_SNAKE_CASE__ : str = mask_time_prob SCREAMING_SNAKE_CASE__ : Tuple = mask_time_length SCREAMING_SNAKE_CASE__ : List[Any] = mask_time_min_masks SCREAMING_SNAKE_CASE__ : int = mask_feature_prob SCREAMING_SNAKE_CASE__ : List[Any] = mask_feature_length SCREAMING_SNAKE_CASE__ : Tuple = mask_feature_min_masks # ctc loss SCREAMING_SNAKE_CASE__ : Tuple = ctc_loss_reduction SCREAMING_SNAKE_CASE__ : Tuple = ctc_zero_infinity # sequence classification SCREAMING_SNAKE_CASE__ : Tuple = use_weighted_layer_sum SCREAMING_SNAKE_CASE__ : str = classifier_proj_size @property def _a ( self ) -> Any: """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
680
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) a :Union[str, Any] = { "configuration_speecht5": [ "SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP", "SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP", "SpeechT5Config", "SpeechT5HifiGanConfig", ], "feature_extraction_speecht5": ["SpeechT5FeatureExtractor"], "processing_speecht5": ["SpeechT5Processor"], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = ["SpeechT5Tokenizer"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST", "SpeechT5ForSpeechToText", "SpeechT5ForSpeechToSpeech", "SpeechT5ForTextToSpeech", "SpeechT5Model", "SpeechT5PreTrainedModel", "SpeechT5HifiGan", ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys a :Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a :int = logging.get_logger(__name__) a :str = { "microsoft/swinv2-tiny-patch4-window8-256": ( "https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json" ), } class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :int = """swinv2""" _SCREAMING_SNAKE_CASE :List[str] = { """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers""", } def __init__( self , _a=224 , _a=4 , _a=3 , _a=96 , _a=[2, 2, 6, 2] , _a=[3, 6, 12, 24] , _a=7 , _a=4.0 , _a=True , _a=0.0 , _a=0.0 , _a=0.1 , _a="gelu" , _a=False , _a=0.02 , _a=1E-5 , _a=32 , **_a , ) -> Any: """simple docstring""" super().__init__(**_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = image_size SCREAMING_SNAKE_CASE__ : List[Any] = patch_size SCREAMING_SNAKE_CASE__ : int = num_channels SCREAMING_SNAKE_CASE__ : Any = embed_dim SCREAMING_SNAKE_CASE__ : Optional[int] = depths SCREAMING_SNAKE_CASE__ : int = len(_a ) SCREAMING_SNAKE_CASE__ : List[str] = num_heads SCREAMING_SNAKE_CASE__ : Tuple = window_size SCREAMING_SNAKE_CASE__ : List[str] = mlp_ratio SCREAMING_SNAKE_CASE__ : Tuple = qkv_bias SCREAMING_SNAKE_CASE__ : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[int] = drop_path_rate SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE__ : Any = use_absolute_embeddings SCREAMING_SNAKE_CASE__ : List[Any] = layer_norm_eps SCREAMING_SNAKE_CASE__ : Dict = initializer_range SCREAMING_SNAKE_CASE__ : Any = encoder_stride # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model SCREAMING_SNAKE_CASE__ : Tuple = int(embed_dim * 2 ** (len(_a ) - 1) ) SCREAMING_SNAKE_CASE__ : List[Any] = (0, 0, 0, 0)
680
"""simple docstring""" import math import os import sys def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Union[str, Any] = """""" try: with open(__lowerCAmelCase , """rb""" ) as binary_file: SCREAMING_SNAKE_CASE__ : Optional[int] = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Dict = F'''{dat:08b}''' result += curr_byte return result except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> None: lexicon.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = last_match_id if math.loga(__lowerCAmelCase ).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE__ : Dict = """0""" + lexicon[curr_key] SCREAMING_SNAKE_CASE__ : str = bin(__lowerCAmelCase )[2:] def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Dict = {"""0""": """0""", """1""": """1"""} SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = """""", """""" SCREAMING_SNAKE_CASE__ : Any = len(__lowerCAmelCase ) for i in range(len(__lowerCAmelCase ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon[curr_string] result += last_match_id add_key_to_lexicon(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) index += 1 SCREAMING_SNAKE_CASE__ : List[str] = """""" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE__ : List[Any] = lexicon[curr_string] result += last_match_id return result def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Any = os.path.getsize(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = bin(__lowerCAmelCase )[2:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = len(__lowerCAmelCase ) return "0" * (length_length - 1) + file_length_binary + compressed def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Optional[int] = 8 try: with open(__lowerCAmelCase , """wb""" ) as opened_file: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ to_write[i : i + byte_length] for i in range(0 , len(__lowerCAmelCase ) , __lowerCAmelCase ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("""10000000""" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(__lowerCAmelCase , 2 ).to_bytes(1 , byteorder="""big""" ) ) except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Dict = read_file_binary(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = compress_data(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = add_file_length(__lowerCAmelCase , __lowerCAmelCase ) write_file_binary(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
680
1
"""simple docstring""" import argparse import json import os import evaluate import torch from datasets import load_dataset 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 from accelerate.utils.deepspeed import DummyOptim, DummyScheduler a :int = 16 a :List[str] = 32 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase = 16 , __lowerCAmelCase = "bert-base-cased" ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[Any] = AutoTokenizer.from_pretrained(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__lowerCAmelCase ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__lowerCAmelCase , max_length=__lowerCAmelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset SCREAMING_SNAKE_CASE__ : Optional[int] = datasets.map( __lowerCAmelCase , batched=__lowerCAmelCase , remove_columns=["""idx""", """sentence1""", """sentence2"""] , load_from_cache_file=__lowerCAmelCase ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__lowerCAmelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(__lowerCAmelCase , padding="""max_length""" , max_length=128 , return_tensors="""pt""" ) return tokenizer.pad(__lowerCAmelCase , padding="""longest""" , return_tensors="""pt""" ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE__ : Union[str, Any] = DataLoader( tokenized_datasets["""train"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = DataLoader( tokenized_datasets["""validation"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) return train_dataloader, eval_dataloader def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]: # Initialize accelerator SCREAMING_SNAKE_CASE__ : Optional[int] = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE__ : Tuple = config["""lr"""] SCREAMING_SNAKE_CASE__ : str = int(config["""num_epochs"""] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = int(config["""seed"""] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = int(config["""batch_size"""] ) SCREAMING_SNAKE_CASE__ : str = args.model_name_or_path set_seed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = get_dataloaders(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE__ : Dict = AutoModelForSequenceClassification.from_pretrained(__lowerCAmelCase , return_dict=__lowerCAmelCase ) # Instantiate optimizer SCREAMING_SNAKE_CASE__ : List[str] = ( AdamW if accelerator.state.deepspeed_plugin is None or """optimizer""" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) SCREAMING_SNAKE_CASE__ : Optional[int] = optimizer_cls(params=model.parameters() , lr=__lowerCAmelCase ) if accelerator.state.deepspeed_plugin is not None: SCREAMING_SNAKE_CASE__ : int = accelerator.state.deepspeed_plugin.deepspeed_config[ """gradient_accumulation_steps""" ] else: SCREAMING_SNAKE_CASE__ : Tuple = 1 SCREAMING_SNAKE_CASE__ : Dict = (len(__lowerCAmelCase ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): SCREAMING_SNAKE_CASE__ : str = get_linear_schedule_with_warmup( optimizer=__lowerCAmelCase , num_warmup_steps=0 , num_training_steps=__lowerCAmelCase , ) else: SCREAMING_SNAKE_CASE__ : Tuple = DummyScheduler(__lowerCAmelCase , total_num_steps=__lowerCAmelCase , warmup_num_steps=0 ) # 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. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = accelerator.prepare( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # We need to keep track of how many total steps we have iterated over SCREAMING_SNAKE_CASE__ : Any = 0 # We also need to keep track of the stating epoch so files are named properly SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 # Now we train the model SCREAMING_SNAKE_CASE__ : Optional[int] = evaluate.load("""glue""" , """mrpc""" ) SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : Optional[Any] = {} for epoch in range(__lowerCAmelCase , __lowerCAmelCase ): model.train() for step, batch in enumerate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Dict = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = outputs.loss SCREAMING_SNAKE_CASE__ : Optional[int] = loss / gradient_accumulation_steps accelerator.backward(__lowerCAmelCase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = 0 for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[Any] = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = accelerator.gather( (predictions, batch["""labels"""]) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(__lowerCAmelCase ) - 1: SCREAMING_SNAKE_CASE__ : Tuple = predictions[: len(eval_dataloader.dataset ) - samples_seen] SCREAMING_SNAKE_CASE__ : Tuple = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=__lowerCAmelCase , references=__lowerCAmelCase , ) SCREAMING_SNAKE_CASE__ : List[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = eval_metric["""accuracy"""] if best_performance < eval_metric["accuracy"]: SCREAMING_SNAKE_CASE__ : Any = eval_metric["""accuracy"""] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), F'''Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}''' accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , """all_results.json""" ) , """w""" ) as f: json.dump(__lowerCAmelCase , __lowerCAmelCase ) def _lowercase ( ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : List[str] = argparse.ArgumentParser(description="""Simple example of training script tracking peak GPU memory usage.""" ) parser.add_argument( """--model_name_or_path""" , type=__lowerCAmelCase , default="""bert-base-cased""" , help="""Path to pretrained model or model identifier from huggingface.co/models.""" , required=__lowerCAmelCase , ) parser.add_argument( """--output_dir""" , type=__lowerCAmelCase , default=""".""" , help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory.""" , ) parser.add_argument( """--performance_lower_bound""" , type=__lowerCAmelCase , default=__lowerCAmelCase , help="""Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.""" , ) parser.add_argument( """--num_epochs""" , type=__lowerCAmelCase , default=3 , help="""Number of train epochs.""" , ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : int = {"""lr""": 2E-5, """num_epochs""": args.num_epochs, """seed""": 42, """batch_size""": 16} training_function(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": main()
680
"""simple docstring""" import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Tuple = SamImageProcessor() SCREAMING_SNAKE_CASE__ : List[str] = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> Union[str, Any]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> Tuple: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Tuple = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Dict = processor(images=_a , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_torch def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [torch.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : str = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : List[Any] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : Any = processor.post_process_masks(_a , _a , _a ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Dict = processor.post_process_masks( _a , torch.tensor(_a ) , torch.tensor(_a ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np SCREAMING_SNAKE_CASE__ : Dict = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks(_a , np.array(_a ) , np.array(_a ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Dict = [[1, 0], [0, 1]] with self.assertRaises(_a ): SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks(_a , np.array(_a ) , np.array(_a ) ) @require_vision @require_tf class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Optional[int] = SamImageProcessor() SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> List[str]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> int: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Any = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : int = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Tuple = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Any = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Any = processor(images=_a , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_tf def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Union[str, Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [tf.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Optional[int] = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks(_a , _a , _a , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks( _a , tf.convert_to_tensor(_a ) , tf.convert_to_tensor(_a ) , return_tensors="""tf""" , ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np SCREAMING_SNAKE_CASE__ : Optional[int] = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks( _a , np.array(_a ) , np.array(_a ) , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Any = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): SCREAMING_SNAKE_CASE__ : str = processor.post_process_masks( _a , np.array(_a ) , np.array(_a ) , return_tensors="""tf""" ) @require_vision @require_torchvision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Dict = SamImageProcessor() SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> Any: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> Union[str, Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : int = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : List[Any] = [tf.convert_to_tensor(_a )] SCREAMING_SNAKE_CASE__ : Dict = [torch.tensor(_a )] SCREAMING_SNAKE_CASE__ : Optional[int] = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : List[str] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : List[Any] = processor.post_process_masks( _a , _a , _a , return_tensors="""tf""" ) SCREAMING_SNAKE_CASE__ : List[str] = processor.post_process_masks( _a , _a , _a , return_tensors="""pt""" ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : str = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : int = image_processor(_a , return_tensors="""pt""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : Any = processor(images=_a , return_tensors="""pt""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor(_a , return_tensors="""tf""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : str = processor(images=_a , return_tensors="""tf""" )["""pixel_values"""].numpy() self.assertTrue(np.allclose(_a , _a ) ) self.assertTrue(np.allclose(_a , _a ) ) self.assertTrue(np.allclose(_a , _a ) )
680
1
"""simple docstring""" import unicodedata from dataclasses import dataclass from typing import Optional, Union import numpy as np from transformers.data.data_collator import DataCollatorMixin from transformers.file_utils import PaddingStrategy from transformers.tokenization_utils_base import PreTrainedTokenizerBase def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Dict: if isinstance(__lowerCAmelCase , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = np.full((len(__lowerCAmelCase ), sequence_length, 2) , __lowerCAmelCase ) else: SCREAMING_SNAKE_CASE__ : List[Any] = np.full((len(__lowerCAmelCase ), sequence_length) , __lowerCAmelCase ) for i, tensor in enumerate(__lowerCAmelCase ): if padding_side == "right": if isinstance(__lowerCAmelCase , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = tensor[:sequence_length] else: SCREAMING_SNAKE_CASE__ : Optional[int] = tensor[:sequence_length] else: if isinstance(__lowerCAmelCase , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = tensor[:sequence_length] else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = tensor[:sequence_length] return out_tensor.tolist() def _lowercase ( __lowerCAmelCase ) -> Any: SCREAMING_SNAKE_CASE__ : int = ord(__lowerCAmelCase ) if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126): return True SCREAMING_SNAKE_CASE__ : Optional[Any] = unicodedata.category(__lowerCAmelCase ) if cat.startswith("""P""" ): return True return False @dataclass class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :PreTrainedTokenizerBase _SCREAMING_SNAKE_CASE :Union[bool, str, PaddingStrategy] = True _SCREAMING_SNAKE_CASE :Optional[int] = None _SCREAMING_SNAKE_CASE :Optional[int] = None _SCREAMING_SNAKE_CASE :int = -1_00 _SCREAMING_SNAKE_CASE :str = "pt" def _a ( self , _a ) -> Optional[int]: """simple docstring""" import torch SCREAMING_SNAKE_CASE__ : Optional[int] = """label""" if """label""" in features[0].keys() else """labels""" SCREAMING_SNAKE_CASE__ : int = [feature[label_name] for feature in features] if label_name in features[0].keys() else None SCREAMING_SNAKE_CASE__ : Dict = self.tokenizer.pad( _a , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="""pt""" if labels is None else None , ) if labels is None: return batch SCREAMING_SNAKE_CASE__ : str = torch.tensor(batch["""entity_ids"""] ).shape[1] SCREAMING_SNAKE_CASE__ : str = self.tokenizer.padding_side if padding_side == "right": SCREAMING_SNAKE_CASE__ : Tuple = [ list(_a ) + [self.label_pad_token_id] * (sequence_length - len(_a )) for label in labels ] else: SCREAMING_SNAKE_CASE__ : str = [ [self.label_pad_token_id] * (sequence_length - len(_a )) + list(_a ) for label in labels ] SCREAMING_SNAKE_CASE__ : int = [feature["""ner_tags"""] for feature in features] SCREAMING_SNAKE_CASE__ : Dict = padding_tensor(_a , -1 , _a , _a ) SCREAMING_SNAKE_CASE__ : List[str] = [feature["""original_entity_spans"""] for feature in features] SCREAMING_SNAKE_CASE__ : Dict = padding_tensor(_a , (-1, -1) , _a , _a ) SCREAMING_SNAKE_CASE__ : Optional[int] = {k: torch.tensor(_a , dtype=torch.intaa ) for k, v in batch.items()} return batch
680
"""simple docstring""" import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __a (UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = LayoutLMTokenizer _SCREAMING_SNAKE_CASE :Optional[int] = LayoutLMTokenizerFast _SCREAMING_SNAKE_CASE :str = True _SCREAMING_SNAKE_CASE :Optional[int] = True def _a ( self ) -> Tuple: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : List[str] = [ """[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] SCREAMING_SNAKE_CASE__ : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def _a ( self , **_a ) -> Optional[int]: """simple docstring""" return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **_a ) def _a ( self , _a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = """UNwant\u00E9d,running""" SCREAMING_SNAKE_CASE__ : Optional[Any] = """unwanted, running""" return input_text, output_text def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(_a , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_a ) , [7, 4, 5, 10, 8, 9] ) def _a ( self ) -> Optional[int]: """simple docstring""" pass
680
1
"""simple docstring""" import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import datasets import evaluate import numpy as np from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.31.0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt") a :Optional[int] = logging.getLogger(__name__) @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[int] = field( default=1_28 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) _SCREAMING_SNAKE_CASE :bool = field( default=UpperCamelCase_ , metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""}) _SCREAMING_SNAKE_CASE :bool = field( default=UpperCamelCase_ , metadata={ """help""": ( """Whether to pad all samples to `max_seq_length`. """ """If False, will pad the samples dynamically when batching to the maximum length in the batch.""" ) } , ) _SCREAMING_SNAKE_CASE :Optional[int] = field( default=UpperCamelCase_ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of training examples to this """ """value if set.""" ) } , ) _SCREAMING_SNAKE_CASE :Optional[int] = field( default=UpperCamelCase_ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of evaluation examples to this """ """value if set.""" ) } , ) _SCREAMING_SNAKE_CASE :Optional[int] = field( default=UpperCamelCase_ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of prediction examples to this """ """value if set.""" ) } , ) @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :str = field( default=UpperCamelCase_ , metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}) _SCREAMING_SNAKE_CASE :str = field( default=UpperCamelCase_ , metadata={"""help""": """Evaluation language. Also train language if `train_language` is set to None."""}) _SCREAMING_SNAKE_CASE :Optional[str] = field( default=UpperCamelCase_ , metadata={"""help""": """Train language if it is different from the evaluation language."""}) _SCREAMING_SNAKE_CASE :Optional[str] = field( default=UpperCamelCase_ , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}) _SCREAMING_SNAKE_CASE :Optional[str] = field( default=UpperCamelCase_ , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}) _SCREAMING_SNAKE_CASE :Optional[str] = field( default=UpperCamelCase_ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) _SCREAMING_SNAKE_CASE :Optional[bool] = field( default=UpperCamelCase_ , metadata={"""help""": """arg to indicate if tokenizer should do lower case in AutoTokenizer.from_pretrained()"""} , ) _SCREAMING_SNAKE_CASE :bool = field( default=UpperCamelCase_ , metadata={"""help""": """Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."""} , ) _SCREAMING_SNAKE_CASE :str = field( default="""main""" , metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""} , ) _SCREAMING_SNAKE_CASE :bool = field( default=UpperCamelCase_ , metadata={ """help""": ( """Will use the token generated when running `huggingface-cli login` (necessary to use this script """ """with private models).""" ) } , ) _SCREAMING_SNAKE_CASE :bool = field( default=UpperCamelCase_ , metadata={"""help""": """Will enable to load a pretrained model whose head dimensions are different."""} , ) def _lowercase ( ) -> Dict: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. SCREAMING_SNAKE_CASE__ : Optional[int] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("""run_xnli""" , __lowerCAmelCase ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : Optional[int] = training_args.get_process_log_level() logger.setLevel(__lowerCAmelCase ) datasets.utils.logging.set_verbosity(__lowerCAmelCase ) transformers.utils.logging.set_verbosity(__lowerCAmelCase ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}''' + F'''distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}''' ) logger.info(F'''Training/evaluation parameters {training_args}''' ) # Detecting last checkpoint. SCREAMING_SNAKE_CASE__ : int = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: SCREAMING_SNAKE_CASE__ : Optional[int] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'''Output directory ({training_args.output_dir}) already exists and is not empty. ''' """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None: logger.info( F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ''' """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Set seed before initializing model. set_seed(training_args.seed ) # In distributed training, the load_dataset function guarantees that only one local process can concurrently # download the dataset. # Downloading and loading xnli dataset from the hub. if training_args.do_train: if model_args.train_language is None: SCREAMING_SNAKE_CASE__ : Any = load_dataset( """xnli""" , model_args.language , split="""train""" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) else: SCREAMING_SNAKE_CASE__ : str = load_dataset( """xnli""" , model_args.train_language , split="""train""" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ : int = train_dataset.features["""label"""].names if training_args.do_eval: SCREAMING_SNAKE_CASE__ : Optional[Any] = load_dataset( """xnli""" , model_args.language , split="""validation""" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ : Any = eval_dataset.features["""label"""].names if training_args.do_predict: SCREAMING_SNAKE_CASE__ : Optional[int] = load_dataset( """xnli""" , model_args.language , split="""test""" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ : Optional[int] = predict_dataset.features["""label"""].names # Labels SCREAMING_SNAKE_CASE__ : Any = len(__lowerCAmelCase ) # Load pretrained model and tokenizer # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. SCREAMING_SNAKE_CASE__ : str = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=__lowerCAmelCase , idalabel={str(__lowerCAmelCase ): label for i, label in enumerate(__lowerCAmelCase )} , labelaid={label: i for i, label in enumerate(__lowerCAmelCase )} , finetuning_task="""xnli""" , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ : Dict = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , do_lower_case=model_args.do_lower_case , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ : int = AutoModelForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=__lowerCAmelCase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , ) # Preprocessing the datasets # Padding strategy if data_args.pad_to_max_length: SCREAMING_SNAKE_CASE__ : Optional[int] = """max_length""" else: # We will pad later, dynamically at batch creation, to the max sequence length in each batch SCREAMING_SNAKE_CASE__ : Optional[int] = False def preprocess_function(__lowerCAmelCase ): # Tokenize the texts return tokenizer( examples["""premise"""] , examples["""hypothesis"""] , padding=__lowerCAmelCase , max_length=data_args.max_seq_length , truncation=__lowerCAmelCase , ) if training_args.do_train: if data_args.max_train_samples is not None: SCREAMING_SNAKE_CASE__ : str = min(len(__lowerCAmelCase ) , data_args.max_train_samples ) SCREAMING_SNAKE_CASE__ : Tuple = train_dataset.select(range(__lowerCAmelCase ) ) with training_args.main_process_first(desc="""train dataset map pre-processing""" ): SCREAMING_SNAKE_CASE__ : int = train_dataset.map( __lowerCAmelCase , batched=__lowerCAmelCase , load_from_cache_file=not data_args.overwrite_cache , desc="""Running tokenizer on train dataset""" , ) # Log a few random samples from the training set: for index in random.sample(range(len(__lowerCAmelCase ) ) , 3 ): logger.info(F'''Sample {index} of the training set: {train_dataset[index]}.''' ) if training_args.do_eval: if data_args.max_eval_samples is not None: SCREAMING_SNAKE_CASE__ : List[str] = min(len(__lowerCAmelCase ) , data_args.max_eval_samples ) SCREAMING_SNAKE_CASE__ : Dict = eval_dataset.select(range(__lowerCAmelCase ) ) with training_args.main_process_first(desc="""validation dataset map pre-processing""" ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = eval_dataset.map( __lowerCAmelCase , batched=__lowerCAmelCase , load_from_cache_file=not data_args.overwrite_cache , desc="""Running tokenizer on validation dataset""" , ) if training_args.do_predict: if data_args.max_predict_samples is not None: SCREAMING_SNAKE_CASE__ : List[str] = min(len(__lowerCAmelCase ) , data_args.max_predict_samples ) SCREAMING_SNAKE_CASE__ : Any = predict_dataset.select(range(__lowerCAmelCase ) ) with training_args.main_process_first(desc="""prediction dataset map pre-processing""" ): SCREAMING_SNAKE_CASE__ : int = predict_dataset.map( __lowerCAmelCase , batched=__lowerCAmelCase , load_from_cache_file=not data_args.overwrite_cache , desc="""Running tokenizer on prediction dataset""" , ) # Get the metric function SCREAMING_SNAKE_CASE__ : Union[str, Any] = evaluate.load("""xnli""" ) # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[Any] = p.predictions[0] if isinstance(p.predictions , __lowerCAmelCase ) else p.predictions SCREAMING_SNAKE_CASE__ : int = np.argmax(__lowerCAmelCase , axis=1 ) return metric.compute(predictions=__lowerCAmelCase , references=p.label_ids ) # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding. if data_args.pad_to_max_length: SCREAMING_SNAKE_CASE__ : Union[str, Any] = default_data_collator elif training_args.fpaa: SCREAMING_SNAKE_CASE__ : List[Any] = DataCollatorWithPadding(__lowerCAmelCase , pad_to_multiple_of=8 ) else: SCREAMING_SNAKE_CASE__ : List[str] = None # Initialize our Trainer SCREAMING_SNAKE_CASE__ : List[Any] = Trainer( model=__lowerCAmelCase , args=__lowerCAmelCase , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , compute_metrics=__lowerCAmelCase , tokenizer=__lowerCAmelCase , data_collator=__lowerCAmelCase , ) # Training if training_args.do_train: SCREAMING_SNAKE_CASE__ : int = None if training_args.resume_from_checkpoint is not None: SCREAMING_SNAKE_CASE__ : Any = training_args.resume_from_checkpoint elif last_checkpoint is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = last_checkpoint SCREAMING_SNAKE_CASE__ : str = trainer.train(resume_from_checkpoint=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = train_result.metrics SCREAMING_SNAKE_CASE__ : str = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(__lowerCAmelCase ) ) SCREAMING_SNAKE_CASE__ : Dict = min(__lowerCAmelCase , len(__lowerCAmelCase ) ) trainer.save_model() # Saves the tokenizer too for easy upload trainer.log_metrics("""train""" , __lowerCAmelCase ) trainer.save_metrics("""train""" , __lowerCAmelCase ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("""*** Evaluate ***""" ) SCREAMING_SNAKE_CASE__ : Any = trainer.evaluate(eval_dataset=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = min(__lowerCAmelCase , len(__lowerCAmelCase ) ) trainer.log_metrics("""eval""" , __lowerCAmelCase ) trainer.save_metrics("""eval""" , __lowerCAmelCase ) # Prediction if training_args.do_predict: logger.info("""*** Predict ***""" ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = trainer.predict(__lowerCAmelCase , metric_key_prefix="""predict""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = ( data_args.max_predict_samples if data_args.max_predict_samples is not None else len(__lowerCAmelCase ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = min(__lowerCAmelCase , len(__lowerCAmelCase ) ) trainer.log_metrics("""predict""" , __lowerCAmelCase ) trainer.save_metrics("""predict""" , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.argmax(__lowerCAmelCase , axis=1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.join(training_args.output_dir , """predictions.txt""" ) if trainer.is_world_process_zero(): with open(__lowerCAmelCase , """w""" ) as writer: writer.write("""index\tprediction\n""" ) for index, item in enumerate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = label_list[item] writer.write(F'''{index}\t{item}\n''' ) if __name__ == "__main__": main()
680
"""simple docstring""" import argparse import os import evaluate import torch from datasets import load_dataset 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 # and perform gradient accumulation # # 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 run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a :str = 16 a :Union[str, Any] = 32 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase = 16 ) -> Tuple: SCREAMING_SNAKE_CASE__ : int = AutoTokenizer.from_pretrained("""bert-base-cased""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__lowerCAmelCase ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__lowerCAmelCase , max_length=__lowerCAmelCase ) 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(): SCREAMING_SNAKE_CASE__ : List[str] = datasets.map( __lowerCAmelCase , batched=__lowerCAmelCase , 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 SCREAMING_SNAKE_CASE__ : Any = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__lowerCAmelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE__ : int = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE__ : str = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE__ : Dict = 8 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = None return tokenizer.pad( __lowerCAmelCase , padding="""longest""" , max_length=__lowerCAmelCase , pad_to_multiple_of=__lowerCAmelCase , return_tensors="""pt""" , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE__ : int = DataLoader( tokenized_datasets["""train"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = DataLoader( tokenized_datasets["""validation"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": from accelerate.test_utils.training import mocked_dataloaders a :Dict = mocked_dataloaders # noqa: F811 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , __lowerCAmelCase ) == "1": SCREAMING_SNAKE_CASE__ : Optional[int] = 2 # New Code # SCREAMING_SNAKE_CASE__ : Optional[int] = int(args.gradient_accumulation_steps ) # Initialize accelerator SCREAMING_SNAKE_CASE__ : Optional[Any] = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=__lowerCAmelCase ) if accelerator.distributed_type == DistributedType.TPU and gradient_accumulation_steps > 1: raise NotImplementedError( """Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE__ : Any = config["""lr"""] SCREAMING_SNAKE_CASE__ : str = int(config["""num_epochs"""] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = int(config["""seed"""] ) SCREAMING_SNAKE_CASE__ : List[str] = int(config["""batch_size"""] ) SCREAMING_SNAKE_CASE__ : Any = evaluate.load("""glue""" , """mrpc""" ) set_seed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = get_dataloaders(__lowerCAmelCase , __lowerCAmelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE__ : int = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=__lowerCAmelCase ) # 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). SCREAMING_SNAKE_CASE__ : int = model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE__ : Union[str, Any] = AdamW(params=model.parameters() , lr=__lowerCAmelCase ) # Instantiate scheduler SCREAMING_SNAKE_CASE__ : Any = get_linear_schedule_with_warmup( optimizer=__lowerCAmelCase , num_warmup_steps=100 , num_training_steps=(len(__lowerCAmelCase ) * num_epochs) , ) # 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. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = accelerator.prepare( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Now we train the model for epoch in range(__lowerCAmelCase ): model.train() for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = output.loss accelerator.backward(__lowerCAmelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=__lowerCAmelCase , references=__lowerCAmelCase , ) SCREAMING_SNAKE_CASE__ : List[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , __lowerCAmelCase ) def _lowercase ( ) -> Any: SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=__lowerCAmelCase , default=__lowerCAmelCase , 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.""" , ) # New Code # parser.add_argument( """--gradient_accumulation_steps""" , type=__lowerCAmelCase , default=1 , help="""The number of minibatches to be ran before gradients are accumulated.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : int = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": main()
680
1
"""simple docstring""" import math import sys def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Tuple = """""" try: with open(__lowerCAmelCase , """rb""" ) as binary_file: SCREAMING_SNAKE_CASE__ : Any = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Union[str, Any] = F'''{dat:08b}''' result += curr_byte return result except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Dict = {"""0""": """0""", """1""": """1"""} SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = """""", """""" SCREAMING_SNAKE_CASE__ : Tuple = len(__lowerCAmelCase ) for i in range(len(__lowerCAmelCase ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon[curr_string] result += last_match_id SCREAMING_SNAKE_CASE__ : int = last_match_id + """0""" if math.loga(__lowerCAmelCase ).is_integer(): SCREAMING_SNAKE_CASE__ : Optional[int] = {} for curr_key in list(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[Any] = lexicon.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = new_lex SCREAMING_SNAKE_CASE__ : Union[str, Any] = last_match_id + """1""" index += 1 SCREAMING_SNAKE_CASE__ : str = """""" return result def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Optional[int] = 8 try: with open(__lowerCAmelCase , """wb""" ) as opened_file: SCREAMING_SNAKE_CASE__ : Optional[int] = [ to_write[i : i + byte_length] for i in range(0 , len(__lowerCAmelCase ) , __lowerCAmelCase ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("""10000000""" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array[:-1]: opened_file.write(int(__lowerCAmelCase , 2 ).to_bytes(1 , byteorder="""big""" ) ) except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Optional[int] = 0 for letter in data_bits: if letter == "1": break counter += 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = data_bits[counter:] SCREAMING_SNAKE_CASE__ : Any = data_bits[counter + 1 :] return data_bits def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : List[str] = read_file_binary(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = remove_prefix(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = decompress_data(__lowerCAmelCase ) write_file_binary(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
680
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available a :str = { "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST", "ErnieForCausalLM", "ErnieForMaskedLM", "ErnieForMultipleChoice", "ErnieForNextSentencePrediction", "ErnieForPreTraining", "ErnieForQuestionAnswering", "ErnieForSequenceClassification", "ErnieForTokenClassification", "ErnieModel", "ErniePreTrainedModel", ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys a :Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
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 rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL a :List[str] = logging.get_logger(__name__) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : int = b.T SCREAMING_SNAKE_CASE__ : Dict = np.sum(np.square(__lowerCAmelCase ) , axis=1 ) SCREAMING_SNAKE_CASE__ : int = np.sum(np.square(__lowerCAmelCase ) , axis=0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.matmul(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = aa[:, None] - 2 * ab + ba[None, :] return d def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Dict = x.reshape(-1 , 3 ) SCREAMING_SNAKE_CASE__ : int = squared_euclidean_distance(__lowerCAmelCase , __lowerCAmelCase ) return np.argmin(__lowerCAmelCase , axis=1 ) class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[str] = ["""pixel_values"""] def __init__( self , _a = None , _a = True , _a = None , _a = PILImageResampling.BILINEAR , _a = True , _a = True , **_a , ) -> None: """simple docstring""" super().__init__(**_a ) SCREAMING_SNAKE_CASE__ : Tuple = size if size is not None else {"""height""": 256, """width""": 256} SCREAMING_SNAKE_CASE__ : Dict = get_size_dict(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.array(_a ) if clusters is not None else None SCREAMING_SNAKE_CASE__ : Tuple = do_resize SCREAMING_SNAKE_CASE__ : List[str] = size SCREAMING_SNAKE_CASE__ : str = resample SCREAMING_SNAKE_CASE__ : Dict = do_normalize SCREAMING_SNAKE_CASE__ : Tuple = do_color_quantize def _a ( self , _a , _a , _a = PILImageResampling.BILINEAR , _a = None , **_a , ) -> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = get_size_dict(_a ) if "height" not in size or "width" not in size: raise ValueError(f'''Size dictionary must contain both height and width keys. Got {size.keys()}''' ) return resize( _a , size=(size["""height"""], size["""width"""]) , resample=_a , data_format=_a , **_a ) def _a ( self , _a , _a = None , ) -> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = rescale(image=_a , scale=1 / 127.5 , data_format=_a ) SCREAMING_SNAKE_CASE__ : Any = image - 1 return image def _a ( self , _a , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = ChannelDimension.FIRST , **_a , ) -> PIL.Image.Image: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE__ : int = size if size is not None else self.size SCREAMING_SNAKE_CASE__ : str = get_size_dict(_a ) SCREAMING_SNAKE_CASE__ : Any = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE__ : Dict = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE__ : Optional[int] = do_color_quantize if do_color_quantize is not None else self.do_color_quantize SCREAMING_SNAKE_CASE__ : List[str] = clusters if clusters is not None else self.clusters SCREAMING_SNAKE_CASE__ : List[Any] = np.array(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = make_list_of_images(_a ) if not valid_images(_a ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_color_quantize and clusters is None: raise ValueError("""Clusters must be specified if do_color_quantize is True.""" ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE__ : List[Any] = [to_numpy_array(_a ) for image in images] if do_resize: SCREAMING_SNAKE_CASE__ : List[str] = [self.resize(image=_a , size=_a , resample=_a ) for image in images] if do_normalize: SCREAMING_SNAKE_CASE__ : Optional[Any] = [self.normalize(image=_a ) for image in images] if do_color_quantize: SCREAMING_SNAKE_CASE__ : Tuple = [to_channel_dimension_format(_a , ChannelDimension.LAST ) for image in images] # color quantize from (batch_size, height, width, 3) to (batch_size, height, width) SCREAMING_SNAKE_CASE__ : Dict = np.array(_a ) SCREAMING_SNAKE_CASE__ : List[str] = color_quantize(_a , _a ).reshape(images.shape[:-1] ) # flatten to (batch_size, height*width) SCREAMING_SNAKE_CASE__ : Any = images.shape[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = images.reshape(_a , -1 ) # We need to convert back to a list of images to keep consistent behaviour across processors. SCREAMING_SNAKE_CASE__ : Any = list(_a ) else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [to_channel_dimension_format(_a , _a ) for image in images] SCREAMING_SNAKE_CASE__ : List[Any] = {"""input_ids""": images} return BatchFeature(data=_a , tensor_type=_a )
680
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> int: assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and number_of_steps > 0 ), F'''number_of_steps needs to be positive integer, your input {number_of_steps}''' if number_of_steps == 1: return 1 SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = 1, 1 for _ in range(number_of_steps - 1 ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = current + previous, current return current if __name__ == "__main__": import doctest doctest.testmod()
680
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) a :List[Any] = {"configuration_fnet": ["FNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FNetConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Optional[int] = ["FNetTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = ["FNetTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :List[str] = [ "FNET_PRETRAINED_MODEL_ARCHIVE_LIST", "FNetForMaskedLM", "FNetForMultipleChoice", "FNetForNextSentencePrediction", "FNetForPreTraining", "FNetForQuestionAnswering", "FNetForSequenceClassification", "FNetForTokenClassification", "FNetLayer", "FNetModel", "FNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys a :Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
"""simple docstring""" from math import factorial def _lowercase ( __lowerCAmelCase = 100 ) -> int: return sum(int(__lowerCAmelCase ) for x in str(factorial(__lowerCAmelCase ) ) ) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
680
1
"""simple docstring""" import argparse import json import os import evaluate import torch from datasets import load_dataset 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 from accelerate.utils.deepspeed import DummyOptim, DummyScheduler a :int = 16 a :Dict = 32 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase = 16 , __lowerCAmelCase = "bert-base-cased" ) -> List[str]: SCREAMING_SNAKE_CASE__ : Tuple = AutoTokenizer.from_pretrained(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__lowerCAmelCase ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE__ : int = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__lowerCAmelCase , max_length=__lowerCAmelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset SCREAMING_SNAKE_CASE__ : Optional[int] = datasets.map( __lowerCAmelCase , batched=__lowerCAmelCase , remove_columns=["""idx""", """sentence1""", """sentence2"""] , load_from_cache_file=__lowerCAmelCase ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE__ : str = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__lowerCAmelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(__lowerCAmelCase , padding="""max_length""" , max_length=128 , return_tensors="""pt""" ) return tokenizer.pad(__lowerCAmelCase , padding="""longest""" , return_tensors="""pt""" ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE__ : Tuple = DataLoader( tokenized_datasets["""train"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = DataLoader( tokenized_datasets["""validation"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) return train_dataloader, eval_dataloader def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> List[str]: model.eval() SCREAMING_SNAKE_CASE__ : List[str] = 0 for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[str] = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = accelerator.gather( (predictions, batch["""labels"""]) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(__lowerCAmelCase ) - 1: SCREAMING_SNAKE_CASE__ : Tuple = predictions[: len(eval_dataloader.dataset ) - samples_seen] SCREAMING_SNAKE_CASE__ : Optional[Any] = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=__lowerCAmelCase , references=__lowerCAmelCase , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = metric.compute() return eval_metric["accuracy"] def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> str: # Initialize accelerator SCREAMING_SNAKE_CASE__ : Any = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE__ : Optional[int] = config["""lr"""] SCREAMING_SNAKE_CASE__ : str = int(config["""num_epochs"""] ) SCREAMING_SNAKE_CASE__ : int = int(config["""seed"""] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = int(config["""batch_size"""] ) SCREAMING_SNAKE_CASE__ : Any = args.model_name_or_path set_seed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = get_dataloaders(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoModelForSequenceClassification.from_pretrained(__lowerCAmelCase , return_dict=__lowerCAmelCase ) # Instantiate optimizer SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( AdamW if accelerator.state.deepspeed_plugin is None or """optimizer""" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) SCREAMING_SNAKE_CASE__ : Any = optimizer_cls(params=model.parameters() , lr=__lowerCAmelCase ) if accelerator.state.deepspeed_plugin is not None: SCREAMING_SNAKE_CASE__ : List[str] = accelerator.state.deepspeed_plugin.deepspeed_config[ """gradient_accumulation_steps""" ] else: SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : List[Any] = (len(__lowerCAmelCase ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_linear_schedule_with_warmup( optimizer=__lowerCAmelCase , num_warmup_steps=0 , num_training_steps=__lowerCAmelCase , ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] = DummyScheduler(__lowerCAmelCase , total_num_steps=__lowerCAmelCase , warmup_num_steps=0 ) # 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. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = accelerator.prepare( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # We need to keep track of how many total steps we have iterated over SCREAMING_SNAKE_CASE__ : Optional[int] = 0 # We also need to keep track of the stating epoch so files are named properly SCREAMING_SNAKE_CASE__ : List[str] = 0 SCREAMING_SNAKE_CASE__ : Union[str, Any] = evaluate.load("""glue""" , """mrpc""" ) SCREAMING_SNAKE_CASE__ : Dict = num_epochs if args.partial_train_epoch is not None: SCREAMING_SNAKE_CASE__ : List[str] = args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) SCREAMING_SNAKE_CASE__ : List[Any] = args.resume_from_checkpoint.split("""epoch_""" )[1] SCREAMING_SNAKE_CASE__ : Tuple = """""" for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break SCREAMING_SNAKE_CASE__ : Optional[int] = int(__lowerCAmelCase ) + 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = evaluation_loop(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) accelerator.print("""resumed checkpoint performance:""" , __lowerCAmelCase ) accelerator.print("""resumed checkpoint's scheduler's lr:""" , lr_scheduler.get_lr()[0] ) accelerator.print("""resumed optimizers's lr:""" , optimizer.param_groups[0]["""lr"""] ) with open(os.path.join(args.output_dir , F'''state_{starting_epoch-1}.json''' ) , """r""" ) as f: SCREAMING_SNAKE_CASE__ : str = json.load(__lowerCAmelCase ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model SCREAMING_SNAKE_CASE__ : Tuple = {} for epoch in range(__lowerCAmelCase , __lowerCAmelCase ): model.train() for step, batch in enumerate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Optional[int] = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = outputs.loss SCREAMING_SNAKE_CASE__ : Optional[Any] = loss / gradient_accumulation_steps accelerator.backward(__lowerCAmelCase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 SCREAMING_SNAKE_CASE__ : Any = F'''epoch_{epoch}''' SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.join(args.output_dir , __lowerCAmelCase ) accelerator.save_state(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = evaluation_loop(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : int = accuracy SCREAMING_SNAKE_CASE__ : Union[str, Any] = lr_scheduler.get_lr()[0] SCREAMING_SNAKE_CASE__ : List[str] = optimizer.param_groups[0]["""lr"""] SCREAMING_SNAKE_CASE__ : Optional[Any] = epoch SCREAMING_SNAKE_CASE__ : Optional[Any] = overall_step accelerator.print(F'''epoch {epoch}:''' , __lowerCAmelCase ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , F'''state_{epoch}.json''' ) , """w""" ) as f: json.dump(__lowerCAmelCase , __lowerCAmelCase ) def _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Dict = argparse.ArgumentParser(description="""Simple example of training script tracking peak GPU memory usage.""" ) parser.add_argument( """--model_name_or_path""" , type=__lowerCAmelCase , default="""bert-base-cased""" , help="""Path to pretrained model or model identifier from huggingface.co/models.""" , required=__lowerCAmelCase , ) parser.add_argument( """--output_dir""" , type=__lowerCAmelCase , default=""".""" , help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory.""" , ) parser.add_argument( """--resume_from_checkpoint""" , type=__lowerCAmelCase , default=__lowerCAmelCase , help="""If the training should continue from a checkpoint folder.""" , ) parser.add_argument( """--partial_train_epoch""" , type=__lowerCAmelCase , default=__lowerCAmelCase , help="""If passed, the training will stop after this number of epochs.""" , ) parser.add_argument( """--num_epochs""" , type=__lowerCAmelCase , default=2 , help="""Number of train epochs.""" , ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : List[Any] = {"""lr""": 2E-5, """num_epochs""": args.num_epochs, """seed""": 42, """batch_size""": 16} training_function(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": main()
680
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from typing import List from unittest.mock import Mock import torch from torch.utils.data import DataLoader, IterableDataset, TensorDataset from accelerate.accelerator import Accelerator from accelerate.utils.dataclasses import DistributedType class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = data def __iter__( self ) -> Tuple: """simple docstring""" for element in self.data: yield element def _lowercase ( __lowerCAmelCase=True ) -> str: SCREAMING_SNAKE_CASE__ : str = Accelerator(even_batches=__lowerCAmelCase ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = False ) -> Optional[int]: if iterable: SCREAMING_SNAKE_CASE__ : int = DummyIterableDataset(torch.as_tensor(range(__lowerCAmelCase ) ) ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = TensorDataset(torch.as_tensor(range(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : str = DataLoader(__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = accelerator.prepare(__lowerCAmelCase ) return dl def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> Tuple: SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(accelerator=__lowerCAmelCase , dataset_size=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = [len(batch[0] ) for batch in dl] if accelerator.process_index == 0: assert batch_sizes == process_0_expected_batch_sizes elif accelerator.process_index == 1: assert batch_sizes == process_1_expected_batch_sizes def _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Tuple = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1, 1] , ) # without padding, we would expect the same number of batches, but different sizes verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_accelerator(even_batches=__lowerCAmelCase ) verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , ) verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , ) def _lowercase ( ) -> str: SCREAMING_SNAKE_CASE__ : List[str] = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) SCREAMING_SNAKE_CASE__ : int = [] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Optional[Any] = ddp_model(batch[0].float() ) SCREAMING_SNAKE_CASE__ : List[Any] = output.sum() loss.backward() batch_idxs.append(__lowerCAmelCase ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: with warnings.catch_warnings(record=__lowerCAmelCase ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category , __lowerCAmelCase ) assert "only supported for multi-GPU" in str(w[-1].message ) def _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = False SCREAMING_SNAKE_CASE__ : Any = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerator.prepare(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) SCREAMING_SNAKE_CASE__ : List[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[Any] = train_dl.batch_sampler.even_batches SCREAMING_SNAKE_CASE__ : str = valid_dl.batch_sampler.even_batches assert train_dl_overridden_value == overridden_even_batches assert valid_dl_overridden_value == overridden_even_batches assert train_dl.batch_sampler.even_batches == default_even_batches assert valid_dl.batch_sampler.even_batches == default_even_batches def _lowercase ( ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[Any] = True SCREAMING_SNAKE_CASE__ : List[Any] = False SCREAMING_SNAKE_CASE__ : int = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : str = accelerator.prepare(__lowerCAmelCase ) create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings("""ignore""" ) try: with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = batch_dl.batch_sampler.even_batches except AttributeError: # ensure attribute error is not raised when processing iterable dl raise AssertionError assert batch_dl_overridden_value == overridden_even_batches assert batch_dl.batch_sampler.even_batches == default_even_batches def _lowercase ( ) -> List[str]: SCREAMING_SNAKE_CASE__ : str = create_accelerator() SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase ) create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase ) with warnings.catch_warnings(record=__lowerCAmelCase ) as w: with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): pass assert issubclass(w[-1].category , __lowerCAmelCase ) assert "only supported for map-style datasets" in str(w[-1].message ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_accelerator() accelerator.print("""Test that even_batches variable ensures uniform batches across processes""" ) test_default_ensures_even_batch_sizes() accelerator.print("""Run tests with even_batches disabled""" ) test_can_disable_even_batches() accelerator.print("""Test joining uneven inputs""" ) test_can_join_uneven_inputs() accelerator.print("""Test overriding even_batches when joining uneven inputs""" ) test_join_can_override_even_batches() accelerator.print("""Test overriding even_batches for mixed dataloader types""" ) test_join_can_override_for_mixed_type_dataloaders() accelerator.print("""Test overriding even_batches raises a warning for iterable dataloaders""" ) test_join_raises_warning_for_iterable_when_overriding_even_batches() accelerator.print("""Test join with non DDP distributed raises warning""" ) SCREAMING_SNAKE_CASE__ : Dict = accelerator.state.distributed_type SCREAMING_SNAKE_CASE__ : Optional[int] = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = original_state if __name__ == "__main__": main()
680
1
"""simple docstring""" import inspect import unittest from transformers import YolosConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import YolosForObjectDetection, YolosModel from transformers.models.yolos.modeling_yolos import YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __a : '''simple docstring''' def __init__( self , _a , _a=13 , _a=[30, 30] , _a=2 , _a=3 , _a=True , _a=True , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=10 , _a=0.02 , _a=3 , _a=None , _a=8 , _a=10 , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = parent SCREAMING_SNAKE_CASE__ : Optional[int] = batch_size SCREAMING_SNAKE_CASE__ : List[Any] = image_size SCREAMING_SNAKE_CASE__ : Tuple = patch_size SCREAMING_SNAKE_CASE__ : Tuple = num_channels SCREAMING_SNAKE_CASE__ : List[str] = is_training SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_labels SCREAMING_SNAKE_CASE__ : Dict = hidden_size SCREAMING_SNAKE_CASE__ : int = num_hidden_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : str = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE__ : List[str] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[int] = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Any = initializer_range SCREAMING_SNAKE_CASE__ : Dict = num_labels SCREAMING_SNAKE_CASE__ : Any = scope SCREAMING_SNAKE_CASE__ : Union[str, Any] = n_targets SCREAMING_SNAKE_CASE__ : int = num_detection_tokens # we set the expected sequence length (which is used in several tests) # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) + num_detection_tokens SCREAMING_SNAKE_CASE__ : Union[str, Any] = (image_size[1] // patch_size) * (image_size[0] // patch_size) SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_patches + 1 + self.num_detection_tokens def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]] ) SCREAMING_SNAKE_CASE__ : List[Any] = None if self.use_labels: # labels is a list of Dict (each Dict being the labels for a given example in the batch) SCREAMING_SNAKE_CASE__ : str = [] for i in range(self.batch_size ): SCREAMING_SNAKE_CASE__ : Dict = {} SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.randint( high=self.num_labels , size=(self.n_targets,) , device=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.rand(self.n_targets , 4 , device=_a ) labels.append(_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_config() return config, pixel_values, labels def _a ( self ) -> Optional[int]: """simple docstring""" return YolosConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_a , initializer_range=self.initializer_range , num_detection_tokens=self.num_detection_tokens , num_labels=self.num_labels , ) def _a ( self , _a , _a , _a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = YolosModel(config=_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.expected_seq_len, self.hidden_size) ) def _a ( self , _a , _a , _a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = YolosForObjectDetection(_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(pixel_values=_a ) SCREAMING_SNAKE_CASE__ : Any = model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_detection_tokens, self.num_labels + 1) ) self.parent.assertEqual(result.pred_boxes.shape , (self.batch_size, self.num_detection_tokens, 4) ) SCREAMING_SNAKE_CASE__ : int = model(pixel_values=_a , labels=_a ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_detection_tokens, self.num_labels + 1) ) self.parent.assertEqual(result.pred_boxes.shape , (self.batch_size, self.num_detection_tokens, 4) ) def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = config_and_inputs SCREAMING_SNAKE_CASE__ : str = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class __a (UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[int] = (YolosModel, YolosForObjectDetection) if is_torch_available() else () _SCREAMING_SNAKE_CASE :List[Any] = ( {"""feature-extraction""": YolosModel, """object-detection""": YolosForObjectDetection} if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE :str = False _SCREAMING_SNAKE_CASE :Union[str, Any] = False _SCREAMING_SNAKE_CASE :Any = False _SCREAMING_SNAKE_CASE :Tuple = False def _a ( self , _a , _a , _a=False ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = super()._prepare_for_class(_a , _a , return_labels=_a ) if return_labels: if model_class.__name__ == "YolosForObjectDetection": SCREAMING_SNAKE_CASE__ : Tuple = [] for i in range(self.model_tester.batch_size ): SCREAMING_SNAKE_CASE__ : List[Any] = {} SCREAMING_SNAKE_CASE__ : str = torch.ones( size=(self.model_tester.n_targets,) , device=_a , dtype=torch.long ) SCREAMING_SNAKE_CASE__ : Dict = torch.ones( self.model_tester.n_targets , 4 , device=_a , dtype=torch.float ) labels.append(_a ) SCREAMING_SNAKE_CASE__ : List[str] = labels return inputs_dict def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = YolosModelTester(self ) SCREAMING_SNAKE_CASE__ : Any = ConfigTester(self , config_class=_a , has_text_modality=_a , hidden_size=37 ) def _a ( self ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() def _a ( self ) -> List[str]: """simple docstring""" pass def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : int = model_class(_a ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_a , nn.Linear ) ) def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : Union[str, Any] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Optional[int] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _a ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Any = True # in YOLOS, the seq_len is different SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.expected_seq_len for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[Any] = True SCREAMING_SNAKE_CASE__ : Any = False SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : str = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Dict = model(**self._prepare_for_class(_a , _a ) ) SCREAMING_SNAKE_CASE__ : str = outputs.attentions self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] SCREAMING_SNAKE_CASE__ : List[str] = True SCREAMING_SNAKE_CASE__ : List[str] = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[int] = model(**self._prepare_for_class(_a , _a ) ) SCREAMING_SNAKE_CASE__ : Tuple = outputs.attentions self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = len(_a ) # Check attention is always last and order is fine SCREAMING_SNAKE_CASE__ : str = True SCREAMING_SNAKE_CASE__ : List[str] = True SCREAMING_SNAKE_CASE__ : List[Any] = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : str = model(**self._prepare_for_class(_a , _a ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = 1 self.assertEqual(out_len + added_hidden_states , len(_a ) ) SCREAMING_SNAKE_CASE__ : int = outputs.attentions self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) def _a ( self ) -> str: """simple docstring""" def check_hidden_states_output(_a , _a , _a ): SCREAMING_SNAKE_CASE__ : int = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(**self._prepare_for_class(_a , _a ) ) SCREAMING_SNAKE_CASE__ : Any = outputs.hidden_states SCREAMING_SNAKE_CASE__ : Optional[int] = getattr( self.model_tester , """expected_num_hidden_layers""" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(_a ) , _a ) # YOLOS has a different seq_length SCREAMING_SNAKE_CASE__ : int = self.model_tester.expected_seq_len self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Dict = True check_hidden_states_output(_a , _a , _a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : Union[str, Any] = True check_hidden_states_output(_a , _a , _a ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_object_detection(*_a ) @slow def _a ( self ) -> Optional[Any]: """simple docstring""" for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[int] = YolosModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def _lowercase ( ) -> Any: SCREAMING_SNAKE_CASE__ : Tuple = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class __a (unittest.TestCase): '''simple docstring''' @cached_property def _a ( self ) -> Optional[Any]: """simple docstring""" return AutoImageProcessor.from_pretrained("""hustvl/yolos-small""" ) if is_vision_available() else None @slow def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = YolosForObjectDetection.from_pretrained("""hustvl/yolos-small""" ).to(_a ) SCREAMING_SNAKE_CASE__ : Dict = self.default_image_processor SCREAMING_SNAKE_CASE__ : Any = prepare_img() SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(images=_a , return_tensors="""pt""" ).to(_a ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[Any] = model(inputs.pixel_values ) # verify outputs SCREAMING_SNAKE_CASE__ : str = torch.Size((1, 100, 92) ) self.assertEqual(outputs.logits.shape , _a ) SCREAMING_SNAKE_CASE__ : int = torch.tensor( [[-24.0_248, -10.3_024, -14.8_290], [-42.0_392, -16.8_200, -27.4_334], [-27.2_743, -11.8_154, -18.7_148]] , device=_a , ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor( [[0.2_559, 0.5_455, 0.4_706], [0.2_989, 0.7_279, 0.1_875], [0.7_732, 0.4_017, 0.4_462]] , device=_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , _a , atol=1E-4 ) ) self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3] , _a , atol=1E-4 ) ) # verify postprocessing SCREAMING_SNAKE_CASE__ : List[Any] = image_processor.post_process_object_detection( _a , threshold=0.3 , target_sizes=[image.size[::-1]] )[0] SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor([0.9_994, 0.9_790, 0.9_964, 0.9_972, 0.9_861] ).to(_a ) SCREAMING_SNAKE_CASE__ : List[str] = [75, 75, 17, 63, 17] SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([335.0_609, 79.3_848, 375.4_216, 187.2_495] ).to(_a ) self.assertEqual(len(results["""scores"""] ) , 5 ) self.assertTrue(torch.allclose(results["""scores"""] , _a , atol=1E-4 ) ) self.assertSequenceEqual(results["""labels"""].tolist() , _a ) self.assertTrue(torch.allclose(results["""boxes"""][0, :] , _a ) )
680
"""simple docstring""" def _lowercase ( __lowerCAmelCase = 200_0000 ) -> int: SCREAMING_SNAKE_CASE__ : int = [0 for i in range(n + 1 )] SCREAMING_SNAKE_CASE__ : str = 1 SCREAMING_SNAKE_CASE__ : str = 1 for i in range(2 , int(n**0.5 ) + 1 ): if primality_list[i] == 0: for j in range(i * i , n + 1 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 for i in range(__lowerCAmelCase ): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(f'{solution() = }')
680
1
"""simple docstring""" def _lowercase ( __lowerCAmelCase = 10**12 ) -> int: SCREAMING_SNAKE_CASE__ : str = 1 SCREAMING_SNAKE_CASE__ : Optional[int] = 0 SCREAMING_SNAKE_CASE__ : Optional[int] = 1 SCREAMING_SNAKE_CASE__ : List[str] = 1 while numerator <= 2 * min_total - 1: prev_numerator += 2 * numerator numerator += 2 * prev_numerator prev_denominator += 2 * denominator denominator += 2 * prev_denominator return (denominator + 1) // 2 if __name__ == "__main__": print(f'{solution() = }')
680
"""simple docstring""" import numpy as np import qiskit def _lowercase ( __lowerCAmelCase = 8 , __lowerCAmelCase = None ) -> str: SCREAMING_SNAKE_CASE__ : List[Any] = np.random.default_rng(seed=__lowerCAmelCase ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. SCREAMING_SNAKE_CASE__ : List[str] = 6 * key_len # Measurement basis for Alice's qubits. SCREAMING_SNAKE_CASE__ : List[Any] = rng.integers(2 , size=__lowerCAmelCase ) # The set of states Alice will prepare. SCREAMING_SNAKE_CASE__ : Optional[Any] = rng.integers(2 , size=__lowerCAmelCase ) # Measurement basis for Bob's qubits. SCREAMING_SNAKE_CASE__ : str = rng.integers(2 , size=__lowerCAmelCase ) # Quantum Circuit to simulate BB84 SCREAMING_SNAKE_CASE__ : Union[str, Any] = qiskit.QuantumCircuit(__lowerCAmelCase , name="""BB84""" ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(__lowerCAmelCase ): if alice_state[index] == 1: bbaa_circ.x(__lowerCAmelCase ) if alice_basis[index] == 1: bbaa_circ.h(__lowerCAmelCase ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(__lowerCAmelCase ): if bob_basis[index] == 1: bbaa_circ.h(__lowerCAmelCase ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. SCREAMING_SNAKE_CASE__ : str = qiskit.Aer.get_backend("""aer_simulator""" ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. SCREAMING_SNAKE_CASE__ : Optional[int] = qiskit.execute(__lowerCAmelCase , __lowerCAmelCase , shots=1 , seed_simulator=__lowerCAmelCase ) # Returns the result of measurement. SCREAMING_SNAKE_CASE__ : int = job.result().get_counts(__lowerCAmelCase ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. SCREAMING_SNAKE_CASE__ : Optional[Any] = """""".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. SCREAMING_SNAKE_CASE__ : Optional[int] = gen_key[:key_len] if len(__lowerCAmelCase ) >= key_len else gen_key.ljust(__lowerCAmelCase , """0""" ) return key if __name__ == "__main__": print(f'The generated key is : {bbaa(8, seed=0)}') from doctest import testmod testmod()
680
1
"""simple docstring""" import argparse import torch from safetensors.torch import load_file from diffusers import StableDiffusionPipeline def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Any: # load base model SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionPipeline.from_pretrained(__lowerCAmelCase , torch_dtype=torch.floataa ) # load LoRA weight from .safetensors SCREAMING_SNAKE_CASE__ : Any = load_file(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = [] # directly update weight in diffusers model for key in state_dict: # it is suggested to print out the key, it usually will be something like below # "lora_te_text_model_encoder_layers_0_self_attn_k_proj.lora_down.weight" # as we have set the alpha beforehand, so just skip if ".alpha" in key or key in visited: continue if "text" in key: SCREAMING_SNAKE_CASE__ : Dict = key.split(""".""" )[0].split(LORA_PREFIX_TEXT_ENCODER + """_""" )[-1].split("""_""" ) SCREAMING_SNAKE_CASE__ : int = pipeline.text_encoder else: SCREAMING_SNAKE_CASE__ : Tuple = key.split(""".""" )[0].split(LORA_PREFIX_UNET + """_""" )[-1].split("""_""" ) SCREAMING_SNAKE_CASE__ : List[str] = pipeline.unet # find the target layer SCREAMING_SNAKE_CASE__ : Optional[int] = layer_infos.pop(0 ) while len(__lowerCAmelCase ) > -1: try: SCREAMING_SNAKE_CASE__ : Dict = curr_layer.__getattr__(__lowerCAmelCase ) if len(__lowerCAmelCase ) > 0: SCREAMING_SNAKE_CASE__ : Optional[int] = layer_infos.pop(0 ) elif len(__lowerCAmelCase ) == 0: break except Exception: if len(__lowerCAmelCase ) > 0: temp_name += "_" + layer_infos.pop(0 ) else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = layer_infos.pop(0 ) SCREAMING_SNAKE_CASE__ : Dict = [] if "lora_down" in key: pair_keys.append(key.replace("""lora_down""" , """lora_up""" ) ) pair_keys.append(__lowerCAmelCase ) else: pair_keys.append(__lowerCAmelCase ) pair_keys.append(key.replace("""lora_up""" , """lora_down""" ) ) # update weight if len(state_dict[pair_keys[0]].shape ) == 4: SCREAMING_SNAKE_CASE__ : Union[str, Any] = state_dict[pair_keys[0]].squeeze(3 ).squeeze(2 ).to(torch.floataa ) SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict[pair_keys[1]].squeeze(3 ).squeeze(2 ).to(torch.floataa ) curr_layer.weight.data += alpha * torch.mm(__lowerCAmelCase , __lowerCAmelCase ).unsqueeze(2 ).unsqueeze(3 ) else: SCREAMING_SNAKE_CASE__ : str = state_dict[pair_keys[0]].to(torch.floataa ) SCREAMING_SNAKE_CASE__ : List[str] = state_dict[pair_keys[1]].to(torch.floataa ) curr_layer.weight.data += alpha * torch.mm(__lowerCAmelCase , __lowerCAmelCase ) # update visited list for item in pair_keys: visited.append(__lowerCAmelCase ) return pipeline if __name__ == "__main__": a :Optional[int] = argparse.ArgumentParser() parser.add_argument( "--base_model_path", default=None, type=str, required=True, help="Path to the base model in diffusers format." ) parser.add_argument( "--checkpoint_path", default=None, type=str, required=True, help="Path to the checkpoint to convert." ) parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.") parser.add_argument( "--lora_prefix_unet", default="lora_unet", type=str, help="The prefix of UNet weight in safetensors" ) parser.add_argument( "--lora_prefix_text_encoder", default="lora_te", type=str, help="The prefix of text encoder weight in safetensors", ) parser.add_argument("--alpha", default=0.75, type=float, help="The merging ratio in W = W0 + alpha * deltaW") parser.add_argument( "--to_safetensors", action="store_true", help="Whether to store pipeline in safetensors format or not." ) parser.add_argument("--device", type=str, help="Device to use (e.g. cpu, cuda:0, cuda:1, etc.)") a :Any = parser.parse_args() a :List[str] = args.base_model_path a :Tuple = args.checkpoint_path a :Union[str, Any] = args.dump_path a :List[Any] = args.lora_prefix_unet a :int = args.lora_prefix_text_encoder a :Dict = args.alpha a :Any = convert(base_model_path, checkpoint_path, lora_prefix_unet, lora_prefix_text_encoder, alpha) a :Optional[int] = pipe.to(args.device) pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
680
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __a (UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :str = StableDiffusionInpaintPipeline _SCREAMING_SNAKE_CASE :Any = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS _SCREAMING_SNAKE_CASE :Dict = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS _SCREAMING_SNAKE_CASE :Optional[int] = frozenset( []) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _SCREAMING_SNAKE_CASE :Dict = frozenset([]) def _a ( self ) -> Dict: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , 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 , ) SCREAMING_SNAKE_CASE__ : List[str] = PNDMScheduler(skip_prk_steps=_a ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = 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 ) SCREAMING_SNAKE_CASE__ : int = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) SCREAMING_SNAKE_CASE__ : int = CLIPTextModel(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) SCREAMING_SNAKE_CASE__ : int = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def _a ( self , _a , _a=0 ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = floats_tensor((1, 3, 32, 32) , rng=random.Random(_a ) ).to(_a ) SCREAMING_SNAKE_CASE__ : Tuple = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : Any = Image.fromarray(np.uinta(_a ) ).convert("""RGB""" ).resize((64, 64) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(_a ).startswith("""mps""" ): SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(_a ) else: SCREAMING_SNAKE_CASE__ : str = torch.Generator(device=_a ).manual_seed(_a ) SCREAMING_SNAKE_CASE__ : Tuple = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInpaintPipeline(**_a ) SCREAMING_SNAKE_CASE__ : Any = sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : int = self.get_dummy_inputs(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe(**_a ).images SCREAMING_SNAKE_CASE__ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : str = np.array([0.4_727, 0.5_735, 0.3_941, 0.5_446, 0.5_926, 0.4_394, 0.5_062, 0.4_654, 0.4_476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _a ( self ) -> Optional[int]: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : Any = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : Any = StableDiffusionInpaintPipeline.from_pretrained(_a , safety_checker=_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : int = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Tuple = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : int = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) SCREAMING_SNAKE_CASE__ : List[str] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInpaintPipeline.from_pretrained( _a , torch_dtype=torch.floataa , safety_checker=_a , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Any = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Tuple = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def _a ( self ) -> Tuple: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE__ : Dict = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : str = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : List[str] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : Dict = PNDMScheduler.from_pretrained(_a , subfolder="""scheduler""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = StableDiffusionInpaintPipeline.from_pretrained( _a , safety_checker=_a , scheduler=_a , torch_dtype=torch.floataa , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE__ : Union[str, Any] = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , num_inference_steps=2 , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : List[str] = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
680
1
"""simple docstring""" import os import time import pytest from datasets.utils.filelock import FileLock, Timeout def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Dict = FileLock(str(tmpdir / """foo.lock""" ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = FileLock(str(tmpdir / """foo.lock""" ) ) SCREAMING_SNAKE_CASE__ : str = 0.01 with locka.acquire(): with pytest.raises(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = time.time() locka.acquire(__lowerCAmelCase ) assert time.time() - _start > timeout def _lowercase ( __lowerCAmelCase ) -> Any: SCREAMING_SNAKE_CASE__ : List[str] = """a""" * 1000 + """.lock""" SCREAMING_SNAKE_CASE__ : Dict = FileLock(str(tmpdir / filename ) ) assert locka._lock_file.endswith(""".lock""" ) assert not locka._lock_file.endswith(__lowerCAmelCase ) assert len(os.path.basename(locka._lock_file ) ) <= 255 SCREAMING_SNAKE_CASE__ : Union[str, Any] = FileLock(tmpdir / filename ) with locka.acquire(): with pytest.raises(__lowerCAmelCase ): locka.acquire(0 )
680
"""simple docstring""" import argparse import logging import pickle import random import time import numpy as np from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) a :str = logging.getLogger(__name__) def _lowercase ( ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Dict = argparse.ArgumentParser( description="""Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids).""" ) parser.add_argument("""--file_path""" , type=__lowerCAmelCase , default="""data/dump.txt""" , help="""The path to the data.""" ) parser.add_argument("""--tokenizer_type""" , type=__lowerCAmelCase , default="""bert""" , choices=["""bert""", """roberta""", """gpt2"""] ) parser.add_argument("""--tokenizer_name""" , type=__lowerCAmelCase , default="""bert-base-uncased""" , help="""The tokenizer to use.""" ) parser.add_argument("""--dump_file""" , type=__lowerCAmelCase , default="""data/dump""" , help="""The dump file prefix.""" ) SCREAMING_SNAKE_CASE__ : str = parser.parse_args() logger.info(F'''Loading Tokenizer ({args.tokenizer_name})''' ) if args.tokenizer_type == "bert": SCREAMING_SNAKE_CASE__ : List[str] = BertTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : str = tokenizer.special_tokens_map["""cls_token"""] # `[CLS]` SCREAMING_SNAKE_CASE__ : str = tokenizer.special_tokens_map["""sep_token"""] # `[SEP]` elif args.tokenizer_type == "roberta": SCREAMING_SNAKE_CASE__ : List[Any] = RobertaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.special_tokens_map["""cls_token"""] # `<s>` SCREAMING_SNAKE_CASE__ : Dict = tokenizer.special_tokens_map["""sep_token"""] # `</s>` elif args.tokenizer_type == "gpt2": SCREAMING_SNAKE_CASE__ : List[Any] = GPTaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.special_tokens_map["""bos_token"""] # `<|endoftext|>` SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.special_tokens_map["""eos_token"""] # `<|endoftext|>` logger.info(F'''Loading text from {args.file_path}''' ) with open(args.file_path , """r""" , encoding="""utf8""" ) as fp: SCREAMING_SNAKE_CASE__ : int = fp.readlines() logger.info("""Start encoding""" ) logger.info(F'''{len(__lowerCAmelCase )} examples to process.''' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1_0000 SCREAMING_SNAKE_CASE__ : Dict = time.time() for text in data: SCREAMING_SNAKE_CASE__ : Dict = F'''{bos} {text.strip()} {sep}''' SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) rslt.append(__lowerCAmelCase ) iter += 1 if iter % interval == 0: SCREAMING_SNAKE_CASE__ : str = time.time() logger.info(F'''{iter} examples processed. - {(end-start):.2f}s/{interval}expl''' ) SCREAMING_SNAKE_CASE__ : Tuple = time.time() logger.info("""Finished binarization""" ) logger.info(F'''{len(__lowerCAmelCase )} examples processed.''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = F'''{args.dump_file}.{args.tokenizer_name}.pickle''' SCREAMING_SNAKE_CASE__ : Dict = tokenizer.vocab_size if vocab_size < (1 << 16): SCREAMING_SNAKE_CASE__ : Tuple = [np.uintaa(__lowerCAmelCase ) for d in rslt] else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [np.intaa(__lowerCAmelCase ) for d in rslt] random.shuffle(rslt_ ) logger.info(F'''Dump to {dp_file}''' ) with open(__lowerCAmelCase , """wb""" ) as handle: pickle.dump(rslt_ , __lowerCAmelCase , protocol=pickle.HIGHEST_PROTOCOL ) if __name__ == "__main__": main()
680
1
"""simple docstring""" def _lowercase ( __lowerCAmelCase = 10 ) -> str: if not isinstance(__lowerCAmelCase , __lowerCAmelCase ) or n < 0: raise ValueError("""Invalid input""" ) SCREAMING_SNAKE_CASE__ : List[str] = 10**n SCREAMING_SNAKE_CASE__ : Optional[Any] = 2_8433 * (pow(2 , 783_0457 , __lowerCAmelCase )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(f'{solution(10) = }')
680
"""simple docstring""" import glob import os import random from string import ascii_lowercase, digits import cva a :List[Any] = "" a :Union[str, Any] = "" a :List[str] = "" a :str = 1 # (0 is vertical, 1 is horizontal) def _lowercase ( ) -> None: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = get_dataset(__lowerCAmelCase , __lowerCAmelCase ) print("""Processing...""" ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = update_image_and_anno(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) for index, image in enumerate(__lowerCAmelCase ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' SCREAMING_SNAKE_CASE__ : List[Any] = random_chars(32 ) SCREAMING_SNAKE_CASE__ : List[str] = paths[index].split(os.sep )[-1].rsplit(""".""" , 1 )[0] SCREAMING_SNAKE_CASE__ : List[str] = F'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(F'''/{file_root}.jpg''' , __lowerCAmelCase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F'''Success {index+1}/{len(__lowerCAmelCase )} with {file_name}''' ) SCREAMING_SNAKE_CASE__ : int = [] for anno in new_annos[index]: SCREAMING_SNAKE_CASE__ : Tuple = F'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(__lowerCAmelCase ) with open(F'''/{file_root}.txt''' , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> tuple[list, list]: SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] for label_file in glob.glob(os.path.join(__lowerCAmelCase , """*.txt""" ) ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(__lowerCAmelCase ) as in_file: SCREAMING_SNAKE_CASE__ : Dict = in_file.readlines() SCREAMING_SNAKE_CASE__ : int = os.path.join(__lowerCAmelCase , F'''{label_name}.jpg''' ) SCREAMING_SNAKE_CASE__ : int = [] for obj_list in obj_lists: SCREAMING_SNAKE_CASE__ : Optional[int] = obj_list.rstrip("""\n""" ).split(""" """ ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(__lowerCAmelCase ) labels.append(__lowerCAmelCase ) return img_paths, labels def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = 1 ) -> tuple[list, list, list]: SCREAMING_SNAKE_CASE__ : Dict = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [] for idx in range(len(__lowerCAmelCase ) ): SCREAMING_SNAKE_CASE__ : List[str] = [] SCREAMING_SNAKE_CASE__ : str = img_list[idx] path_list.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = anno_list[idx] SCREAMING_SNAKE_CASE__ : Tuple = cva.imread(__lowerCAmelCase ) if flip_type == 1: SCREAMING_SNAKE_CASE__ : int = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: SCREAMING_SNAKE_CASE__ : Optional[int] = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: SCREAMING_SNAKE_CASE__ : Any = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: SCREAMING_SNAKE_CASE__ : List[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(__lowerCAmelCase ) new_imgs_list.append(__lowerCAmelCase ) return new_imgs_list, new_annos_lists, path_list def _lowercase ( __lowerCAmelCase = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" SCREAMING_SNAKE_CASE__ : List[str] = ascii_lowercase + digits return "".join(random.choice(__lowerCAmelCase ) for _ in range(__lowerCAmelCase ) ) if __name__ == "__main__": main() print("DONE ✅")
680
1
"""simple docstring""" from __future__ import annotations def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> list[int]: SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 SCREAMING_SNAKE_CASE__ : Dict = len(__lowerCAmelCase ) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: SCREAMING_SNAKE_CASE__ : Optional[int] = i + 1 else: SCREAMING_SNAKE_CASE__ : str = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(f'{two_pointer([2, 7, 11, 15], 9) = }')
680
"""simple docstring""" import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class __a (enum.Enum): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = 0 _SCREAMING_SNAKE_CASE :List[Any] = 1 _SCREAMING_SNAKE_CASE :Dict = 2 @add_end_docstrings(UpperCamelCase_) class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = """ In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision and denounces one of the men as a horse thief. Although his father initially slaps him for making such an accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop, begging for his blessing. <eod> </s> <eos> """ def __init__( self , *_a , **_a ) -> Tuple: """simple docstring""" super().__init__(*_a , **_a ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == """tf""" else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. SCREAMING_SNAKE_CASE__ : Any = None if self.model.config.prefix is not None: SCREAMING_SNAKE_CASE__ : List[str] = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. SCREAMING_SNAKE_CASE__ : Optional[Any] = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self._sanitize_parameters(prefix=_a , **self._forward_params ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {**self._preprocess_params, **preprocess_params} SCREAMING_SNAKE_CASE__ : Optional[Any] = {**self._forward_params, **forward_params} def _a ( self , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , **_a , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = {} if prefix is not None: SCREAMING_SNAKE_CASE__ : Dict = prefix if prefix: SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer( _a , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Tuple = prefix_inputs["""input_ids"""].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( f'''{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected''' """ [None, 'hole']""" ) SCREAMING_SNAKE_CASE__ : int = handle_long_generation preprocess_params.update(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs SCREAMING_SNAKE_CASE__ : int = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_full_text`""" ) if return_tensors is not None: raise ValueError("""`return_full_text` is mutually exclusive with `return_tensors`""" ) SCREAMING_SNAKE_CASE__ : List[Any] = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_tensors`""" ) SCREAMING_SNAKE_CASE__ : Tuple = ReturnType.TENSORS if return_type is not None: SCREAMING_SNAKE_CASE__ : int = return_type if clean_up_tokenization_spaces is not None: SCREAMING_SNAKE_CASE__ : List[str] = clean_up_tokenization_spaces if stop_sequence is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.encode(_a , add_special_tokens=_a ) if len(_a ) > 1: warnings.warn( """Stopping on a multiple token sequence is not yet supported on transformers. The first token of""" """ the stop sequence will be used as the stop sequence string in the interim.""" ) SCREAMING_SNAKE_CASE__ : List[Any] = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def _a ( self , *_a , **_a ) -> Any: """simple docstring""" if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({"""add_space_before_punct_symbol""": True} ) return super()._parse_and_tokenize(*_a , **_a ) def __call__( self , _a , **_a ) -> Optional[int]: """simple docstring""" return super().__call__(_a , **_a ) def _a ( self , _a , _a="" , _a=None , **_a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer( prefix + prompt_text , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Tuple = prompt_text if handle_long_generation == "hole": SCREAMING_SNAKE_CASE__ : List[Any] = inputs["""input_ids"""].shape[-1] if "max_new_tokens" in generate_kwargs: SCREAMING_SNAKE_CASE__ : Union[str, Any] = generate_kwargs["""max_new_tokens"""] else: SCREAMING_SNAKE_CASE__ : Tuple = generate_kwargs.get("""max_length""" , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError("""We cannot infer how many new tokens are expected""" ) if cur_len + new_tokens > self.tokenizer.model_max_length: SCREAMING_SNAKE_CASE__ : str = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( """We cannot use `hole` to handle this generation the number of desired tokens exceeds the""" """ models max length""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs["""input_ids"""][:, -keep_length:] if "attention_mask" in inputs: SCREAMING_SNAKE_CASE__ : Optional[int] = inputs["""attention_mask"""][:, -keep_length:] return inputs def _a ( self , _a , **_a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_inputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : Optional[int] = model_inputs.get("""attention_mask""" , _a ) # Allow empty prompts if input_ids.shape[1] == 0: SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : List[Any] = None SCREAMING_SNAKE_CASE__ : List[str] = 1 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.shape[0] SCREAMING_SNAKE_CASE__ : Tuple = model_inputs.pop("""prompt_text""" ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs.pop("""prefix_length""" , 0 ) if prefix_length > 0: SCREAMING_SNAKE_CASE__ : List[str] = """max_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].max_new_tokens is not None ) if not has_max_new_tokens: SCREAMING_SNAKE_CASE__ : int = generate_kwargs.get("""max_length""" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length SCREAMING_SNAKE_CASE__ : Dict = """min_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL SCREAMING_SNAKE_CASE__ : Tuple = self.model.generate(input_ids=_a , attention_mask=_a , **_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = generated_sequence.shape[0] if self.framework == "pt": SCREAMING_SNAKE_CASE__ : str = generated_sequence.reshape(_a , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.reshape(_a , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def _a ( self , _a , _a=ReturnType.FULL_TEXT , _a=True ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = model_outputs["""generated_sequence"""][0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_outputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : str = model_outputs["""prompt_text"""] SCREAMING_SNAKE_CASE__ : Any = generated_sequence.numpy().tolist() SCREAMING_SNAKE_CASE__ : List[Any] = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: SCREAMING_SNAKE_CASE__ : Tuple = {"""generated_token_ids""": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.decode( _a , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: SCREAMING_SNAKE_CASE__ : Dict = 0 else: SCREAMING_SNAKE_CASE__ : Optional[int] = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) ) if return_type == ReturnType.FULL_TEXT: SCREAMING_SNAKE_CASE__ : Tuple = prompt_text + text[prompt_length:] else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = text[prompt_length:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {"""generated_text""": all_text} records.append(_a ) return records
680
1
"""simple docstring""" from __future__ import annotations def _lowercase ( __lowerCAmelCase , __lowerCAmelCase = None , __lowerCAmelCase = None , __lowerCAmelCase = False , ) -> tuple[int, float, str]: SCREAMING_SNAKE_CASE__ : int = cipher_alphabet or [chr(__lowerCAmelCase ) for i in range(97 , 123 )] # If the argument is None or the user provided an empty dictionary if not frequencies_dict: # Frequencies of letters in the english language (how much they show up) SCREAMING_SNAKE_CASE__ : Dict = { """a""": 0.08_497, """b""": 0.01_492, """c""": 0.02_202, """d""": 0.04_253, """e""": 0.11_162, """f""": 0.02_228, """g""": 0.02_015, """h""": 0.06_094, """i""": 0.07_546, """j""": 0.00_153, """k""": 0.01_292, """l""": 0.04_025, """m""": 0.02_406, """n""": 0.06_749, """o""": 0.07_507, """p""": 0.01_929, """q""": 0.00_095, """r""": 0.07_587, """s""": 0.06_327, """t""": 0.09_356, """u""": 0.02_758, """v""": 0.00_978, """w""": 0.02_560, """x""": 0.00_150, """y""": 0.01_994, """z""": 0.00_077, } else: # Custom frequencies dictionary SCREAMING_SNAKE_CASE__ : Optional[int] = frequencies_dict if not case_sensitive: SCREAMING_SNAKE_CASE__ : int = ciphertext.lower() # Chi squared statistic values SCREAMING_SNAKE_CASE__ : dict[int, tuple[float, str]] = {} # cycle through all of the shifts for shift in range(len(__lowerCAmelCase ) ): SCREAMING_SNAKE_CASE__ : Optional[int] = """""" # decrypt the message with the shift for letter in ciphertext: try: # Try to index the letter in the alphabet SCREAMING_SNAKE_CASE__ : Optional[Any] = (alphabet_letters.index(letter.lower() ) - shift) % len( __lowerCAmelCase ) decrypted_with_shift += ( alphabet_letters[new_key].upper() if case_sensitive and letter.isupper() else alphabet_letters[new_key] ) except ValueError: # Append the character if it isn't in the alphabet decrypted_with_shift += letter SCREAMING_SNAKE_CASE__ : Any = 0.0 # Loop through each letter in the decoded message with the shift for letter in decrypted_with_shift: if case_sensitive: SCREAMING_SNAKE_CASE__ : Optional[int] = letter.lower() if letter in frequencies: # Get the amount of times the letter occurs in the message SCREAMING_SNAKE_CASE__ : List[Any] = decrypted_with_shift.lower().count(__lowerCAmelCase ) # Get the excepcted amount of times the letter should appear based # on letter frequencies SCREAMING_SNAKE_CASE__ : List[str] = frequencies[letter] * occurrences # Complete the chi squared statistic formula SCREAMING_SNAKE_CASE__ : int = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value else: if letter.lower() in frequencies: # Get the amount of times the letter occurs in the message SCREAMING_SNAKE_CASE__ : List[Any] = decrypted_with_shift.count(__lowerCAmelCase ) # Get the excepcted amount of times the letter should appear based # on letter frequencies SCREAMING_SNAKE_CASE__ : Tuple = frequencies[letter] * occurrences # Complete the chi squared statistic formula SCREAMING_SNAKE_CASE__ : int = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value # Add the data to the chi_squared_statistic_values dictionary SCREAMING_SNAKE_CASE__ : int = ( chi_squared_statistic, decrypted_with_shift, ) # Get the most likely cipher by finding the cipher with the smallest chi squared # statistic def chi_squared_statistic_values_sorting_key(__lowerCAmelCase ) -> tuple[float, str]: return chi_squared_statistic_values[key] SCREAMING_SNAKE_CASE__ : int = min( __lowerCAmelCase , key=__lowerCAmelCase , ) # Get all the data from the most likely cipher (key, decoded message) ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Union[str, Any] = chi_squared_statistic_values[most_likely_cipher] # Return the data on the most likely shift return ( most_likely_cipher, most_likely_cipher_chi_squared_value, decoded_most_likely_cipher, )
680
"""simple docstring""" from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> list[float]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = coefficient_matrix.shape SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE__ : Tuple = F'''Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if colsa != 1: SCREAMING_SNAKE_CASE__ : str = F'''Constant matrix must be nx1 but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if rowsa != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Coefficient and constant matrices dimensions must be nxn and nx1 but """ F'''received {rowsa}x{colsa} and {rowsa}x{colsa}''' ) raise ValueError(__lowerCAmelCase ) if len(__lowerCAmelCase ) != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Number of initial values must be equal to number of rows in coefficient """ F'''matrix but received {len(__lowerCAmelCase )} and {rowsa}''' ) raise ValueError(__lowerCAmelCase ) if iterations <= 0: raise ValueError("""Iterations must be at least 1""" ) SCREAMING_SNAKE_CASE__ : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = table.shape strictly_diagonally_dominant(__lowerCAmelCase ) # Iterates the whole matrix for given number of times for _ in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = [] for row in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = 0 for col in range(__lowerCAmelCase ): if col == row: SCREAMING_SNAKE_CASE__ : int = table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE__ : Any = (temp + val) / denom new_val.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = new_val return [float(__lowerCAmelCase ) for i in new_val] def _lowercase ( __lowerCAmelCase ) -> bool: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = table.shape SCREAMING_SNAKE_CASE__ : str = True for i in range(0 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("""Coefficient matrix is not strictly diagonally dominant""" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
680
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 ( ImageTextPipelineOutput, UniDiffuserPipeline, ) else: from .modeling_text_decoder import UniDiffuserTextDecoder from .modeling_uvit import UniDiffuserModel, UTransformeraDModel from .pipeline_unidiffuser import ImageTextPipelineOutput, UniDiffuserPipeline
680
"""simple docstring""" import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Union[str, Path]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = True _SCREAMING_SNAKE_CASE :Optional[int] = None _SCREAMING_SNAKE_CASE :int = 1 _SCREAMING_SNAKE_CASE :Optional[Union[str, bool]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None def _a ( self ) -> "DownloadConfig": """simple docstring""" return self.__class__(**{k: copy.deepcopy(_a ) for k, v in self.__dict__.items()} )
680
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) a :str = { "configuration_lxmert": ["LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "LxmertConfig"], "tokenization_lxmert": ["LxmertTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :List[Any] = ["LxmertTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :List[str] = [ "LxmertEncoder", "LxmertForPreTraining", "LxmertForQuestionAnswering", "LxmertModel", "LxmertPreTrainedModel", "LxmertVisualFeatureEncoder", "LxmertXLayer", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Optional[int] = [ "TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFLxmertForPreTraining", "TFLxmertMainLayer", "TFLxmertModel", "TFLxmertPreTrainedModel", "TFLxmertVisualFeatureEncoder", ] if TYPE_CHECKING: from .configuration_lxmert import LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, LxmertConfig from .tokenization_lxmert import LxmertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_lxmert_fast import LxmertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lxmert import ( LxmertEncoder, LxmertForPreTraining, LxmertForQuestionAnswering, LxmertModel, LxmertPreTrainedModel, LxmertVisualFeatureEncoder, LxmertXLayer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_lxmert import ( TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFLxmertForPreTraining, TFLxmertMainLayer, TFLxmertModel, TFLxmertPreTrainedModel, TFLxmertVisualFeatureEncoder, ) else: import sys a :List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
"""simple docstring""" import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger a :Optional[Any] = "<<<<<<< This should probably be modified because it mentions: " a :Tuple = "=======\n>>>>>>>\n" a :str = [ "TextEncoderConfig", "ByteTextEncoder", "SubwordTextEncoder", "encoder_config", "maybe_build_from_corpus", "manual_dir", ] a :Union[str, Any] = [ # (pattern, replacement) # Order is important here for some replacements (r"tfds\.core", r"datasets"), (r"tf\.io\.gfile\.GFile", r"open"), (r"tf\.([\w\d]+)", r"datasets.Value('\1')"), (r"tfds\.features\.Text\(\)", r"datasets.Value('string')"), (r"tfds\.features\.Text\(", r"datasets.Value('string'),"), (r"features\s*=\s*tfds.features.FeaturesDict\(", r"features=datasets.Features("), (r"tfds\.features\.FeaturesDict\(", r"dict("), (r"The TensorFlow Datasets Authors", r"The TensorFlow Datasets Authors and the HuggingFace Datasets Authors"), (r"tfds\.", r"datasets."), (r"dl_manager\.manual_dir", r"self.config.data_dir"), (r"self\.builder_config", r"self.config"), ] def _lowercase ( __lowerCAmelCase ) -> int: return ConvertCommand(args.tfds_path , args.datasets_directory ) class __a (UpperCamelCase_): '''simple docstring''' @staticmethod def _a ( _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.add_parser( """convert""" , help="""Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.""" , ) train_parser.add_argument( """--tfds_path""" , type=_a , required=_a , help="""Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.""" , ) train_parser.add_argument( """--datasets_directory""" , type=_a , required=_a , help="""Path to the HuggingFace Datasets folder.""" ) train_parser.set_defaults(func=_a ) def __init__( self , _a , _a , *_a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = get_logger("""datasets-cli/converting""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tfds_path SCREAMING_SNAKE_CASE__ : List[Any] = datasets_directory def _a ( self ) -> List[str]: """simple docstring""" if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.abspath(self._tfds_path ) elif os.path.isfile(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Tuple = os.path.dirname(self._tfds_path ) else: raise ValueError("""--tfds_path is neither a directory nor a file. Please check path.""" ) SCREAMING_SNAKE_CASE__ : Dict = os.path.abspath(self._datasets_directory ) self._logger.info(f'''Converting datasets from {abs_tfds_path} to {abs_datasets_path}''' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : List[Any] = {} if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.listdir(_a ) else: SCREAMING_SNAKE_CASE__ : List[Any] = [os.path.basename(self._tfds_path )] for f_name in file_names: self._logger.info(f'''Looking at file {f_name}''' ) SCREAMING_SNAKE_CASE__ : int = os.path.join(_a , _a ) SCREAMING_SNAKE_CASE__ : Dict = os.path.join(_a , _a ) if not os.path.isfile(_a ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info("""Skipping file""" ) continue with open(_a , encoding="""utf-8""" ) as f: SCREAMING_SNAKE_CASE__ : List[str] = f.readlines() SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = False SCREAMING_SNAKE_CASE__ : Optional[int] = False SCREAMING_SNAKE_CASE__ : Dict = [] for line in lines: SCREAMING_SNAKE_CASE__ : List[str] = line # Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: SCREAMING_SNAKE_CASE__ : List[Any] = """import datasets\n""" elif "import tensorflow" in out_line: # order is important here SCREAMING_SNAKE_CASE__ : Optional[Any] = """""" continue elif "from absl import logging" in out_line: SCREAMING_SNAKE_CASE__ : Any = """from datasets import logging\n""" elif "getLogger" in out_line: SCREAMING_SNAKE_CASE__ : Optional[int] = out_line.replace("""getLogger""" , """get_logger""" ) elif any(expression in out_line for expression in TO_HIGHLIGHT ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Tuple = list(filter(lambda _a : e in out_line , _a ) ) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(_a ) + """\n""" ) out_lines.append(_a ) out_lines.append(_a ) continue else: for pattern, replacement in TO_CONVERT: SCREAMING_SNAKE_CASE__ : int = re.sub(_a , _a , _a ) # Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: SCREAMING_SNAKE_CASE__ : Dict = re.match(r"""from\stensorflow_datasets.*import\s([^\.\r\n]+)""" , _a ) tfds_imports.extend(imp.strip() for imp in match.group(1 ).split(""",""" ) ) SCREAMING_SNAKE_CASE__ : Dict = """from . import """ + match.group(1 ) # Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(f'''Error converting {out_line.strip()}''' ) if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line: SCREAMING_SNAKE_CASE__ : Union[str, Any] = True out_lines.append(_a ) if is_builder or "wmt" in f_name: # We create a new directory for each dataset SCREAMING_SNAKE_CASE__ : Union[str, Any] = f_name.replace(""".py""" , """""" ) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(_a , _a ) SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(_a , _a ) os.makedirs(_a , exist_ok=_a ) self._logger.info(f'''Adding directory {output_dir}''' ) imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} ) else: # Utilities will be moved at the end utils_files.append(_a ) if needs_manual_update: with_manual_update.append(_a ) with open(_a , """w""" , encoding="""utf-8""" ) as f: f.writelines(_a ) self._logger.info(f'''Converted in {output_file}''' ) for utils_file in utils_files: try: SCREAMING_SNAKE_CASE__ : str = os.path.basename(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = imports_to_builder_map[f_name.replace(""".py""" , """""" )] self._logger.info(f'''Moving {dest_folder} to {utils_file}''' ) shutil.copy(_a , _a ) except KeyError: self._logger.error(f'''Cannot find destination folder for {utils_file}. Please copy manually.''' ) if with_manual_update: for file_path in with_manual_update: self._logger.warning( f'''You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.''' )
680
1
"""simple docstring""" from timeit import timeit def _lowercase ( __lowerCAmelCase ) -> int: if number < 0: raise ValueError("""the value of input must not be negative""" ) SCREAMING_SNAKE_CASE__ : Dict = 0 while number: number &= number - 1 result += 1 return result def _lowercase ( __lowerCAmelCase ) -> int: if number < 0: raise ValueError("""the value of input must not be negative""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0 while number: if number % 2 == 1: result += 1 number >>= 1 return result def _lowercase ( ) -> None: def do_benchmark(__lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Any = """import __main__ as z""" print(F'''Benchmark when {number = }:''' ) print(F'''{get_set_bits_count_using_modulo_operator(__lowerCAmelCase ) = }''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = timeit("""z.get_set_bits_count_using_modulo_operator(25)""" , setup=__lowerCAmelCase ) print(F'''timeit() runs in {timing} seconds''' ) print(F'''{get_set_bits_count_using_brian_kernighans_algorithm(__lowerCAmelCase ) = }''' ) SCREAMING_SNAKE_CASE__ : int = timeit( """z.get_set_bits_count_using_brian_kernighans_algorithm(25)""" , setup=__lowerCAmelCase , ) print(F'''timeit() runs in {timing} seconds''' ) for number in (25, 37, 58, 0): do_benchmark(__lowerCAmelCase ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
680
"""simple docstring""" from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance a :str = 637_8137.0 a :Optional[Any] = 635_6752.31_4245 a :List[Any] = 6_378_137 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> float: SCREAMING_SNAKE_CASE__ : Dict = (AXIS_A - AXIS_B) / AXIS_A # Parametric latitudes # https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) # Compute central angle between two points # using haversine theta. sigma = haversine_distance / equatorial radius SCREAMING_SNAKE_CASE__ : Tuple = haversine_distance(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) / EQUATORIAL_RADIUS # Intermediate P and Q values SCREAMING_SNAKE_CASE__ : List[str] = (b_lata + b_lata) / 2 SCREAMING_SNAKE_CASE__ : Dict = (b_lata - b_lata) / 2 # Intermediate X value # X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2) SCREAMING_SNAKE_CASE__ : Tuple = (sin(__lowerCAmelCase ) ** 2) * (cos(__lowerCAmelCase ) ** 2) SCREAMING_SNAKE_CASE__ : str = cos(sigma / 2 ) ** 2 SCREAMING_SNAKE_CASE__ : List[str] = (sigma - sin(__lowerCAmelCase )) * (x_numerator / x_demonimator) # Intermediate Y value # Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2) SCREAMING_SNAKE_CASE__ : int = (cos(__lowerCAmelCase ) ** 2) * (sin(__lowerCAmelCase ) ** 2) SCREAMING_SNAKE_CASE__ : int = sin(sigma / 2 ) ** 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = (sigma + sin(__lowerCAmelCase )) * (y_numerator / y_denominator) return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value))) if __name__ == "__main__": import doctest doctest.testmod()
680
1
"""simple docstring""" from typing import List, Optional from tokenizers import ByteLevelBPETokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot_small import BlenderbotSmallTokenizer a :int = logging.get_logger(__name__) a :List[str] = { "vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_config_file": "tokenizer_config.json", } a :Dict = { "vocab_file": { "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json" }, "merges_file": { "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt" }, "tokenizer_config_file": { "facebook/blenderbot_small-90M": ( "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json" ) }, } a :List[Any] = { "facebook/blenderbot_small-90M": 512, } class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE :Optional[int] = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE :List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE :List[str] = BlenderbotSmallTokenizer def __init__( self , _a=None , _a=None , _a="<|endoftext|>" , _a="<|endoftext|>" , _a="<|endoftext|>" , _a=False , _a=True , **_a , ) -> Dict: """simple docstring""" super().__init__( ByteLevelBPETokenizer( vocab=_a , merges=_a , add_prefix_space=_a , trim_offsets=_a , ) , bos_token=_a , eos_token=_a , unk_token=_a , **_a , ) SCREAMING_SNAKE_CASE__ : Dict = add_prefix_space def _a ( self , _a , _a=None ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : Dict = [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]
680
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision.transforms import functional as F from transformers import DetrImageProcessor, TableTransformerConfig, TableTransformerForObjectDetection from transformers.utils import logging logging.set_verbosity_info() a :Any = logging.get_logger(__name__) # here we list all keys to be renamed (original name on the left, our name on the right) a :str = [] for i in range(6): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (f'transformer.encoder.layers.{i}.self_attn.out_proj.weight', f'encoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (f'transformer.encoder.layers.{i}.self_attn.out_proj.bias', f'encoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append((f'transformer.encoder.layers.{i}.linear1.weight', f'encoder.layers.{i}.fc1.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.linear1.bias', f'encoder.layers.{i}.fc1.bias')) rename_keys.append((f'transformer.encoder.layers.{i}.linear2.weight', f'encoder.layers.{i}.fc2.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.linear2.bias', f'encoder.layers.{i}.fc2.bias')) rename_keys.append( (f'transformer.encoder.layers.{i}.norm1.weight', f'encoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((f'transformer.encoder.layers.{i}.norm1.bias', f'encoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append((f'transformer.encoder.layers.{i}.norm2.weight', f'encoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.norm2.bias', f'encoder.layers.{i}.final_layer_norm.bias')) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( (f'transformer.decoder.layers.{i}.self_attn.out_proj.weight', f'decoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (f'transformer.decoder.layers.{i}.self_attn.out_proj.bias', f'decoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append( ( f'transformer.decoder.layers.{i}.multihead_attn.out_proj.weight', f'decoder.layers.{i}.encoder_attn.out_proj.weight', ) ) rename_keys.append( ( f'transformer.decoder.layers.{i}.multihead_attn.out_proj.bias', f'decoder.layers.{i}.encoder_attn.out_proj.bias', ) ) rename_keys.append((f'transformer.decoder.layers.{i}.linear1.weight', f'decoder.layers.{i}.fc1.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.linear1.bias', f'decoder.layers.{i}.fc1.bias')) rename_keys.append((f'transformer.decoder.layers.{i}.linear2.weight', f'decoder.layers.{i}.fc2.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.linear2.bias', f'decoder.layers.{i}.fc2.bias')) rename_keys.append( (f'transformer.decoder.layers.{i}.norm1.weight', f'decoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((f'transformer.decoder.layers.{i}.norm1.bias', f'decoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append( (f'transformer.decoder.layers.{i}.norm2.weight', f'decoder.layers.{i}.encoder_attn_layer_norm.weight') ) rename_keys.append( (f'transformer.decoder.layers.{i}.norm2.bias', f'decoder.layers.{i}.encoder_attn_layer_norm.bias') ) rename_keys.append((f'transformer.decoder.layers.{i}.norm3.weight', f'decoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.norm3.bias', f'decoder.layers.{i}.final_layer_norm.bias')) # convolutional projection + query embeddings + layernorm of encoder + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ("input_proj.weight", "input_projection.weight"), ("input_proj.bias", "input_projection.bias"), ("query_embed.weight", "query_position_embeddings.weight"), ("transformer.encoder.norm.weight", "encoder.layernorm.weight"), ("transformer.encoder.norm.bias", "encoder.layernorm.bias"), ("transformer.decoder.norm.weight", "decoder.layernorm.weight"), ("transformer.decoder.norm.bias", "decoder.layernorm.bias"), ("class_embed.weight", "class_labels_classifier.weight"), ("class_embed.bias", "class_labels_classifier.bias"), ("bbox_embed.layers.0.weight", "bbox_predictor.layers.0.weight"), ("bbox_embed.layers.0.bias", "bbox_predictor.layers.0.bias"), ("bbox_embed.layers.1.weight", "bbox_predictor.layers.1.weight"), ("bbox_embed.layers.1.bias", "bbox_predictor.layers.1.bias"), ("bbox_embed.layers.2.weight", "bbox_predictor.layers.2.weight"), ("bbox_embed.layers.2.bias", "bbox_predictor.layers.2.bias"), ] ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Tuple = state_dict.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = val def _lowercase ( __lowerCAmelCase ) -> Tuple: SCREAMING_SNAKE_CASE__ : str = OrderedDict() for key, value in state_dict.items(): if "backbone.0.body" in key: SCREAMING_SNAKE_CASE__ : List[Any] = key.replace("""backbone.0.body""" , """backbone.conv_encoder.model""" ) SCREAMING_SNAKE_CASE__ : Dict = value else: SCREAMING_SNAKE_CASE__ : Tuple = value return new_state_dict def _lowercase ( __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : str = """""" # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : int = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : int = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE__ : Any = in_proj_bias[:256] SCREAMING_SNAKE_CASE__ : Dict = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[256:512] SCREAMING_SNAKE_CASE__ : int = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[-256:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6 ): # read in weights + bias of input projection layer of self-attention SCREAMING_SNAKE_CASE__ : List[str] = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : Tuple = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Any = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[:256] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[256:512] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias[-256:] # read in weights + bias of input projection layer of cross-attention SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop( F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : List[Any] = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) of cross-attention to the state dict SCREAMING_SNAKE_CASE__ : int = in_proj_weight_cross_attn[:256, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias_cross_attn[:256] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight_cross_attn[256:512, :] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_bias_cross_attn[256:512] SCREAMING_SNAKE_CASE__ : int = in_proj_weight_cross_attn[-256:, :] SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias_cross_attn[-256:] def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = image.size SCREAMING_SNAKE_CASE__ : Optional[Any] = max(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = 800 if """detection""" in checkpoint_url else 1000 SCREAMING_SNAKE_CASE__ : List[str] = target_max_size / current_max_size SCREAMING_SNAKE_CASE__ : str = image.resize((int(round(scale * width ) ), int(round(scale * height ) )) ) return resized_image def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[int] = F.to_tensor(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = F.normalize(__lowerCAmelCase , mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ) return image @torch.no_grad() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Optional[Any]: logger.info("""Converting model...""" ) # load original state dict SCREAMING_SNAKE_CASE__ : str = torch.hub.load_state_dict_from_url(__lowerCAmelCase , map_location="""cpu""" ) # rename keys for src, dest in rename_keys: rename_key(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = rename_backbone_keys(__lowerCAmelCase ) # query, key and value matrices need special treatment read_in_q_k_v(__lowerCAmelCase ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them SCREAMING_SNAKE_CASE__ : Optional[int] = """model.""" for key in state_dict.copy().keys(): if not key.startswith("""class_labels_classifier""" ) and not key.startswith("""bbox_predictor""" ): SCREAMING_SNAKE_CASE__ : Optional[int] = state_dict.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = val # create HuggingFace model and load state dict SCREAMING_SNAKE_CASE__ : Tuple = TableTransformerConfig( backbone="""resnet18""" , mask_loss_coefficient=1 , dice_loss_coefficient=1 , ce_loss_coefficient=1 , bbox_loss_coefficient=5 , giou_loss_coefficient=2 , eos_coefficient=0.4 , class_cost=1 , bbox_cost=5 , giou_cost=2 , ) if "detection" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] = 15 SCREAMING_SNAKE_CASE__ : Any = 2 SCREAMING_SNAKE_CASE__ : str = {0: """table""", 1: """table rotated"""} SCREAMING_SNAKE_CASE__ : Union[str, Any] = idalabel SCREAMING_SNAKE_CASE__ : List[str] = {v: k for k, v in idalabel.items()} else: SCREAMING_SNAKE_CASE__ : Tuple = 125 SCREAMING_SNAKE_CASE__ : str = 6 SCREAMING_SNAKE_CASE__ : List[Any] = { 0: """table""", 1: """table column""", 2: """table row""", 3: """table column header""", 4: """table projected row header""", 5: """table spanning cell""", } SCREAMING_SNAKE_CASE__ : Any = idalabel SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Dict = DetrImageProcessor( format="""coco_detection""" , max_size=800 if """detection""" in checkpoint_url else 1000 ) SCREAMING_SNAKE_CASE__ : Tuple = TableTransformerForObjectDetection(__lowerCAmelCase ) model.load_state_dict(__lowerCAmelCase ) model.eval() # verify our conversion SCREAMING_SNAKE_CASE__ : Dict = """example_pdf.png""" if """detection""" in checkpoint_url else """example_table.png""" SCREAMING_SNAKE_CASE__ : Tuple = hf_hub_download(repo_id="""nielsr/example-pdf""" , repo_type="""dataset""" , filename=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = Image.open(__lowerCAmelCase ).convert("""RGB""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = normalize(resize(__lowerCAmelCase , __lowerCAmelCase ) ).unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : Dict = model(__lowerCAmelCase ) if "detection" in checkpoint_url: SCREAMING_SNAKE_CASE__ : List[Any] = (1, 15, 3) SCREAMING_SNAKE_CASE__ : str = torch.tensor( [[-6.7_897, -16.9_985, 6.7_937], [-8.0_186, -22.2_192, 6.9_677], [-7.3_117, -21.0_708, 7.4_055]] ) SCREAMING_SNAKE_CASE__ : str = torch.tensor([[0.4_867, 0.1_767, 0.6_732], [0.6_718, 0.4_479, 0.3_830], [0.4_716, 0.1_760, 0.6_364]] ) else: SCREAMING_SNAKE_CASE__ : Dict = (1, 125, 7) SCREAMING_SNAKE_CASE__ : Any = torch.tensor( [[-18.1_430, -8.3_214, 4.8_274], [-18.4_685, -7.1_361, -4.2_667], [-26.3_693, -9.3_429, -4.9_962]] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([[0.4_983, 0.5_595, 0.9_440], [0.4_916, 0.6_315, 0.5_954], [0.6_108, 0.8_637, 0.1_135]] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(F'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(__lowerCAmelCase ).mkdir(exist_ok=__lowerCAmelCase ) model.save_pretrained(__lowerCAmelCase ) image_processor.save_pretrained(__lowerCAmelCase ) if push_to_hub: # Push model to HF hub logger.info("""Pushing model to the hub...""" ) SCREAMING_SNAKE_CASE__ : List[Any] = ( """microsoft/table-transformer-detection""" if """detection""" in checkpoint_url else """microsoft/table-transformer-structure-recognition""" ) model.push_to_hub(__lowerCAmelCase ) image_processor.push_to_hub(__lowerCAmelCase ) if __name__ == "__main__": a :Any = argparse.ArgumentParser() parser.add_argument( "--checkpoint_url", default="https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth", type=str, choices=[ "https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth", "https://pubtables1m.blob.core.windows.net/model/pubtables1m_structure_detr_r18.pth", ], help="URL of the Table Transformer checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) a :int = parser.parse_args() convert_table_transformer_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
680
1
"""simple docstring""" from statistics import mean import numpy as np def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> list: SCREAMING_SNAKE_CASE__ : Tuple = 0 # Number of processes finished SCREAMING_SNAKE_CASE__ : List[str] = 0 # Displays the finished process. # If it is 0, the performance is completed if it is 1, before the performance. SCREAMING_SNAKE_CASE__ : Any = [0] * no_of_process # List to include calculation results SCREAMING_SNAKE_CASE__ : Optional[int] = [0] * no_of_process # Sort by arrival time. SCREAMING_SNAKE_CASE__ : List[str] = [burst_time[i] for i in np.argsort(__lowerCAmelCase )] SCREAMING_SNAKE_CASE__ : Tuple = [process_name[i] for i in np.argsort(__lowerCAmelCase )] arrival_time.sort() while no_of_process > finished_process_count: SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 while finished_process[i] == 1: i += 1 if current_time < arrival_time[i]: SCREAMING_SNAKE_CASE__ : Dict = arrival_time[i] SCREAMING_SNAKE_CASE__ : Optional[int] = 0 # Index showing the location of the process being performed SCREAMING_SNAKE_CASE__ : Optional[int] = 0 # Saves the current response ratio. SCREAMING_SNAKE_CASE__ : Tuple = 0 for i in range(0 , __lowerCAmelCase ): if finished_process[i] == 0 and arrival_time[i] <= current_time: SCREAMING_SNAKE_CASE__ : str = (burst_time[i] + (current_time - arrival_time[i])) / burst_time[ i ] if response_ratio < temp: SCREAMING_SNAKE_CASE__ : Any = temp SCREAMING_SNAKE_CASE__ : Tuple = i # Calculate the turn around time SCREAMING_SNAKE_CASE__ : List[str] = current_time + burst_time[loc] - arrival_time[loc] current_time += burst_time[loc] # Indicates that the process has been performed. SCREAMING_SNAKE_CASE__ : int = 1 # Increase finished_process_count by 1 finished_process_count += 1 return turn_around_time def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> list: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [0] * no_of_process for i in range(0 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Optional[int] = turn_around_time[i] - burst_time[i] return waiting_time if __name__ == "__main__": a :Optional[int] = 5 a :Dict = ["A", "B", "C", "D", "E"] a :Optional[Any] = [1, 2, 3, 4, 5] a :Tuple = [1, 2, 3, 4, 5] a :Union[str, Any] = calculate_turn_around_time( process_name, arrival_time, burst_time, no_of_process ) a :Optional[int] = calculate_waiting_time( process_name, turn_around_time, burst_time, no_of_process ) print("Process name \tArrival time \tBurst time \tTurn around time \tWaiting time") for i in range(0, no_of_process): print( f'{process_name[i]}\t\t{arrival_time[i]}\t\t{burst_time[i]}\t\t' f'{turn_around_time[i]}\t\t\t{waiting_time[i]}' ) print(f'average waiting time : {mean(waiting_time):.5f}') print(f'average turn around time : {mean(turn_around_time):.5f}')
680
"""simple docstring""" from __future__ import annotations import unittest from transformers import 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, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers import ( TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, BertConfig, DPRConfig, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) class __a : '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=2 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , _a=0 , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : str = seq_length SCREAMING_SNAKE_CASE__ : List[str] = is_training SCREAMING_SNAKE_CASE__ : List[str] = use_input_mask SCREAMING_SNAKE_CASE__ : Dict = use_token_type_ids SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE__ : Dict = hidden_size SCREAMING_SNAKE_CASE__ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE__ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : str = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Any = type_vocab_size SCREAMING_SNAKE_CASE__ : int = type_sequence_label_size SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : Any = num_labels SCREAMING_SNAKE_CASE__ : Dict = num_choices SCREAMING_SNAKE_CASE__ : Any = scope SCREAMING_SNAKE_CASE__ : int = projection_dim def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : str = None if self.use_input_mask: # follow test_modeling_tf_ctrl.py SCREAMING_SNAKE_CASE__ : str = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : Any = BertConfig( 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 , ) SCREAMING_SNAKE_CASE__ : str = DPRConfig(projection_dim=self.projection_dim , **config.to_dict() ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRContextEncoder(config=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , attention_mask=_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : str = model(_a ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = TFDPRQuestionEncoder(config=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_a , attention_mask=_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : List[str] = model(_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(_a ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = TFDPRReader(config=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , attention_mask=_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) ) self.parent.assertEqual(result.relevance_logits.shape , (self.batch_size,) ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE__ : int = {"""input_ids""": input_ids} return config, inputs_dict @require_tf class __a (UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = ( ( TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) if is_tf_available() else () ) _SCREAMING_SNAKE_CASE :int = {"""feature-extraction""": TFDPRQuestionEncoder} if is_tf_available() else {} _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = False _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :Dict = False def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFDPRModelTester(self ) SCREAMING_SNAKE_CASE__ : List[str] = ConfigTester(self , config_class=_a , hidden_size=37 ) def _a ( self ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_context_encoder(*_a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_question_encoder(*_a ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_reader(*_a ) @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRContextEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[int] = TFDPRContextEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = TFDPRQuestionEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRReader.from_pretrained(_a ) self.assertIsNotNone(_a ) @require_tf class __a (unittest.TestCase): '''simple docstring''' @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFDPRQuestionEncoder.from_pretrained("""facebook/dpr-question_encoder-single-nq-base""" ) SCREAMING_SNAKE_CASE__ : List[Any] = tf.constant( [[101, 7_592, 1_010, 2_003, 2_026, 3_899, 10_140, 1_029, 102]] ) # [CLS] hello, is my dog cute? [SEP] SCREAMING_SNAKE_CASE__ : Tuple = model(_a )[0] # embedding shape = (1, 768) # compare the actual values for a slice. SCREAMING_SNAKE_CASE__ : Any = tf.constant( [ [ 0.03_236_253, 0.12_753_335, 0.16_818_509, 0.00_279_786, 0.3_896_933, 0.24_264_945, 0.2_178_971, -0.02_335_227, -0.08_481_959, -0.14_324_117, ] ] ) self.assertTrue(numpy.allclose(output[:, :10].numpy() , expected_slice.numpy() , atol=1E-4 ) )
680
1
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.whisper import WhisperForConditionalGeneration, WhisperProcessor from .base import PipelineTool class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Dict = """openai/whisper-base""" _SCREAMING_SNAKE_CASE :Dict = ( """This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the """ """transcribed text.""" ) _SCREAMING_SNAKE_CASE :List[str] = """transcriber""" _SCREAMING_SNAKE_CASE :Optional[int] = WhisperProcessor _SCREAMING_SNAKE_CASE :List[str] = WhisperForConditionalGeneration _SCREAMING_SNAKE_CASE :Dict = ["""audio"""] _SCREAMING_SNAKE_CASE :str = ["""text"""] def _a ( self , _a ) -> int: """simple docstring""" return self.pre_processor(_a , return_tensors="""pt""" ).input_features def _a ( self , _a ) -> Optional[int]: """simple docstring""" return self.model.generate(inputs=_a ) def _a ( self , _a ) -> Any: """simple docstring""" return self.pre_processor.batch_decode(_a , skip_special_tokens=_a )[0]
680
"""simple docstring""" # DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion # and https://github.com/hojonathanho/diffusion import math from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.schedulers.scheduling_utils import SchedulerMixin from diffusers.utils import BaseOutput, deprecate @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :torch.FloatTensor _SCREAMING_SNAKE_CASE :Optional[torch.FloatTensor] = None def _lowercase ( __lowerCAmelCase , __lowerCAmelCase=0.999 , __lowerCAmelCase="cosine" , ) -> Union[str, Any]: if alpha_transform_type == "cosine": def alpha_bar_fn(__lowerCAmelCase ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(__lowerCAmelCase ): return math.exp(t * -12.0 ) else: raise ValueError(F'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) SCREAMING_SNAKE_CASE__ : List[Any] = [] for i in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = i / num_diffusion_timesteps SCREAMING_SNAKE_CASE__ : int = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(__lowerCAmelCase ) / alpha_bar_fn(__lowerCAmelCase ) , __lowerCAmelCase ) ) return torch.tensor(__lowerCAmelCase , dtype=torch.floataa ) class __a (UpperCamelCase_ , UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = 1 @register_to_config def __init__( self , _a = 1_000 , _a = 0.0_001 , _a = 0.02 , _a = "linear" , _a = None , _a = True , _a = True , _a = 0 , _a = "epsilon" , _a = 1.0 , **_a , ) -> Dict: """simple docstring""" if kwargs.get("""set_alpha_to_one""" , _a ) is not None: SCREAMING_SNAKE_CASE__ : Tuple = ( """The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead.""" ) deprecate("""set_alpha_to_one""" , """1.0.0""" , _a , standard_warn=_a ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs["""set_alpha_to_one"""] if trained_betas is not None: SCREAMING_SNAKE_CASE__ : Dict = torch.tensor(_a , dtype=torch.floataa ) elif beta_schedule == "linear": SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.linspace(_a , _a , _a , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. SCREAMING_SNAKE_CASE__ : Optional[int] = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , _a , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule SCREAMING_SNAKE_CASE__ : Tuple = betas_for_alpha_bar(_a ) else: raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = 1.0 - self.betas SCREAMING_SNAKE_CASE__ : List[Any] = torch.cumprod(self.alphas , dim=0 ) # At every step in inverted ddim, we are looking into the next alphas_cumprod # For the final step, there is no next alphas_cumprod, and the index is out of bounds # `set_alpha_to_zero` decides whether we set this parameter simply to zero # in this case, self.step() just output the predicted noise # or whether we use the final alpha of the "non-previous" one. SCREAMING_SNAKE_CASE__ : Any = torch.tensor(0.0 ) if set_alpha_to_zero else self.alphas_cumprod[-1] # standard deviation of the initial noise distribution SCREAMING_SNAKE_CASE__ : Tuple = 1.0 # setable values SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : List[str] = torch.from_numpy(np.arange(0 , _a ).copy().astype(np.intaa ) ) def _a ( self , _a , _a = None ) -> torch.FloatTensor: """simple docstring""" return sample def _a ( self , _a , _a = None ) -> Optional[int]: """simple docstring""" if num_inference_steps > self.config.num_train_timesteps: raise ValueError( f'''`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:''' f''' {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle''' f''' maximal {self.config.num_train_timesteps} timesteps.''' ) SCREAMING_SNAKE_CASE__ : List[str] = num_inference_steps SCREAMING_SNAKE_CASE__ : Optional[Any] = self.config.num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 SCREAMING_SNAKE_CASE__ : str = (np.arange(0 , _a ) * step_ratio).round().copy().astype(np.intaa ) SCREAMING_SNAKE_CASE__ : Tuple = torch.from_numpy(_a ).to(_a ) self.timesteps += self.config.steps_offset def _a ( self , _a , _a , _a , _a = 0.0 , _a = False , _a = None , _a = True , ) -> Union[DDIMSchedulerOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = timestep + self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas # change original implementation to exactly match noise levels for analogous forward process SCREAMING_SNAKE_CASE__ : Optional[int] = self.alphas_cumprod[timestep] SCREAMING_SNAKE_CASE__ : Optional[int] = ( self.alphas_cumprod[prev_timestep] if prev_timestep < self.config.num_train_timesteps else self.final_alpha_cumprod ) SCREAMING_SNAKE_CASE__ : Any = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf if self.config.prediction_type == "epsilon": SCREAMING_SNAKE_CASE__ : int = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 SCREAMING_SNAKE_CASE__ : List[Any] = model_output elif self.config.prediction_type == "sample": SCREAMING_SNAKE_CASE__ : Dict = model_output SCREAMING_SNAKE_CASE__ : int = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 elif self.config.prediction_type == "v_prediction": SCREAMING_SNAKE_CASE__ : Dict = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output SCREAMING_SNAKE_CASE__ : str = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or''' """ `v_prediction`""" ) # 4. Clip or threshold "predicted x_0" if self.config.clip_sample: SCREAMING_SNAKE_CASE__ : Tuple = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : Any = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : Dict = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if not return_dict: return (prev_sample, pred_original_sample) return DDIMSchedulerOutput(prev_sample=_a , pred_original_sample=_a ) def __len__( self ) -> Dict: """simple docstring""" return self.config.num_train_timesteps
680
1
"""simple docstring""" import json import os from functools import lru_cache from typing import Dict, List, Optional, Tuple, Union import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding, EncodedInput from ...utils import PaddingStrategy, logging a :List[str] = logging.get_logger(__name__) a :List[str] = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} # See all LED models at https://huggingface.co/models?filter=LED a :int = { "vocab_file": { "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json", }, "merges_file": { "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt", }, "tokenizer_file": { "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json", }, } a :Dict = { "allenai/led-base-16384": 16_384, } @lru_cache() # Copied from transformers.models.bart.tokenization_bart.bytes_to_unicode def _lowercase ( ) -> str: SCREAMING_SNAKE_CASE__ : List[Any] = ( list(range(ord("""!""" ) , ord("""~""" ) + 1 ) ) + list(range(ord("""¡""" ) , ord("""¬""" ) + 1 ) ) + list(range(ord("""®""" ) , ord("""ÿ""" ) + 1 ) ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = bs[:] SCREAMING_SNAKE_CASE__ : List[Any] = 0 for b in range(2**8 ): if b not in bs: bs.append(__lowerCAmelCase ) cs.append(2**8 + n ) n += 1 SCREAMING_SNAKE_CASE__ : List[Any] = [chr(__lowerCAmelCase ) for n in cs] return dict(zip(__lowerCAmelCase , __lowerCAmelCase ) ) def _lowercase ( __lowerCAmelCase ) -> Any: SCREAMING_SNAKE_CASE__ : int = set() SCREAMING_SNAKE_CASE__ : Optional[Any] = word[0] for char in word[1:]: pairs.add((prev_char, char) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = char return pairs class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[str] = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE :Any = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE :List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE :Tuple = ["""input_ids""", """attention_mask"""] def __init__( self , _a , _a , _a="replace" , _a="<s>" , _a="</s>" , _a="</s>" , _a="<s>" , _a="<unk>" , _a="<pad>" , _a="<mask>" , _a=False , **_a , ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else bos_token SCREAMING_SNAKE_CASE__ : Dict = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else eos_token SCREAMING_SNAKE_CASE__ : int = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else sep_token SCREAMING_SNAKE_CASE__ : List[str] = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else cls_token SCREAMING_SNAKE_CASE__ : Dict = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else unk_token SCREAMING_SNAKE_CASE__ : List[str] = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else pad_token # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE__ : Optional[Any] = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token super().__init__( errors=_a , bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , cls_token=_a , pad_token=_a , mask_token=_a , add_prefix_space=_a , **_a , ) with open(_a , encoding="""utf-8""" ) as vocab_handle: SCREAMING_SNAKE_CASE__ : int = json.load(_a ) SCREAMING_SNAKE_CASE__ : Any = {v: k for k, v in self.encoder.items()} SCREAMING_SNAKE_CASE__ : List[Any] = errors # how to handle errors in decoding SCREAMING_SNAKE_CASE__ : Union[str, Any] = bytes_to_unicode() SCREAMING_SNAKE_CASE__ : List[Any] = {v: k for k, v in self.byte_encoder.items()} with open(_a , encoding="""utf-8""" ) as merges_handle: SCREAMING_SNAKE_CASE__ : Optional[Any] = merges_handle.read().split("""\n""" )[1:-1] SCREAMING_SNAKE_CASE__ : Dict = [tuple(merge.split() ) for merge in bpe_merges] SCREAMING_SNAKE_CASE__ : str = dict(zip(_a , range(len(_a ) ) ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {} SCREAMING_SNAKE_CASE__ : Optional[int] = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions SCREAMING_SNAKE_CASE__ : Optional[Any] = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""" ) @property # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.vocab_size def _a ( self ) -> Optional[Any]: """simple docstring""" return len(self.encoder ) def _a ( self ) -> int: """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def _a ( self , _a ) -> Any: """simple docstring""" if token in self.cache: return self.cache[token] SCREAMING_SNAKE_CASE__ : int = tuple(_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_pairs(_a ) if not pairs: return token while True: SCREAMING_SNAKE_CASE__ : Optional[Any] = min(_a , key=lambda _a : self.bpe_ranks.get(_a , float("""inf""" ) ) ) if bigram not in self.bpe_ranks: break SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = bigram SCREAMING_SNAKE_CASE__ : Optional[Any] = [] SCREAMING_SNAKE_CASE__ : List[str] = 0 while i < len(_a ): try: SCREAMING_SNAKE_CASE__ : Tuple = word.index(_a , _a ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) SCREAMING_SNAKE_CASE__ : List[str] = j if word[i] == first and i < len(_a ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 SCREAMING_SNAKE_CASE__ : str = tuple(_a ) SCREAMING_SNAKE_CASE__ : List[str] = new_word if len(_a ) == 1: break else: SCREAMING_SNAKE_CASE__ : Optional[Any] = get_pairs(_a ) SCREAMING_SNAKE_CASE__ : Any = """ """.join(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = word return word def _a ( self , _a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] for token in re.findall(self.pat , _a ): SCREAMING_SNAKE_CASE__ : Tuple = """""".join( self.byte_encoder[b] for b in token.encode("""utf-8""" ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_a ).split(""" """ ) ) return bpe_tokens def _a ( self , _a ) -> Optional[Any]: """simple docstring""" return self.encoder.get(_a , self.encoder.get(self.unk_token ) ) def _a ( self , _a ) -> Optional[Any]: """simple docstring""" return self.decoder.get(_a ) def _a ( self , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = """""".join(_a ) SCREAMING_SNAKE_CASE__ : Tuple = bytearray([self.byte_decoder[c] for c in text] ).decode("""utf-8""" , errors=self.errors ) return text def _a ( self , _a , _a = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE__ : Any = os.path.join( _a , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ : List[Any] = os.path.join( _a , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""] ) with open(_a , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=_a , ensure_ascii=_a ) + """\n""" ) SCREAMING_SNAKE_CASE__ : Dict = 0 with open(_a , """w""" , encoding="""utf-8""" ) as writer: writer.write("""#version: 0.2\n""" ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda _a : kv[1] ): if index != token_index: logger.warning( f'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.''' """ Please check that the tokenizer is not corrupted!""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = token_index writer.write(""" """.join(_a ) + """\n""" ) index += 1 return vocab_file, merge_file def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] SCREAMING_SNAKE_CASE__ : List[str] = [self.cls_token_id] SCREAMING_SNAKE_CASE__ : Any = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _a ( self , _a , _a = None , _a = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a , token_ids_a=_a , already_has_special_tokens=_a ) if token_ids_a is None: return [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1, 1] + ([0] * len(_a )) + [1] def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _a ( self , _a , _a=False , **_a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = kwargs.pop("""add_prefix_space""" , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(_a ) > 0 and not text[0].isspace()): SCREAMING_SNAKE_CASE__ : int = """ """ + text return (text, kwargs) def _a ( self , _a , _a = None , _a = PaddingStrategy.DO_NOT_PAD , _a = None , _a = None , ) -> dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = super()._pad( encoded_inputs=_a , max_length=_a , padding_strategy=_a , pad_to_multiple_of=_a , return_attention_mask=_a , ) # Load from model defaults if return_attention_mask is None: SCREAMING_SNAKE_CASE__ : Dict = """attention_mask""" in self.model_input_names if return_attention_mask and "global_attention_mask" in encoded_inputs: SCREAMING_SNAKE_CASE__ : int = encoded_inputs[self.model_input_names[0]] # `global_attention_mask` need to have the same length as other (sequential) inputs. SCREAMING_SNAKE_CASE__ : List[str] = len(encoded_inputs["""global_attention_mask"""] ) != len(_a ) if needs_to_be_padded: SCREAMING_SNAKE_CASE__ : Union[str, Any] = len(_a ) - len(encoded_inputs["""global_attention_mask"""] ) if self.padding_side == "right": # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend` SCREAMING_SNAKE_CASE__ : List[Any] = ( encoded_inputs["""global_attention_mask"""] + [-1] * difference ) elif self.padding_side == "left": SCREAMING_SNAKE_CASE__ : List[str] = [-1] * difference + encoded_inputs[ """global_attention_mask""" ] else: raise ValueError("""Invalid padding strategy:""" + str(self.padding_side ) ) return encoded_inputs
680
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) a :Union[str, Any] = { "configuration_speecht5": [ "SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP", "SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP", "SpeechT5Config", "SpeechT5HifiGanConfig", ], "feature_extraction_speecht5": ["SpeechT5FeatureExtractor"], "processing_speecht5": ["SpeechT5Processor"], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = ["SpeechT5Tokenizer"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST", "SpeechT5ForSpeechToText", "SpeechT5ForSpeechToSpeech", "SpeechT5ForTextToSpeech", "SpeechT5Model", "SpeechT5PreTrainedModel", "SpeechT5HifiGan", ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys a :Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
1
"""simple docstring""" class __a : '''simple docstring''' def __init__( self , _a , _a , _a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = name SCREAMING_SNAKE_CASE__ : Tuple = value SCREAMING_SNAKE_CASE__ : List[Any] = weight def __repr__( self ) -> Union[str, Any]: """simple docstring""" return f'''{self.__class__.__name__}({self.name}, {self.value}, {self.weight})''' def _a ( self ) -> Optional[int]: """simple docstring""" return self.value def _a ( self ) -> List[str]: """simple docstring""" return self.name def _a ( self ) -> List[Any]: """simple docstring""" return self.weight def _a ( self ) -> List[str]: """simple docstring""" return self.value / self.weight def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[str] = [] for i in range(len(__lowerCAmelCase ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> List[Any]: SCREAMING_SNAKE_CASE__ : str = sorted(__lowerCAmelCase , key=__lowerCAmelCase , reverse=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = 0.0, 0.0 for i in range(len(__lowerCAmelCase ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def _lowercase ( ) -> str: pass if __name__ == "__main__": import doctest doctest.testmod()
680
"""simple docstring""" import math import os import sys def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Union[str, Any] = """""" try: with open(__lowerCAmelCase , """rb""" ) as binary_file: SCREAMING_SNAKE_CASE__ : Optional[int] = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Dict = F'''{dat:08b}''' result += curr_byte return result except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> None: lexicon.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = last_match_id if math.loga(__lowerCAmelCase ).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE__ : Dict = """0""" + lexicon[curr_key] SCREAMING_SNAKE_CASE__ : str = bin(__lowerCAmelCase )[2:] def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Dict = {"""0""": """0""", """1""": """1"""} SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = """""", """""" SCREAMING_SNAKE_CASE__ : Any = len(__lowerCAmelCase ) for i in range(len(__lowerCAmelCase ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon[curr_string] result += last_match_id add_key_to_lexicon(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) index += 1 SCREAMING_SNAKE_CASE__ : List[str] = """""" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE__ : List[Any] = lexicon[curr_string] result += last_match_id return result def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Any = os.path.getsize(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = bin(__lowerCAmelCase )[2:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = len(__lowerCAmelCase ) return "0" * (length_length - 1) + file_length_binary + compressed def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Optional[int] = 8 try: with open(__lowerCAmelCase , """wb""" ) as opened_file: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ to_write[i : i + byte_length] for i in range(0 , len(__lowerCAmelCase ) , __lowerCAmelCase ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("""10000000""" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(__lowerCAmelCase , 2 ).to_bytes(1 , byteorder="""big""" ) ) except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Dict = read_file_binary(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = compress_data(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = add_file_length(__lowerCAmelCase , __lowerCAmelCase ) write_file_binary(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
680
1
"""simple docstring""" import unittest import numpy as np from datasets import load_dataset from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import BeitImageProcessor class __a (unittest.TestCase): '''simple docstring''' def __init__( self , _a , _a=7 , _a=3 , _a=18 , _a=30 , _a=400 , _a=True , _a=None , _a=True , _a=None , _a=True , _a=[0.5, 0.5, 0.5] , _a=[0.5, 0.5, 0.5] , _a=False , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = size if size is not None else {"""height""": 20, """width""": 20} SCREAMING_SNAKE_CASE__ : List[Any] = crop_size if crop_size is not None else {"""height""": 18, """width""": 18} SCREAMING_SNAKE_CASE__ : Union[str, Any] = parent SCREAMING_SNAKE_CASE__ : List[Any] = batch_size SCREAMING_SNAKE_CASE__ : Tuple = num_channels SCREAMING_SNAKE_CASE__ : Optional[Any] = image_size SCREAMING_SNAKE_CASE__ : List[Any] = min_resolution SCREAMING_SNAKE_CASE__ : str = max_resolution SCREAMING_SNAKE_CASE__ : List[str] = do_resize SCREAMING_SNAKE_CASE__ : Optional[Any] = size SCREAMING_SNAKE_CASE__ : int = do_center_crop SCREAMING_SNAKE_CASE__ : Any = crop_size SCREAMING_SNAKE_CASE__ : int = do_normalize SCREAMING_SNAKE_CASE__ : Any = image_mean SCREAMING_SNAKE_CASE__ : Optional[int] = image_std SCREAMING_SNAKE_CASE__ : int = do_reduce_labels def _a ( self ) -> Union[str, Any]: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_reduce_labels": self.do_reduce_labels, } def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : List[str] = load_dataset("""hf-internal-testing/fixtures_ade20k""" , split="""test""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = Image.open(dataset[0]["""file"""] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Image.open(dataset[1]["""file"""] ) return image, map def _lowercase ( ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : Dict = load_dataset("""hf-internal-testing/fixtures_ade20k""" , split="""test""" ) SCREAMING_SNAKE_CASE__ : List[Any] = Image.open(ds[0]["""file"""] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Image.open(ds[1]["""file"""] ) SCREAMING_SNAKE_CASE__ : Tuple = Image.open(ds[2]["""file"""] ) SCREAMING_SNAKE_CASE__ : List[Any] = Image.open(ds[3]["""file"""] ) return [imagea, imagea], [mapa, mapa] @require_torch @require_vision class __a (UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :str = BeitImageProcessor if is_vision_available() else None def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BeitImageProcessingTester(self ) @property def _a ( self ) -> Optional[Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_a , """do_resize""" ) ) self.assertTrue(hasattr(_a , """size""" ) ) self.assertTrue(hasattr(_a , """do_center_crop""" ) ) self.assertTrue(hasattr(_a , """center_crop""" ) ) self.assertTrue(hasattr(_a , """do_normalize""" ) ) self.assertTrue(hasattr(_a , """image_mean""" ) ) self.assertTrue(hasattr(_a , """image_std""" ) ) def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 20, """width""": 20} ) self.assertEqual(image_processor.crop_size , {"""height""": 18, """width""": 18} ) self.assertEqual(image_processor.do_reduce_labels , _a ) SCREAMING_SNAKE_CASE__ : Any = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , crop_size=84 , reduce_labels=_a ) self.assertEqual(image_processor.size , {"""height""": 42, """width""": 42} ) self.assertEqual(image_processor.crop_size , {"""height""": 84, """width""": 84} ) self.assertEqual(image_processor.do_reduce_labels , _a ) def _a ( self ) -> Any: """simple docstring""" pass def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=_a ) for image in image_inputs: self.assertIsInstance(_a , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : List[str] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched SCREAMING_SNAKE_CASE__ : str = image_processing(_a , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE__ : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_a , numpify=_a ) for image in image_inputs: self.assertIsInstance(_a , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE__ : List[Any] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched SCREAMING_SNAKE_CASE__ : int = image_processing(_a , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE__ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=_a , torchify=_a ) for image in image_inputs: self.assertIsInstance(_a , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE__ : Any = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched SCREAMING_SNAKE_CASE__ : List[str] = image_processing(_a , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE__ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=_a , torchify=_a ) SCREAMING_SNAKE_CASE__ : List[str] = [] for image in image_inputs: self.assertIsInstance(_a , torch.Tensor ) maps.append(torch.zeros(image.shape[-2:] ).long() ) # Test not batched input SCREAMING_SNAKE_CASE__ : List[str] = image_processing(image_inputs[0] , maps[0] , return_tensors="""pt""" ) self.assertEqual( encoding["""pixel_values"""].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual( encoding["""labels"""].shape , ( 1, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual(encoding["""labels"""].dtype , torch.long ) self.assertTrue(encoding["""labels"""].min().item() >= 0 ) self.assertTrue(encoding["""labels"""].max().item() <= 255 ) # Test batched SCREAMING_SNAKE_CASE__ : int = image_processing(_a , _a , return_tensors="""pt""" ) self.assertEqual( encoding["""pixel_values"""].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual( encoding["""labels"""].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual(encoding["""labels"""].dtype , torch.long ) self.assertTrue(encoding["""labels"""].min().item() >= 0 ) self.assertTrue(encoding["""labels"""].max().item() <= 255 ) # Test not batched input (PIL images) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = prepare_semantic_single_inputs() SCREAMING_SNAKE_CASE__ : List[str] = image_processing(_a , _a , return_tensors="""pt""" ) self.assertEqual( encoding["""pixel_values"""].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual( encoding["""labels"""].shape , ( 1, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual(encoding["""labels"""].dtype , torch.long ) self.assertTrue(encoding["""labels"""].min().item() >= 0 ) self.assertTrue(encoding["""labels"""].max().item() <= 255 ) # Test batched input (PIL images) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = prepare_semantic_batch_inputs() SCREAMING_SNAKE_CASE__ : Optional[int] = image_processing(_a , _a , return_tensors="""pt""" ) self.assertEqual( encoding["""pixel_values"""].shape , ( 2, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual( encoding["""labels"""].shape , ( 2, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual(encoding["""labels"""].dtype , torch.long ) self.assertTrue(encoding["""labels"""].min().item() >= 0 ) self.assertTrue(encoding["""labels"""].max().item() <= 255 ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.image_processing_class(**self.image_processor_dict ) # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150 SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = prepare_semantic_single_inputs() SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processing(_a , _a , return_tensors="""pt""" ) self.assertTrue(encoding["""labels"""].min().item() >= 0 ) self.assertTrue(encoding["""labels"""].max().item() <= 150 ) SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : Any = image_processing(_a , _a , return_tensors="""pt""" ) self.assertTrue(encoding["""labels"""].min().item() >= 0 ) self.assertTrue(encoding["""labels"""].max().item() <= 255 )
680
"""simple docstring""" import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Tuple = SamImageProcessor() SCREAMING_SNAKE_CASE__ : List[str] = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> Union[str, Any]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> Tuple: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Tuple = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Dict = processor(images=_a , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_torch def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [torch.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : str = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : List[Any] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : Any = processor.post_process_masks(_a , _a , _a ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Dict = processor.post_process_masks( _a , torch.tensor(_a ) , torch.tensor(_a ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np SCREAMING_SNAKE_CASE__ : Dict = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks(_a , np.array(_a ) , np.array(_a ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Dict = [[1, 0], [0, 1]] with self.assertRaises(_a ): SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks(_a , np.array(_a ) , np.array(_a ) ) @require_vision @require_tf class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Optional[int] = SamImageProcessor() SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> List[str]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> int: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Any = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : int = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Tuple = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Any = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Any = processor(images=_a , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_tf def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Union[str, Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [tf.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Optional[int] = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks(_a , _a , _a , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks( _a , tf.convert_to_tensor(_a ) , tf.convert_to_tensor(_a ) , return_tensors="""tf""" , ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np SCREAMING_SNAKE_CASE__ : Optional[int] = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks( _a , np.array(_a ) , np.array(_a ) , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Any = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): SCREAMING_SNAKE_CASE__ : str = processor.post_process_masks( _a , np.array(_a ) , np.array(_a ) , return_tensors="""tf""" ) @require_vision @require_torchvision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Dict = SamImageProcessor() SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> Any: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> Union[str, Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : int = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : List[Any] = [tf.convert_to_tensor(_a )] SCREAMING_SNAKE_CASE__ : Dict = [torch.tensor(_a )] SCREAMING_SNAKE_CASE__ : Optional[int] = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : List[str] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : List[Any] = processor.post_process_masks( _a , _a , _a , return_tensors="""tf""" ) SCREAMING_SNAKE_CASE__ : List[str] = processor.post_process_masks( _a , _a , _a , return_tensors="""pt""" ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : str = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : int = image_processor(_a , return_tensors="""pt""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : Any = processor(images=_a , return_tensors="""pt""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor(_a , return_tensors="""tf""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : str = processor(images=_a , return_tensors="""tf""" )["""pixel_values"""].numpy() self.assertTrue(np.allclose(_a , _a ) ) self.assertTrue(np.allclose(_a , _a ) ) self.assertTrue(np.allclose(_a , _a ) )
680
1
"""simple docstring""" import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets.utils.py_utils import Literal a :Union[str, Any] = datasets.utils.logging.get_logger(__name__) a :Union[str, Any] = ["names", "prefix"] a :Optional[int] = ["warn_bad_lines", "error_bad_lines", "mangle_dupe_cols"] a :List[str] = ["encoding_errors", "on_bad_lines"] a :Dict = ["date_format"] @dataclass class __a (datasets.BuilderConfig): '''simple docstring''' _SCREAMING_SNAKE_CASE :str = "," _SCREAMING_SNAKE_CASE :Optional[str] = None _SCREAMING_SNAKE_CASE :Optional[Union[int, List[int], str]] = "infer" _SCREAMING_SNAKE_CASE :Optional[List[str]] = None _SCREAMING_SNAKE_CASE :Optional[List[str]] = None _SCREAMING_SNAKE_CASE :Optional[Union[int, str, List[int], List[str]]] = None _SCREAMING_SNAKE_CASE :Optional[Union[List[int], List[str]]] = None _SCREAMING_SNAKE_CASE :Optional[str] = None _SCREAMING_SNAKE_CASE :bool = True _SCREAMING_SNAKE_CASE :Optional[Literal["c", "python", "pyarrow"]] = None _SCREAMING_SNAKE_CASE :Dict[Union[int, str], Callable[[Any], Any]] = None _SCREAMING_SNAKE_CASE :Optional[list] = None _SCREAMING_SNAKE_CASE :Optional[list] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Union[int, List[int]]] = None _SCREAMING_SNAKE_CASE :Optional[int] = None _SCREAMING_SNAKE_CASE :Optional[Union[str, List[str]]] = None _SCREAMING_SNAKE_CASE :bool = True _SCREAMING_SNAKE_CASE :bool = True _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = True _SCREAMING_SNAKE_CASE :Optional[str] = None _SCREAMING_SNAKE_CASE :str = "." _SCREAMING_SNAKE_CASE :Optional[str] = None _SCREAMING_SNAKE_CASE :str = '"' _SCREAMING_SNAKE_CASE :int = 0 _SCREAMING_SNAKE_CASE :Optional[str] = None _SCREAMING_SNAKE_CASE :Optional[str] = None _SCREAMING_SNAKE_CASE :Optional[str] = None _SCREAMING_SNAKE_CASE :Optional[str] = None _SCREAMING_SNAKE_CASE :bool = True _SCREAMING_SNAKE_CASE :bool = True _SCREAMING_SNAKE_CASE :int = 0 _SCREAMING_SNAKE_CASE :bool = True _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[str] = None _SCREAMING_SNAKE_CASE :int = 1_00_00 _SCREAMING_SNAKE_CASE :Optional[datasets.Features] = None _SCREAMING_SNAKE_CASE :Optional[str] = "strict" _SCREAMING_SNAKE_CASE :Literal["error", "warn", "skip"] = "error" _SCREAMING_SNAKE_CASE :Optional[str] = None def _a ( self ) -> Optional[Any]: """simple docstring""" if self.delimiter is not None: SCREAMING_SNAKE_CASE__ : Any = self.delimiter if self.column_names is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.column_names @property def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = { """sep""": self.sep, """header""": self.header, """names""": self.names, """index_col""": self.index_col, """usecols""": self.usecols, """prefix""": self.prefix, """mangle_dupe_cols""": self.mangle_dupe_cols, """engine""": self.engine, """converters""": self.converters, """true_values""": self.true_values, """false_values""": self.false_values, """skipinitialspace""": self.skipinitialspace, """skiprows""": self.skiprows, """nrows""": self.nrows, """na_values""": self.na_values, """keep_default_na""": self.keep_default_na, """na_filter""": self.na_filter, """verbose""": self.verbose, """skip_blank_lines""": self.skip_blank_lines, """thousands""": self.thousands, """decimal""": self.decimal, """lineterminator""": self.lineterminator, """quotechar""": self.quotechar, """quoting""": self.quoting, """escapechar""": self.escapechar, """comment""": self.comment, """encoding""": self.encoding, """dialect""": self.dialect, """error_bad_lines""": self.error_bad_lines, """warn_bad_lines""": self.warn_bad_lines, """skipfooter""": self.skipfooter, """doublequote""": self.doublequote, """memory_map""": self.memory_map, """float_precision""": self.float_precision, """chunksize""": self.chunksize, """encoding_errors""": self.encoding_errors, """on_bad_lines""": self.on_bad_lines, """date_format""": self.date_format, } # some kwargs must not be passed if they don't have a default value # some others are deprecated and we can also not pass them if they are the default value for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS: if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() , _a ): del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 2.0 new arguments if not (datasets.config.PANDAS_VERSION.major >= 2): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 1.3 new arguments if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] return pd_read_csv_kwargs class __a (datasets.ArrowBasedBuilder): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = CsvConfig def _a ( self ) -> str: """simple docstring""" return datasets.DatasetInfo(features=self.config.features ) def _a ( self , _a ) -> int: """simple docstring""" if not self.config.data_files: raise ValueError(f'''At least one data file must be specified, but got data_files={self.config.data_files}''' ) SCREAMING_SNAKE_CASE__ : str = dl_manager.download_and_extract(self.config.data_files ) if isinstance(_a , (str, list, tuple) ): SCREAMING_SNAKE_CASE__ : str = data_files if isinstance(_a , _a ): SCREAMING_SNAKE_CASE__ : List[Any] = [files] SCREAMING_SNAKE_CASE__ : int = [dl_manager.iter_files(_a ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""files""": files} )] SCREAMING_SNAKE_CASE__ : Any = [] for split_name, files in data_files.items(): if isinstance(_a , _a ): SCREAMING_SNAKE_CASE__ : List[Any] = [files] SCREAMING_SNAKE_CASE__ : List[str] = [dl_manager.iter_files(_a ) for file in files] splits.append(datasets.SplitGenerator(name=_a , gen_kwargs={"""files""": files} ) ) return splits def _a ( self , _a ) -> pa.Table: """simple docstring""" if self.config.features is not None: SCREAMING_SNAKE_CASE__ : Dict = self.config.features.arrow_schema if all(not require_storage_cast(_a ) for feature in self.config.features.values() ): # cheaper cast SCREAMING_SNAKE_CASE__ : Tuple = pa.Table.from_arrays([pa_table[field.name] for field in schema] , schema=_a ) else: # more expensive cast; allows str <-> int/float or str to Audio for example SCREAMING_SNAKE_CASE__ : Tuple = table_cast(_a , _a ) return pa_table def _a ( self , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.config.features.arrow_schema if self.config.features else None # dtype allows reading an int column as str SCREAMING_SNAKE_CASE__ : str = ( { name: dtype.to_pandas_dtype() if not require_storage_cast(_a ) else object for name, dtype, feature in zip(schema.names , schema.types , self.config.features.values() ) } if schema is not None else None ) for file_idx, file in enumerate(itertools.chain.from_iterable(_a ) ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = pd.read_csv(_a , iterator=_a , dtype=_a , **self.config.pd_read_csv_kwargs ) try: for batch_idx, df in enumerate(_a ): SCREAMING_SNAKE_CASE__ : Optional[Any] = pa.Table.from_pandas(_a ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(_a ) except ValueError as e: logger.error(f'''Failed to read file \'{file}\' with error {type(_a )}: {e}''' ) raise
680
"""simple docstring""" import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __a (UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = LayoutLMTokenizer _SCREAMING_SNAKE_CASE :Optional[int] = LayoutLMTokenizerFast _SCREAMING_SNAKE_CASE :str = True _SCREAMING_SNAKE_CASE :Optional[int] = True def _a ( self ) -> Tuple: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : List[str] = [ """[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] SCREAMING_SNAKE_CASE__ : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def _a ( self , **_a ) -> Optional[int]: """simple docstring""" return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **_a ) def _a ( self , _a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = """UNwant\u00E9d,running""" SCREAMING_SNAKE_CASE__ : Optional[Any] = """unwanted, running""" return input_text, output_text def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(_a , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_a ) , [7, 4, 5, 10, 8, 9] ) def _a ( self ) -> Optional[int]: """simple docstring""" pass
680
1
"""simple docstring""" import os from distutils.util import strtobool def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> str: for e in env_keys: SCREAMING_SNAKE_CASE__ : Union[str, Any] = int(os.environ.get(__lowerCAmelCase , -1 ) ) if val >= 0: return val return default def _lowercase ( __lowerCAmelCase , __lowerCAmelCase=False ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : int = os.environ.get(__lowerCAmelCase , str(__lowerCAmelCase ) ) return strtobool(__lowerCAmelCase ) == 1 # As its name indicates `strtobool` actually returns an int... def _lowercase ( __lowerCAmelCase , __lowerCAmelCase="no" ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Any = os.environ.get(__lowerCAmelCase , str(__lowerCAmelCase ) ) return value
680
"""simple docstring""" import argparse import os import evaluate import torch from datasets import load_dataset 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 # and perform gradient accumulation # # 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 run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a :str = 16 a :Union[str, Any] = 32 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase = 16 ) -> Tuple: SCREAMING_SNAKE_CASE__ : int = AutoTokenizer.from_pretrained("""bert-base-cased""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__lowerCAmelCase ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__lowerCAmelCase , max_length=__lowerCAmelCase ) 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(): SCREAMING_SNAKE_CASE__ : List[str] = datasets.map( __lowerCAmelCase , batched=__lowerCAmelCase , 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 SCREAMING_SNAKE_CASE__ : Any = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__lowerCAmelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE__ : int = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE__ : str = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE__ : Dict = 8 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = None return tokenizer.pad( __lowerCAmelCase , padding="""longest""" , max_length=__lowerCAmelCase , pad_to_multiple_of=__lowerCAmelCase , return_tensors="""pt""" , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE__ : int = DataLoader( tokenized_datasets["""train"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = DataLoader( tokenized_datasets["""validation"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": from accelerate.test_utils.training import mocked_dataloaders a :Dict = mocked_dataloaders # noqa: F811 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , __lowerCAmelCase ) == "1": SCREAMING_SNAKE_CASE__ : Optional[int] = 2 # New Code # SCREAMING_SNAKE_CASE__ : Optional[int] = int(args.gradient_accumulation_steps ) # Initialize accelerator SCREAMING_SNAKE_CASE__ : Optional[Any] = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=__lowerCAmelCase ) if accelerator.distributed_type == DistributedType.TPU and gradient_accumulation_steps > 1: raise NotImplementedError( """Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE__ : Any = config["""lr"""] SCREAMING_SNAKE_CASE__ : str = int(config["""num_epochs"""] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = int(config["""seed"""] ) SCREAMING_SNAKE_CASE__ : List[str] = int(config["""batch_size"""] ) SCREAMING_SNAKE_CASE__ : Any = evaluate.load("""glue""" , """mrpc""" ) set_seed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = get_dataloaders(__lowerCAmelCase , __lowerCAmelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE__ : int = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=__lowerCAmelCase ) # 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). SCREAMING_SNAKE_CASE__ : int = model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE__ : Union[str, Any] = AdamW(params=model.parameters() , lr=__lowerCAmelCase ) # Instantiate scheduler SCREAMING_SNAKE_CASE__ : Any = get_linear_schedule_with_warmup( optimizer=__lowerCAmelCase , num_warmup_steps=100 , num_training_steps=(len(__lowerCAmelCase ) * num_epochs) , ) # 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. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = accelerator.prepare( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Now we train the model for epoch in range(__lowerCAmelCase ): model.train() for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = output.loss accelerator.backward(__lowerCAmelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=__lowerCAmelCase , references=__lowerCAmelCase , ) SCREAMING_SNAKE_CASE__ : List[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , __lowerCAmelCase ) def _lowercase ( ) -> Any: SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=__lowerCAmelCase , default=__lowerCAmelCase , 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.""" , ) # New Code # parser.add_argument( """--gradient_accumulation_steps""" , type=__lowerCAmelCase , default=1 , help="""The number of minibatches to be ran before gradients are accumulated.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : int = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": main()
680
1