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""" 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
"""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 dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :torch.FloatTensor _SCREAMING_SNAKE_CASE :torch.FloatTensor _SCREAMING_SNAKE_CASE :Optional[torch.FloatTensor] = None class __a (UpperCamelCase_ , UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = 2 @register_to_config def __init__( self , _a = 0.02 , _a = 100 , _a = 1.007 , _a = 80 , _a = 0.05 , _a = 50 , ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = sigma_max # setable values SCREAMING_SNAKE_CASE__ : int = None SCREAMING_SNAKE_CASE__ : np.IntTensor = None SCREAMING_SNAKE_CASE__ : torch.FloatTensor = None # sigma(t_i) def _a ( self , _a , _a = None ) -> torch.FloatTensor: """simple docstring""" return sample def _a ( self , _a , _a = None ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = num_inference_steps SCREAMING_SNAKE_CASE__ : int = np.arange(0 , self.num_inference_steps )[::-1].copy() SCREAMING_SNAKE_CASE__ : Optional[int] = torch.from_numpy(_a ).to(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in self.timesteps ] SCREAMING_SNAKE_CASE__ : Dict = torch.tensor(_a , dtype=torch.floataa , device=_a ) def _a ( self , _a , _a , _a = None ) -> Tuple[torch.FloatTensor, float]: """simple docstring""" if self.config.s_min <= sigma <= self.config.s_max: SCREAMING_SNAKE_CASE__ : Union[str, Any] = min(self.config.s_churn / self.num_inference_steps , 2**0.5 - 1 ) else: SCREAMING_SNAKE_CASE__ : Dict = 0 # sample eps ~ N(0, S_noise^2 * I) SCREAMING_SNAKE_CASE__ : Tuple = self.config.s_noise * randn_tensor(sample.shape , generator=_a ).to(sample.device ) SCREAMING_SNAKE_CASE__ : List[str] = sigma + gamma * sigma SCREAMING_SNAKE_CASE__ : List[str] = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def _a ( self , _a , _a , _a , _a , _a = True , ) -> Union[KarrasVeOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = sample_hat + sigma_hat * model_output SCREAMING_SNAKE_CASE__ : Union[str, Any] = (sample_hat - pred_original_sample) / sigma_hat SCREAMING_SNAKE_CASE__ : List[str] = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=_a , derivative=_a , pred_original_sample=_a ) def _a ( self , _a , _a , _a , _a , _a , _a , _a = True , ) -> Union[KarrasVeOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = sample_prev + sigma_prev * model_output SCREAMING_SNAKE_CASE__ : Union[str, Any] = (sample_prev - pred_original_sample) / sigma_prev SCREAMING_SNAKE_CASE__ : Dict = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=_a , derivative=_a , pred_original_sample=_a ) def _a ( self , _a , _a , _a ) -> Optional[Any]: """simple docstring""" raise NotImplementedError()
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 ) -> str: if number > 0: raise ValueError("""input must be a negative integer""" ) SCREAMING_SNAKE_CASE__ : Tuple = len(bin(__lowerCAmelCase )[3:] ) SCREAMING_SNAKE_CASE__ : Any = bin(abs(__lowerCAmelCase ) - (1 << binary_number_length) )[3:] SCREAMING_SNAKE_CASE__ : Dict = ( ( """1""" + """0""" * (binary_number_length - len(__lowerCAmelCase )) + twos_complement_number ) if number < 0 else """0""" ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
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 tempfile import unittest from make_student import create_student_by_copying_alternating_layers from transformers import AutoConfig from transformers.file_utils import cached_property from transformers.testing_utils import require_torch a :Dict = "sshleifer/bart-tiny-random" a :Tuple = "patrickvonplaten/t5-tiny-random" @require_torch class __a (unittest.TestCase): '''simple docstring''' @cached_property def _a ( self ) -> Any: """simple docstring""" return AutoConfig.from_pretrained(_a ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ : Dict = create_student_by_copying_alternating_layers(_a , tempfile.mkdtemp() , e=1 , d=1 ) self.assertEqual(student.config.num_hidden_layers , 1 ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ : int = create_student_by_copying_alternating_layers(_a , tempfile.mkdtemp() , e=1 , d=_a ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_student_by_copying_alternating_layers(_a , tempfile.mkdtemp() , e=1 , d=_a ) self.assertEqual(student.config.encoder_layers , 1 ) self.assertEqual(student.config.decoder_layers , self.teacher_config.encoder_layers ) def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ : List[Any] = create_student_by_copying_alternating_layers(_a , tempfile.mkdtemp() , e=1 , d=1 ) self.assertEqual(student.config.encoder_layers , 1 ) self.assertEqual(student.config.decoder_layers , 1 ) def _a ( self ) -> Any: """simple docstring""" with self.assertRaises(_a ): create_student_by_copying_alternating_layers(_a , tempfile.mkdtemp() , e=_a , d=_a )
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 argparse from collections import defaultdict import yaml a :Optional[int] = "docs/source/en/_toctree.yml" def _lowercase ( __lowerCAmelCase ) -> List[str]: SCREAMING_SNAKE_CASE__ : Optional[Any] = defaultdict(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = [] SCREAMING_SNAKE_CASE__ : List[str] = [] for doc in doc_list: if "local" in doc: counts[doc["local"]] += 1 if doc["title"].lower() == "overview": overview_doc.append({"""local""": doc["""local"""], """title""": doc["""title"""]} ) else: new_doc_list.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = new_doc_list SCREAMING_SNAKE_CASE__ : List[str] = [key for key, value in counts.items() if value > 1] SCREAMING_SNAKE_CASE__ : int = [] for duplicate_key in duplicates: SCREAMING_SNAKE_CASE__ : Union[str, Any] = list({doc["""title"""] for doc in doc_list if doc["""local"""] == duplicate_key} ) if len(__lowerCAmelCase ) > 1: raise ValueError( F'''{duplicate_key} is present several times in the documentation table of content at ''' """`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the """ """others.""" ) # Only add this once new_doc.append({"""local""": duplicate_key, """title""": titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in doc_list if """local""" not in counts or counts[doc["""local"""]] == 1] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = sorted(__lowerCAmelCase , key=lambda __lowerCAmelCase : s["title"].lower() ) # "overview" gets special treatment and is always first if len(__lowerCAmelCase ) > 1: raise ValueError("""{doc_list} has two 'overview' docs which is not allowed.""" ) overview_doc.extend(__lowerCAmelCase ) # Sort return overview_doc def _lowercase ( __lowerCAmelCase=False ) -> List[str]: with open(__lowerCAmelCase , encoding="""utf-8""" ) as f: SCREAMING_SNAKE_CASE__ : Tuple = yaml.safe_load(f.read() ) # Get to the API doc SCREAMING_SNAKE_CASE__ : int = 0 while content[api_idx]["title"] != "API": api_idx += 1 SCREAMING_SNAKE_CASE__ : Any = content[api_idx]["""sections"""] # Then to the model doc SCREAMING_SNAKE_CASE__ : Dict = 0 while api_doc[scheduler_idx]["title"] != "Schedulers": scheduler_idx += 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = api_doc[scheduler_idx]["""sections"""] SCREAMING_SNAKE_CASE__ : Optional[int] = clean_doc_toc(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = False if new_scheduler_doc != scheduler_doc: SCREAMING_SNAKE_CASE__ : Any = True if overwrite: SCREAMING_SNAKE_CASE__ : List[Any] = new_scheduler_doc if diff: if overwrite: SCREAMING_SNAKE_CASE__ : Dict = api_doc with open(__lowerCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write(yaml.dump(__lowerCAmelCase , allow_unicode=__lowerCAmelCase ) ) else: raise ValueError( """The model doc part of the table of content is not properly sorted, run `make style` to fix this.""" ) def _lowercase ( __lowerCAmelCase=False ) -> Optional[int]: with open(__lowerCAmelCase , encoding="""utf-8""" ) as f: SCREAMING_SNAKE_CASE__ : List[Any] = yaml.safe_load(f.read() ) # Get to the API doc SCREAMING_SNAKE_CASE__ : int = 0 while content[api_idx]["title"] != "API": api_idx += 1 SCREAMING_SNAKE_CASE__ : Tuple = content[api_idx]["""sections"""] # Then to the model doc SCREAMING_SNAKE_CASE__ : Any = 0 while api_doc[pipeline_idx]["title"] != "Pipelines": pipeline_idx += 1 SCREAMING_SNAKE_CASE__ : Any = False SCREAMING_SNAKE_CASE__ : List[Any] = api_doc[pipeline_idx]["""sections"""] SCREAMING_SNAKE_CASE__ : Any = [] # sort sub pipeline docs for pipeline_doc in pipeline_docs: if "section" in pipeline_doc: SCREAMING_SNAKE_CASE__ : int = pipeline_doc["""section"""] SCREAMING_SNAKE_CASE__ : Optional[Any] = clean_doc_toc(__lowerCAmelCase ) if overwrite: SCREAMING_SNAKE_CASE__ : List[str] = new_sub_pipeline_doc new_pipeline_docs.append(__lowerCAmelCase ) # sort overall pipeline doc SCREAMING_SNAKE_CASE__ : int = clean_doc_toc(__lowerCAmelCase ) if new_pipeline_docs != pipeline_docs: SCREAMING_SNAKE_CASE__ : List[Any] = True if overwrite: SCREAMING_SNAKE_CASE__ : Optional[Any] = new_pipeline_docs if diff: if overwrite: SCREAMING_SNAKE_CASE__ : str = api_doc with open(__lowerCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write(yaml.dump(__lowerCAmelCase , allow_unicode=__lowerCAmelCase ) ) else: raise ValueError( """The model doc part of the table of content is not properly sorted, run `make style` to fix this.""" ) if __name__ == "__main__": a :List[Any] = argparse.ArgumentParser() parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") a :Optional[Any] = parser.parse_args() check_scheduler_doc(args.fix_and_overwrite) check_pipeline_doc(args.fix_and_overwrite)
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 os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging a :int = logging.get_logger(__name__) a :Optional[Any] = "▁" a :Tuple = {"vocab_file": "sentencepiece.bpe.model"} a :Tuple = { "vocab_file": { "facebook/mbart-large-50-one-to-many-mmt": ( "https://huggingface.co/facebook/mbart-large-50-one-to-many-mmt/resolve/main/sentencepiece.bpe.model" ), } } a :Dict = { "facebook/mbart-large-50-one-to-many-mmt": 1_024, } # fmt: off a :Any = ["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN", "af_ZA", "az_AZ", "bn_IN", "fa_IR", "he_IL", "hr_HR", "id_ID", "ka_GE", "km_KH", "mk_MK", "ml_IN", "mn_MN", "mr_IN", "pl_PL", "ps_AF", "pt_XX", "sv_SE", "sw_KE", "ta_IN", "te_IN", "th_TH", "tl_XX", "uk_UA", "ur_PK", "xh_ZA", "gl_ES", "sl_SI"] class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :int = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE :Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE :List[str] = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE :List[str] = ["""input_ids""", """attention_mask"""] _SCREAMING_SNAKE_CASE :List[int] = [] _SCREAMING_SNAKE_CASE :List[int] = [] def __init__( self , _a , _a=None , _a=None , _a="</s>" , _a="</s>" , _a="<s>" , _a="<unk>" , _a="<pad>" , _a="<mask>" , _a = None , **_a , ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token SCREAMING_SNAKE_CASE__ : Union[str, Any] = {} if sp_model_kwargs is None else sp_model_kwargs SCREAMING_SNAKE_CASE__ : Union[str, Any] = kwargs.get("""additional_special_tokens""" , [] ) kwargs["additional_special_tokens"] += [ code for code in FAIRSEQ_LANGUAGE_CODES if code not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=_a , tgt_lang=_a , eos_token=_a , unk_token=_a , sep_token=_a , cls_token=_a , pad_token=_a , mask_token=_a , sp_model_kwargs=self.sp_model_kwargs , **_a , ) SCREAMING_SNAKE_CASE__ : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_a ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token SCREAMING_SNAKE_CASE__ : Union[str, Any] = {"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab SCREAMING_SNAKE_CASE__ : Dict = 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = len(self.sp_model ) SCREAMING_SNAKE_CASE__ : Dict = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(_a ) } SCREAMING_SNAKE_CASE__ : Optional[Any] = {v: k for k, v in self.lang_code_to_id.items()} SCREAMING_SNAKE_CASE__ : List[str] = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) SCREAMING_SNAKE_CASE__ : Any = {v: k for k, v in self.fairseq_tokens_to_ids.items()} SCREAMING_SNAKE_CASE__ : str = src_lang if src_lang is not None else """en_XX""" SCREAMING_SNAKE_CASE__ : str = self.lang_code_to_id[self._src_lang] SCREAMING_SNAKE_CASE__ : Any = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def _a ( self ) -> int: """simple docstring""" return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def _a ( self ) -> str: """simple docstring""" return self._src_lang @src_lang.setter def _a ( self , _a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.__dict__.copy() SCREAMING_SNAKE_CASE__ : str = None return state def __setstate__( self , _a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): SCREAMING_SNAKE_CASE__ : Tuple = {} SCREAMING_SNAKE_CASE__ : int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = {self.convert_ids_to_tokens(_a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _a ( self , _a ) -> List[str]: """simple docstring""" return self.sp_model.encode(_a , out_type=_a ) def _a ( self , _a ) -> int: """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE__ : List[str] = self.sp_model.PieceToId(_a ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _a ( self , _a ) -> str: """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def _a ( self , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : int = """""" SCREAMING_SNAKE_CASE__ : List[Any] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_a ) + token SCREAMING_SNAKE_CASE__ : List[Any] = True SCREAMING_SNAKE_CASE__ : str = [] else: current_sub_tokens.append(_a ) SCREAMING_SNAKE_CASE__ : Dict = False out_string += self.sp_model.decode(_a ) return out_string.strip() 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"""] ) 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__ : str = self.sp_model.serialized_model_proto() fi.write(_a ) return (out_vocab_file,) 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 ) SCREAMING_SNAKE_CASE__ : Dict = [1] * len(self.prefix_tokens ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(_a )) + suffix_ones return prefix_ones + ([0] * len(_a )) + ([0] * len(_a )) + suffix_ones def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _a ( self , _a , _a , _a , _a , **_a ) -> Tuple: """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model""" ) SCREAMING_SNAKE_CASE__ : int = src_lang SCREAMING_SNAKE_CASE__ : List[Any] = self(_a , add_special_tokens=_a , return_tensors=_a , **_a ) SCREAMING_SNAKE_CASE__ : str = self.convert_tokens_to_ids(_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tgt_lang_id return inputs def _a ( self , _a , _a = "en_XX" , _a = None , _a = "ro_RO" , **_a , ) -> BatchEncoding: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = src_lang SCREAMING_SNAKE_CASE__ : int = tgt_lang return super().prepare_seqaseq_batch(_a , _a , **_a ) def _a ( self ) -> List[Any]: """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def _a ( self ) -> Optional[int]: """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def _a ( self , _a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.lang_code_to_id[src_lang] SCREAMING_SNAKE_CASE__ : List[str] = [self.cur_lang_code_id] SCREAMING_SNAKE_CASE__ : List[Any] = [self.eos_token_id] def _a ( self , _a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.lang_code_to_id[tgt_lang] SCREAMING_SNAKE_CASE__ : List[Any] = [self.cur_lang_code_id] SCREAMING_SNAKE_CASE__ : Any = [self.eos_token_id]
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 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
"""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 gc import importlib.metadata import tempfile import unittest from packaging import version from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig, pipeline, ) from transformers.testing_utils import ( is_torch_available, require_accelerate, require_bitsandbytes, require_torch, require_torch_gpu, require_torch_multi_gpu, slow, ) def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: if model.config.model_type == "gpt2": return model.transformer.h[0].mlp.c_fc return model.transformer.h[0].mlp.dense_ah_to_h if is_torch_available(): import torch import torch.nn as nn class __a (nn.Module): '''simple docstring''' def __init__( self , _a , _a ) -> Union[str, Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Any = module SCREAMING_SNAKE_CASE__ : Optional[int] = nn.Sequential( nn.Linear(module.in_features , _a , bias=_a ) , nn.Linear(_a , module.out_features , bias=_a ) , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = (2.0 / (5 * min(module.in_features , module.out_features ))) ** 0.5 nn.init.normal_(self.adapter[0].weight , std=_a ) nn.init.zeros_(self.adapter[1].weight ) self.adapter.to(module.weight.device ) def _a ( self , _a , *_a , **_a ) -> List[str]: """simple docstring""" return self.module(_a , *_a , **_a ) + self.adapter(_a ) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class __a (unittest.TestCase): '''simple docstring''' # We keep the constants inside the init function and model loading inside setUp function # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected) # Therefore here we use only bloom-1b3 to test our module _SCREAMING_SNAKE_CASE :List[Any] = """bigscience/bloom-1b7""" # Constant values _SCREAMING_SNAKE_CASE :List[str] = 2.1_09_65_95_52_69_25_74 _SCREAMING_SNAKE_CASE :Tuple = """Hello my name is""" _SCREAMING_SNAKE_CASE :Tuple = set() EXPECTED_OUTPUTS.add("""Hello my name is John and I am a professional photographer. I""") EXPECTED_OUTPUTS.add("""Hello my name is John.\nI am a friend of your father.\n""") EXPECTED_OUTPUTS.add("""Hello my name is John Doe, I am a student at the University""") _SCREAMING_SNAKE_CASE :Optional[int] = 10 def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = AutoTokenizer.from_pretrained(self.model_name ) class __a (UpperCamelCase_): '''simple docstring''' def _a ( self ) -> str: """simple docstring""" super().setUp() # Models and tokenizer SCREAMING_SNAKE_CASE__ : Any = AutoModelForCausalLM.from_pretrained( self.model_name , torch_dtype=torch.floataa , device_map="""auto""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=_a , device_map="""auto""" ) def _a ( self ) -> List[Any]: """simple docstring""" del self.model_fpaa del self.model_abit gc.collect() torch.cuda.empty_cache() def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.model_abit.config self.assertTrue(hasattr(_a , """quantization_config""" ) ) SCREAMING_SNAKE_CASE__ : int = config.to_dict() SCREAMING_SNAKE_CASE__ : Any = config.to_diff_dict() SCREAMING_SNAKE_CASE__ : Dict = config.to_json_string() def _a ( self ) -> List[str]: """simple docstring""" from bitsandbytes.nn import Paramsabit SCREAMING_SNAKE_CASE__ : List[Any] = self.model_fpaa.get_memory_footprint() SCREAMING_SNAKE_CASE__ : Any = self.model_abit.get_memory_footprint() self.assertAlmostEqual(mem_fpaa / mem_abit , self.EXPECTED_RELATIVE_DIFFERENCE ) SCREAMING_SNAKE_CASE__ : List[str] = get_some_linear_layer(self.model_abit ) self.assertTrue(linear.weight.__class__ == Paramsabit ) def _a ( self ) -> Any: """simple docstring""" from transformers import TaPreTrainedModel self.model_fpaa.get_memory_footprint() self.model_abit.get_memory_footprint() for name, module in self.model_abit.named_modules(): if isinstance(_a , torch.nn.Linear ): if name not in ["lm_head"] + TaPreTrainedModel._keep_in_fpaa_modules: # 4-bit parameters are packed in uint8 variables self.assertTrue(module.weight.dtype == torch.uinta ) def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.tokenizer(self.input_text , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE__ : List[str] = self.model_abit.generate(input_ids=encoded_input["""input_ids"""].to(0 ) , max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=_a ) , self.EXPECTED_OUTPUTS ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BitsAndBytesConfig() SCREAMING_SNAKE_CASE__ : Tuple = True SCREAMING_SNAKE_CASE__ : int = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=_a , device_map="""auto""" ) SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer(self.input_text , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE__ : str = model_abit_from_config.generate( input_ids=encoded_input["""input_ids"""].to(0 ) , max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=_a ) , self.EXPECTED_OUTPUTS ) def _a ( self ) -> Any: """simple docstring""" with self.assertRaises(_a ), tempfile.TemporaryDirectory() as tmpdirname: self.model_abit.save_pretrained(_a ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = BitsAndBytesConfig() with self.assertRaises(_a ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=_a , load_in_abit=_a , device_map="""auto""" , bnb_abit_quant_type="""nf4""" , ) def _a ( self ) -> Union[str, Any]: """simple docstring""" with self.assertRaises(_a ): # Tries with `str` self.model_abit.to("""cpu""" ) with self.assertRaises(_a ): # Tries with a `dtype`` self.model_abit.to(torch.floataa ) with self.assertRaises(_a ): # Tries with a `device` self.model_abit.to(torch.device("""cuda:0""" ) ) with self.assertRaises(_a ): # Tries with a `device` self.model_abit.float() with self.assertRaises(_a ): # Tries with a `device` self.model_abit.half() # Test if we did not break anything SCREAMING_SNAKE_CASE__ : Optional[int] = self.tokenizer(self.input_text , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE__ : List[str] = self.model_fpaa.to(torch.floataa ) SCREAMING_SNAKE_CASE__ : Dict = self.model_fpaa.generate(input_ids=encoded_input["""input_ids"""].to(0 ) , max_new_tokens=10 ) # Check this does not throw an error SCREAMING_SNAKE_CASE__ : str = self.model_fpaa.to("""cpu""" ) # Check this does not throw an error SCREAMING_SNAKE_CASE__ : Tuple = self.model_fpaa.half() # Check this does not throw an error SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_fpaa.float() def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = AutoModelForSeqaSeqLM.from_pretrained("""t5-small""" , load_in_abit=_a , device_map="""auto""" ) self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.floataa ) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class __a (unittest.TestCase): '''simple docstring''' @classmethod def _a ( cls ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = """t5-small""" SCREAMING_SNAKE_CASE__ : List[str] = """google/flan-t5-small""" # flan-t5 uses dense-act instead of dense-relu-dense SCREAMING_SNAKE_CASE__ : Tuple = AutoTokenizer.from_pretrained(cls.model_name ) SCREAMING_SNAKE_CASE__ : Tuple = """Translate in German: Hello, my dog is cute""" def _a ( self ) -> int: """simple docstring""" gc.collect() torch.cuda.empty_cache() def _a ( self ) -> Optional[Any]: """simple docstring""" from transformers import TaForConditionalGeneration SCREAMING_SNAKE_CASE__ : Union[str, Any] = TaForConditionalGeneration._keep_in_fpaa_modules SCREAMING_SNAKE_CASE__ : str = None # test with `t5-small` SCREAMING_SNAKE_CASE__ : Union[str, Any] = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=_a , device_map="""auto""" ) SCREAMING_SNAKE_CASE__ : Dict = self.tokenizer(self.input_text , return_tensors="""pt""" ).to(0 ) SCREAMING_SNAKE_CASE__ : Tuple = model.generate(**_a ) # test with `flan-t5-small` SCREAMING_SNAKE_CASE__ : Optional[int] = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=_a , device_map="""auto""" ) SCREAMING_SNAKE_CASE__ : str = self.tokenizer(self.input_text , return_tensors="""pt""" ).to(0 ) SCREAMING_SNAKE_CASE__ : Any = model.generate(**_a ) SCREAMING_SNAKE_CASE__ : int = modules def _a ( self ) -> List[str]: """simple docstring""" import bitsandbytes as bnb from transformers import TaForConditionalGeneration # test with `t5-small` SCREAMING_SNAKE_CASE__ : int = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=_a , device_map="""auto""" ) # there was a bug with decoders - this test checks that it is fixed self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q , bnb.nn.Linearabit ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer(self.input_text , return_tensors="""pt""" ).to(0 ) SCREAMING_SNAKE_CASE__ : Dict = model.generate(**_a ) # test with `flan-t5-small` SCREAMING_SNAKE_CASE__ : int = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=_a , device_map="""auto""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.tokenizer(self.input_text , return_tensors="""pt""" ).to(0 ) SCREAMING_SNAKE_CASE__ : List[str] = model.generate(**_a ) class __a (UpperCamelCase_): '''simple docstring''' def _a ( self ) -> Optional[int]: """simple docstring""" super().setUp() # model_name SCREAMING_SNAKE_CASE__ : List[str] = """bigscience/bloom-560m""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = """t5-small""" # Different types of model SCREAMING_SNAKE_CASE__ : List[str] = AutoModel.from_pretrained(self.model_name , load_in_abit=_a , device_map="""auto""" ) # Sequence classification model SCREAMING_SNAKE_CASE__ : List[Any] = AutoModelForSequenceClassification.from_pretrained( self.model_name , load_in_abit=_a , device_map="""auto""" ) # CausalLM model SCREAMING_SNAKE_CASE__ : Tuple = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=_a , device_map="""auto""" ) # Seq2seq model SCREAMING_SNAKE_CASE__ : Any = AutoModelForSeqaSeqLM.from_pretrained( self.seq_to_seq_name , load_in_abit=_a , device_map="""auto""" ) def _a ( self ) -> Tuple: """simple docstring""" del self.base_model del self.sequence_model del self.model_abit del self.seq_to_seq_model gc.collect() torch.cuda.empty_cache() def _a ( self ) -> str: """simple docstring""" from bitsandbytes.nn import Paramsabit self.assertTrue(self.base_model.h[-1].mlp.dense_ah_to_h.weight.__class__ == Paramsabit ) # Other heads should be nn.Parameter self.assertTrue(self.model_abit.lm_head.weight.__class__ == torch.nn.Parameter ) self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter ) self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter ) class __a (UpperCamelCase_): '''simple docstring''' def _a ( self ) -> Optional[int]: """simple docstring""" super().setUp() def _a ( self ) -> List[Any]: """simple docstring""" del self.pipe gc.collect() torch.cuda.empty_cache() def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipeline( """text-generation""" , model=self.model_name , model_kwargs={"""device_map""": """auto""", """load_in_4bit""": True, """torch_dtype""": torch.floataa} , max_new_tokens=self.MAX_NEW_TOKENS , ) # Real second forward pass SCREAMING_SNAKE_CASE__ : Dict = self.pipe(self.input_text ) self.assertIn(pipeline_output[0]["""generated_text"""] , self.EXPECTED_OUTPUTS ) @require_torch_multi_gpu class __a (UpperCamelCase_): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" super().setUp() def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = AutoModelForCausalLM.from_pretrained( self.model_name , load_in_abit=_a , device_map="""balanced""" ) # Check correct device map self.assertEqual(set(model_parallel.hf_device_map.values() ) , {0, 1} ) # Check that inference pass works on the model SCREAMING_SNAKE_CASE__ : List[Any] = self.tokenizer(self.input_text , return_tensors="""pt""" ) # Second real batch SCREAMING_SNAKE_CASE__ : Optional[Any] = model_parallel.generate(input_ids=encoded_input["""input_ids"""].to(0 ) , max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_parallel[0] , skip_special_tokens=_a ) , self.EXPECTED_OUTPUTS ) class __a (UpperCamelCase_): '''simple docstring''' def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = """facebook/opt-350m""" super().setUp() def _a ( self ) -> List[str]: """simple docstring""" if version.parse(importlib.metadata.version("""bitsandbytes""" ) ) < version.parse("""0.37.0""" ): return # Step 1: freeze all parameters SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=_a ) self.assertEqual(set(model.hf_device_map.values() ) , {torch.cuda.current_device()} ) for param in model.parameters(): SCREAMING_SNAKE_CASE__ : List[Any] = False # freeze the model - train adapters later if param.ndim == 1: # cast the small parameters (e.g. layernorm) to fp32 for stability SCREAMING_SNAKE_CASE__ : int = param.data.to(torch.floataa ) # Step 2: add adapters for _, module in model.named_modules(): if "OPTAttention" in repr(type(_a ) ): SCREAMING_SNAKE_CASE__ : int = LoRALayer(module.q_proj , rank=16 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = LoRALayer(module.k_proj , rank=16 ) SCREAMING_SNAKE_CASE__ : Dict = LoRALayer(module.v_proj , rank=16 ) # Step 3: dummy batch SCREAMING_SNAKE_CASE__ : int = self.tokenizer("""Test batch """ , return_tensors="""pt""" ).to(0 ) # Step 4: Check if the gradient is not None with torch.cuda.amp.autocast(): SCREAMING_SNAKE_CASE__ : Optional[Any] = model.forward(**_a ) out.logits.norm().backward() for module in model.modules(): if isinstance(_a , _a ): self.assertTrue(module.adapter[1].weight.grad is not None ) self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0 ) elif isinstance(_a , nn.Embedding ): self.assertTrue(module.weight.grad is None ) class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = """gpt2-xl""" _SCREAMING_SNAKE_CASE :Tuple = 3.31_91_85_48_54_15_21_87
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 logging import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, BertEncoder, BertModel, BertPreTrainedModel, ) a :List[Any] = logging.getLogger(__name__) class __a (UpperCamelCase_): '''simple docstring''' def _a ( self , _a , _a , _a=None , _a=None ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.layer[current_layer](_a , _a , head_mask[current_layer] ) SCREAMING_SNAKE_CASE__ : Dict = layer_outputs[0] return hidden_states @add_start_docstrings( """The bare Bert Model transformer with PABEE outputting raw hidden-states 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__ : str = BertEncoderWithPabee(_a ) self.init_weights() SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 SCREAMING_SNAKE_CASE__ : List[str] = 0 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 def _a ( self , _a ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = threshold def _a ( self , _a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = patience def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = 0 SCREAMING_SNAKE_CASE__ : List[str] = 0 def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.inference_layers_num / self.inference_instances_num SCREAMING_SNAKE_CASE__ : List[Any] = ( f'''*** Patience = {self.patience} Avg. Inference Layers = {avg_inf_layers:.2f} Speed Up =''' f''' {1 - avg_inf_layers / self.config.num_hidden_layers:.2f} ***''' ) print(_a ) @add_start_docstrings_to_model_forward(_a ) def _a ( self , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=False , ) -> str: """simple docstring""" if input_ids is not None and inputs_embeds is not None: raise ValueError("""You cannot specify both input_ids and inputs_embeds at the same time""" ) elif input_ids is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.size() elif inputs_embeds is not None: SCREAMING_SNAKE_CASE__ : str = inputs_embeds.size()[:-1] else: raise ValueError("""You have to specify either input_ids or inputs_embeds""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: SCREAMING_SNAKE_CASE__ : Dict = torch.ones(_a , device=_a ) if token_type_ids is None: SCREAMING_SNAKE_CASE__ : str = torch.zeros(_a , dtype=torch.long , device=_a ) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. SCREAMING_SNAKE_CASE__ : torch.Tensor = self.get_extended_attention_mask(_a , _a , _a ) # If a 2D ou 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if self.config.is_decoder and encoder_hidden_states is not None: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = encoder_hidden_states.size() SCREAMING_SNAKE_CASE__ : int = (encoder_batch_size, encoder_sequence_length) if encoder_attention_mask is None: SCREAMING_SNAKE_CASE__ : Dict = torch.ones(_a , device=_a ) SCREAMING_SNAKE_CASE__ : Dict = self.invert_attention_mask(_a ) else: SCREAMING_SNAKE_CASE__ : str = None # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] SCREAMING_SNAKE_CASE__ : int = self.get_head_mask(_a , self.config.num_hidden_layers ) SCREAMING_SNAKE_CASE__ : int = self.embeddings( input_ids=_a , position_ids=_a , token_type_ids=_a , inputs_embeds=_a ) SCREAMING_SNAKE_CASE__ : int = embedding_output if self.training: SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for i in range(self.config.num_hidden_layers ): SCREAMING_SNAKE_CASE__ : List[Any] = self.encoder.adaptive_forward( _a , current_layer=_a , attention_mask=_a , head_mask=_a ) SCREAMING_SNAKE_CASE__ : int = self.pooler(_a ) SCREAMING_SNAKE_CASE__ : int = output_layers[i](output_dropout(_a ) ) res.append(_a ) elif self.patience == 0: # Use all layers for inference SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.encoder( _a , attention_mask=_a , head_mask=_a , encoder_hidden_states=_a , encoder_attention_mask=_a , ) SCREAMING_SNAKE_CASE__ : List[Any] = self.pooler(encoder_outputs[0] ) SCREAMING_SNAKE_CASE__ : List[str] = [output_layers[self.config.num_hidden_layers - 1](_a )] else: SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : List[str] = 0 for i in range(self.config.num_hidden_layers ): calculated_layer_num += 1 SCREAMING_SNAKE_CASE__ : List[str] = self.encoder.adaptive_forward( _a , current_layer=_a , attention_mask=_a , head_mask=_a ) SCREAMING_SNAKE_CASE__ : str = self.pooler(_a ) SCREAMING_SNAKE_CASE__ : Dict = output_layers[i](_a ) if regression: SCREAMING_SNAKE_CASE__ : Dict = logits.detach() if patient_result is not None: SCREAMING_SNAKE_CASE__ : Any = patient_result.detach() if (patient_result is not None) and torch.abs(patient_result - labels ) < self.regression_threshold: patient_counter += 1 else: SCREAMING_SNAKE_CASE__ : Any = 0 else: SCREAMING_SNAKE_CASE__ : str = logits.detach().argmax(dim=1 ) if patient_result is not None: SCREAMING_SNAKE_CASE__ : Dict = patient_result.detach().argmax(dim=1 ) if (patient_result is not None) and torch.all(labels.eq(_a ) ): patient_counter += 1 else: SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : Any = logits if patient_counter == self.patience: break SCREAMING_SNAKE_CASE__ : Tuple = [patient_result] self.inference_layers_num += calculated_layer_num self.inference_instances_num += 1 return res @add_start_docstrings( """Bert Model transformer with PABEE and a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks. """ , UpperCamelCase_ , ) class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , _a ) -> List[Any]: """simple docstring""" super().__init__(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = config.num_labels SCREAMING_SNAKE_CASE__ : Optional[Any] = BertModelWithPabee(_a ) SCREAMING_SNAKE_CASE__ : Tuple = nn.Dropout(config.hidden_dropout_prob ) SCREAMING_SNAKE_CASE__ : Any = nn.ModuleList( [nn.Linear(config.hidden_size , self.config.num_labels ) for _ in range(config.num_hidden_layers )] ) self.init_weights() @add_start_docstrings_to_model_forward(_a ) def _a ( self , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.bert( input_ids=_a , attention_mask=_a , token_type_ids=_a , position_ids=_a , head_mask=_a , inputs_embeds=_a , output_dropout=self.dropout , output_layers=self.classifiers , regression=self.num_labels == 1 , ) SCREAMING_SNAKE_CASE__ : Any = (logits[-1],) if labels is not None: SCREAMING_SNAKE_CASE__ : List[Any] = None SCREAMING_SNAKE_CASE__ : List[Any] = 0 for ix, logits_item in enumerate(_a ): if self.num_labels == 1: # We are doing regression SCREAMING_SNAKE_CASE__ : Dict = MSELoss() SCREAMING_SNAKE_CASE__ : Dict = loss_fct(logits_item.view(-1 ) , labels.view(-1 ) ) else: SCREAMING_SNAKE_CASE__ : Dict = CrossEntropyLoss() SCREAMING_SNAKE_CASE__ : List[Any] = loss_fct(logits_item.view(-1 , self.num_labels ) , labels.view(-1 ) ) if total_loss is None: SCREAMING_SNAKE_CASE__ : Tuple = loss else: total_loss += loss * (ix + 1) total_weights += ix + 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = (total_loss / total_weights,) + outputs return outputs
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 collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType a :Union[str, Any] = logging.get_logger(__name__) a :List[Any] = { "microsoft/layoutlmv3-base": "https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json", } class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[int] = """layoutlmv3""" def __init__( self , _a=50_265 , _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-5 , _a=1 , _a=0 , _a=2 , _a=1_024 , _a=128 , _a=128 , _a=True , _a=32 , _a=128 , _a=64 , _a=256 , _a=True , _a=True , _a=True , _a=224 , _a=3 , _a=16 , _a=None , **_a , ) -> str: """simple docstring""" super().__init__( vocab_size=_a , hidden_size=_a , num_hidden_layers=_a , num_attention_heads=_a , intermediate_size=_a , hidden_act=_a , hidden_dropout_prob=_a , attention_probs_dropout_prob=_a , max_position_embeddings=_a , type_vocab_size=_a , initializer_range=_a , layer_norm_eps=_a , pad_token_id=_a , bos_token_id=_a , eos_token_id=_a , **_a , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = max_ad_position_embeddings SCREAMING_SNAKE_CASE__ : Optional[int] = coordinate_size SCREAMING_SNAKE_CASE__ : List[Any] = shape_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = has_relative_attention_bias SCREAMING_SNAKE_CASE__ : Optional[int] = rel_pos_bins SCREAMING_SNAKE_CASE__ : Optional[Any] = max_rel_pos SCREAMING_SNAKE_CASE__ : Optional[Any] = has_spatial_attention_bias SCREAMING_SNAKE_CASE__ : Tuple = rel_ad_pos_bins SCREAMING_SNAKE_CASE__ : str = max_rel_ad_pos SCREAMING_SNAKE_CASE__ : Dict = text_embed SCREAMING_SNAKE_CASE__ : List[str] = visual_embed SCREAMING_SNAKE_CASE__ : str = input_size SCREAMING_SNAKE_CASE__ : Tuple = num_channels SCREAMING_SNAKE_CASE__ : Dict = patch_size SCREAMING_SNAKE_CASE__ : Optional[int] = classifier_dropout class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Dict = version.parse("""1.12""") @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """sequence"""}), ("""attention_mask""", {0: """batch""", 1: """sequence"""}), ("""bbox""", {0: """batch""", 1: """sequence"""}), ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) else: return OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """sequence"""}), ("""bbox""", {0: """batch""", 1: """sequence"""}), ("""attention_mask""", {0: """batch""", 1: """sequence"""}), ("""pixel_values""", {0: """batch""", 1: """num_channels"""}), ] ) @property def _a ( self ) -> float: """simple docstring""" return 1E-5 @property def _a ( self ) -> int: """simple docstring""" return 12 def _a ( self , _a , _a = -1 , _a = -1 , _a = False , _a = None , _a = 3 , _a = 40 , _a = 40 , ) -> Mapping[str, Any]: """simple docstring""" setattr(processor.image_processor , """apply_ocr""" , _a ) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX SCREAMING_SNAKE_CASE__ : Union[str, Any] = compute_effective_axis_dimension( _a , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX SCREAMING_SNAKE_CASE__ : Tuple = processor.tokenizer.num_special_tokens_to_add(_a ) SCREAMING_SNAKE_CASE__ : int = compute_effective_axis_dimension( _a , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=_a ) # Generate dummy inputs according to compute batch and sequence SCREAMING_SNAKE_CASE__ : Tuple = [[""" """.join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size # Generate dummy bounding boxes SCREAMING_SNAKE_CASE__ : List[str] = [[[48, 84, 73, 128]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) SCREAMING_SNAKE_CASE__ : List[Any] = self._generate_dummy_images(_a , _a , _a , _a ) SCREAMING_SNAKE_CASE__ : str = dict( processor( _a , text=_a , boxes=_a , return_tensors=_a , ) ) return inputs
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 collections import defaultdict from pathlib import Path import pandas as pd from rouge_cli import calculate_rouge_path from utils import calculate_rouge a :Any = [ "Prosecutor: \"No videos were used in the crash investigation\" German papers say they saw a cell phone video of the" " final seconds on board Flight 9525. The Germanwings co-pilot says he had a \"previous episode of severe" " depression\" German airline confirms it knew of Andreas Lubitz's depression years before he took control.", "The Palestinian Authority officially becomes the 123rd member of the International Criminal Court. The formal" " accession was marked with a ceremony at The Hague, in the Netherlands. The Palestinians signed the ICC's" " founding Rome Statute in January. Israel and the United States opposed the Palestinians' efforts to join the" " body.", "Amnesty International releases its annual report on the death penalty. The report catalogs the use of" " state-sanctioned killing as a punitive measure across the globe. At least 607 people were executed around the" " world in 2014, compared to 778 in 2013. The U.S. remains one of the worst offenders for imposing capital" " punishment.", ] a :str = [ "Marseille prosecutor says \"so far no videos were used in the crash investigation\" despite media reports ." " Journalists at Bild and Paris Match are \"very confident\" the video clip is real, an editor says . Andreas Lubitz" " had informed his Lufthansa training school of an episode of severe depression, airline says .", "Membership gives the ICC jurisdiction over alleged crimes committed in Palestinian territories since last June ." " Israel and the United States opposed the move, which could open the door to war crimes investigations against" " Israelis .", "Amnesty's annual death penalty report catalogs encouraging signs, but setbacks in numbers of those sentenced to" " death . Organization claims that governments around the world are using the threat of terrorism to advance" " executions . The number of executions worldwide has gone down by almost 22% compared with 2013, but death" " sentences up by 28% .", ] def _lowercase ( ) -> str: SCREAMING_SNAKE_CASE__ : int = calculate_rouge(__lowerCAmelCase , __lowerCAmelCase , bootstrap_aggregation=__lowerCAmelCase , rouge_keys=["""rouge2""", """rougeL"""] ) assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = calculate_rouge(__lowerCAmelCase , __lowerCAmelCase , bootstrap_aggregation=__lowerCAmelCase , rouge_keys=["""rouge2"""] ) assert ( pd.DataFrame(no_aggregation["""rouge2"""] ).fmeasure.mean() == pd.DataFrame(no_aggregation_just_ra["""rouge2"""] ).fmeasure.mean() ) def _lowercase ( ) -> Any: SCREAMING_SNAKE_CASE__ : Any = """rougeLsum""" SCREAMING_SNAKE_CASE__ : Optional[int] = calculate_rouge(__lowerCAmelCase , __lowerCAmelCase , newline_sep=__lowerCAmelCase , rouge_keys=[k] )[k] SCREAMING_SNAKE_CASE__ : Optional[Any] = calculate_rouge(__lowerCAmelCase , __lowerCAmelCase , newline_sep=__lowerCAmelCase , rouge_keys=[k] )[k] assert score > score_no_sep def _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Dict = ["""rouge1""", """rouge2""", """rougeL"""] SCREAMING_SNAKE_CASE__ : List[str] = calculate_rouge(__lowerCAmelCase , __lowerCAmelCase , newline_sep=__lowerCAmelCase , rouge_keys=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = calculate_rouge(__lowerCAmelCase , __lowerCAmelCase , newline_sep=__lowerCAmelCase , rouge_keys=__lowerCAmelCase ) assert score_sep == score_no_sep def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Optional[int] = [ """Her older sister, Margot Frank, died in 1945, a month earlier than previously thought.""", """Marseille prosecutor says \"so far no videos were used in the crash investigation\" despite media reports .""", ] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ """Margot Frank, died in 1945, a month earlier than previously thought.""", """Prosecutor: \"No videos were used in the crash investigation\" German papers say they saw a cell phone video of""" """ the final seconds on board Flight 9525.""", ] assert calculate_rouge(__lowerCAmelCase , __lowerCAmelCase , newline_sep=__lowerCAmelCase ) == calculate_rouge(__lowerCAmelCase , __lowerCAmelCase , newline_sep=__lowerCAmelCase ) def _lowercase ( ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : int = [ """\" \"a person who has such a video needs to immediately give it to the investigators,\" prosecutor says .<n> \"it is a very disturbing scene,\" editor-in-chief of bild online tells \"erin burnett: outfront\" """ ] SCREAMING_SNAKE_CASE__ : Optional[Any] = [ """ Marseille prosecutor says \"so far no videos were used in the crash investigation\" despite media reports . Journalists at Bild and Paris Match are \"very confident\" the video clip is real, an editor says . Andreas Lubitz had informed his Lufthansa training school of an episode of severe depression, airline says .""" ] SCREAMING_SNAKE_CASE__ : str = calculate_rouge(__lowerCAmelCase , __lowerCAmelCase , rouge_keys=["""rougeLsum"""] , newline_sep=__lowerCAmelCase )["""rougeLsum"""] SCREAMING_SNAKE_CASE__ : Dict = calculate_rouge(__lowerCAmelCase , __lowerCAmelCase , rouge_keys=["""rougeLsum"""] )["""rougeLsum"""] assert new_score > prev_score def _lowercase ( ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[Any] = Path("""examples/seq2seq/test_data/wmt_en_ro""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = calculate_rouge_path(data_dir.joinpath("""test.source""" ) , data_dir.joinpath("""test.target""" ) ) assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = calculate_rouge_path( data_dir.joinpath("""test.source""" ) , data_dir.joinpath("""test.target""" ) , bootstrap_aggregation=__lowerCAmelCase ) assert isinstance(__lowerCAmelCase , __lowerCAmelCase )
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""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from argparse import ArgumentParser from accelerate.commands.config import get_config_parser from accelerate.commands.env import env_command_parser from accelerate.commands.launch import launch_command_parser from accelerate.commands.test import test_command_parser from accelerate.commands.tpu import tpu_command_parser def _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Tuple = ArgumentParser("""Accelerate CLI tool""" , usage="""accelerate <command> [<args>]""" , allow_abbrev=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = parser.add_subparsers(help="""accelerate command helpers""" ) # Register commands get_config_parser(subparsers=__lowerCAmelCase ) env_command_parser(subparsers=__lowerCAmelCase ) launch_command_parser(subparsers=__lowerCAmelCase ) tpu_command_parser(subparsers=__lowerCAmelCase ) test_command_parser(subparsers=__lowerCAmelCase ) # Let's go SCREAMING_SNAKE_CASE__ : str = parser.parse_args() if not hasattr(__lowerCAmelCase , """func""" ): parser.print_help() exit(1 ) # Run args.func(__lowerCAmelCase ) if __name__ == "__main__": main()
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 platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available from . import BaseDiffusersCLICommand def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: return EnvironmentCommand() class __a (UpperCamelCase_): '''simple docstring''' @staticmethod def _a ( _a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = parser.add_parser("""env""" ) download_parser.set_defaults(func=_a ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = huggingface_hub.__version__ SCREAMING_SNAKE_CASE__ : Tuple = """not installed""" SCREAMING_SNAKE_CASE__ : Dict = """NA""" if is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : List[str] = torch.__version__ SCREAMING_SNAKE_CASE__ : Tuple = torch.cuda.is_available() SCREAMING_SNAKE_CASE__ : Dict = """not installed""" if is_transformers_available(): import transformers SCREAMING_SNAKE_CASE__ : Optional[int] = transformers.__version__ SCREAMING_SNAKE_CASE__ : Dict = """not installed""" if is_accelerate_available(): import accelerate SCREAMING_SNAKE_CASE__ : Any = accelerate.__version__ SCREAMING_SNAKE_CASE__ : List[str] = """not installed""" if is_xformers_available(): import xformers SCREAMING_SNAKE_CASE__ : List[str] = xformers.__version__ SCREAMING_SNAKE_CASE__ : List[str] = { """`diffusers` version""": version, """Platform""": platform.platform(), """Python version""": platform.python_version(), """PyTorch version (GPU?)""": f'''{pt_version} ({pt_cuda_available})''', """Huggingface_hub version""": hub_version, """Transformers version""": transformers_version, """Accelerate version""": accelerate_version, """xFormers version""": xformers_version, """Using GPU in script?""": """<fill in>""", """Using distributed or parallel set-up in script?""": """<fill in>""", } print("""\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n""" ) print(self.format_dict(_a ) ) return info @staticmethod def _a ( _a ) -> Dict: """simple docstring""" return "\n".join([f'''- {prop}: {val}''' for prop, val in d.items()] ) + "\n"
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 __future__ import annotations import math def _lowercase ( __lowerCAmelCase ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(__lowerCAmelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _lowercase ( __lowerCAmelCase ) -> list[int]: SCREAMING_SNAKE_CASE__ : Tuple = str(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = [n] for i in range(1 , len(__lowerCAmelCase ) ): list_nums.append(int(str_num[i:] ) ) list_nums.append(int(str_num[:-i] ) ) return list_nums def _lowercase ( __lowerCAmelCase ) -> bool: if len(str(__lowerCAmelCase ) ) > 3: if not is_prime(int(str(__lowerCAmelCase )[-3:] ) ) or not is_prime(int(str(__lowerCAmelCase )[:3] ) ): return False return True def _lowercase ( __lowerCAmelCase = 11 ) -> list[int]: SCREAMING_SNAKE_CASE__ : list[int] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = 13 while len(__lowerCAmelCase ) != count: if validate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = list_truncated_nums(__lowerCAmelCase ) if all(is_prime(__lowerCAmelCase ) for i in list_nums ): list_truncated_primes.append(__lowerCAmelCase ) num += 2 return list_truncated_primes def _lowercase ( ) -> int: return sum(compute_truncated_primes(11 ) ) if __name__ == "__main__": print(f'{sum(compute_truncated_primes(11)) = }')
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 jax.numpy as jnp from ...utils import logging from ..ta.modeling_flax_ta import FlaxTaEncoderModel, FlaxTaForConditionalGeneration, FlaxTaModel from .configuration_mta import MTaConfig a :List[str] = logging.get_logger(__name__) a :Dict = "T5Config" def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> jnp.ndarray: SCREAMING_SNAKE_CASE__ : List[Any] = jnp.zeros_like(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = shifted_input_ids.at[:, 1:].set(input_ids[:, :-1] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = shifted_input_ids.at[:, 0].set(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = jnp.where(shifted_input_ids == -100 , __lowerCAmelCase , __lowerCAmelCase ) return shifted_input_ids class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Dict = """mt5""" _SCREAMING_SNAKE_CASE :int = MTaConfig class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = """mt5""" _SCREAMING_SNAKE_CASE :Any = MTaConfig class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = """mt5""" _SCREAMING_SNAKE_CASE :int = MTaConfig
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""" from collections.abc import Callable import numpy as np def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> np.ndarray: SCREAMING_SNAKE_CASE__ : Tuple = int(np.ceil((x_end - xa) / step_size ) ) SCREAMING_SNAKE_CASE__ : Tuple = np.zeros((n + 1,) ) SCREAMING_SNAKE_CASE__ : Any = ya SCREAMING_SNAKE_CASE__ : int = xa for k in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = y[k] + step_size * ode_func(__lowerCAmelCase , y[k] ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
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 math import sqrt def _lowercase ( __lowerCAmelCase ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(sqrt(__lowerCAmelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _lowercase ( __lowerCAmelCase = 1_0001 ) -> int: SCREAMING_SNAKE_CASE__ : Optional[int] = 0 SCREAMING_SNAKE_CASE__ : List[str] = 1 while count != nth and number < 3: number += 1 if is_prime(__lowerCAmelCase ): count += 1 while count != nth: number += 2 if is_prime(__lowerCAmelCase ): count += 1 return number if __name__ == "__main__": print(f'{solution() = }')
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""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a :Any = { "configuration_electra": ["ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP", "ElectraConfig", "ElectraOnnxConfig"], "tokenization_electra": ["ElectraTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :int = ["ElectraTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST", "ElectraForCausalLM", "ElectraForMaskedLM", "ElectraForMultipleChoice", "ElectraForPreTraining", "ElectraForQuestionAnswering", "ElectraForSequenceClassification", "ElectraForTokenClassification", "ElectraModel", "ElectraPreTrainedModel", "load_tf_weights_in_electra", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST", "TFElectraForMaskedLM", "TFElectraForMultipleChoice", "TFElectraForPreTraining", "TFElectraForQuestionAnswering", "TFElectraForSequenceClassification", "TFElectraForTokenClassification", "TFElectraModel", "TFElectraPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Any = [ "FlaxElectraForCausalLM", "FlaxElectraForMaskedLM", "FlaxElectraForMultipleChoice", "FlaxElectraForPreTraining", "FlaxElectraForQuestionAnswering", "FlaxElectraForSequenceClassification", "FlaxElectraForTokenClassification", "FlaxElectraModel", "FlaxElectraPreTrainedModel", ] if TYPE_CHECKING: from .configuration_electra import ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ElectraConfig, ElectraOnnxConfig from .tokenization_electra import ElectraTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_electra_fast import ElectraTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_electra import ( ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, ElectraForCausalLM, ElectraForMaskedLM, ElectraForMultipleChoice, ElectraForPreTraining, ElectraForQuestionAnswering, ElectraForSequenceClassification, ElectraForTokenClassification, ElectraModel, ElectraPreTrainedModel, load_tf_weights_in_electra, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_electra import ( TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, TFElectraForMaskedLM, TFElectraForMultipleChoice, TFElectraForPreTraining, TFElectraForQuestionAnswering, TFElectraForSequenceClassification, TFElectraForTokenClassification, TFElectraModel, TFElectraPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_electra import ( FlaxElectraForCausalLM, FlaxElectraForMaskedLM, FlaxElectraForMultipleChoice, FlaxElectraForPreTraining, FlaxElectraForQuestionAnswering, FlaxElectraForSequenceClassification, FlaxElectraForTokenClassification, FlaxElectraModel, FlaxElectraPreTrainedModel, ) else: import sys a :Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
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 ..utils import DummyObject, requires_backends class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Tuple = ["""flax"""] def __init__( self , *_a , **_a ) -> List[Any]: """simple docstring""" requires_backends(self , ["""flax"""] ) @classmethod def _a ( cls , *_a , **_a ) -> str: """simple docstring""" requires_backends(cls , ["""flax"""] ) @classmethod def _a ( cls , *_a , **_a ) -> List[Any]: """simple docstring""" requires_backends(cls , ["""flax"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = ["""flax"""] def __init__( self , *_a , **_a ) -> Tuple: """simple docstring""" requires_backends(self , ["""flax"""] ) @classmethod def _a ( cls , *_a , **_a ) -> Union[str, Any]: """simple docstring""" requires_backends(cls , ["""flax"""] ) @classmethod def _a ( cls , *_a , **_a ) -> int: """simple docstring""" requires_backends(cls , ["""flax"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :int = ["""flax"""] def __init__( self , *_a , **_a ) -> Dict: """simple docstring""" requires_backends(self , ["""flax"""] ) @classmethod def _a ( cls , *_a , **_a ) -> List[str]: """simple docstring""" requires_backends(cls , ["""flax"""] ) @classmethod def _a ( cls , *_a , **_a ) -> Any: """simple docstring""" requires_backends(cls , ["""flax"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Dict = ["""flax"""] def __init__( self , *_a , **_a ) -> List[str]: """simple docstring""" requires_backends(self , ["""flax"""] ) @classmethod def _a ( cls , *_a , **_a ) -> Union[str, Any]: """simple docstring""" requires_backends(cls , ["""flax"""] ) @classmethod def _a ( cls , *_a , **_a ) -> Union[str, Any]: """simple docstring""" requires_backends(cls , ["""flax"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Tuple = ["""flax"""] def __init__( self , *_a , **_a ) -> Dict: """simple docstring""" requires_backends(self , ["""flax"""] ) @classmethod def _a ( cls , *_a , **_a ) -> Union[str, Any]: """simple docstring""" requires_backends(cls , ["""flax"""] ) @classmethod def _a ( cls , *_a , **_a ) -> str: """simple docstring""" requires_backends(cls , ["""flax"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = ["""flax"""] def __init__( self , *_a , **_a ) -> Union[str, Any]: """simple docstring""" requires_backends(self , ["""flax"""] ) @classmethod def _a ( cls , *_a , **_a ) -> Optional[Any]: """simple docstring""" requires_backends(cls , ["""flax"""] ) @classmethod def _a ( cls , *_a , **_a ) -> List[Any]: """simple docstring""" requires_backends(cls , ["""flax"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[str] = ["""flax"""] def __init__( self , *_a , **_a ) -> List[Any]: """simple docstring""" requires_backends(self , ["""flax"""] ) @classmethod def _a ( cls , *_a , **_a ) -> Any: """simple docstring""" requires_backends(cls , ["""flax"""] ) @classmethod def _a ( cls , *_a , **_a ) -> Union[str, Any]: """simple docstring""" requires_backends(cls , ["""flax"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[int] = ["""flax"""] def __init__( self , *_a , **_a ) -> List[str]: """simple docstring""" requires_backends(self , ["""flax"""] ) @classmethod def _a ( cls , *_a , **_a ) -> Dict: """simple docstring""" requires_backends(cls , ["""flax"""] ) @classmethod def _a ( cls , *_a , **_a ) -> List[str]: """simple docstring""" requires_backends(cls , ["""flax"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Any = ["""flax"""] def __init__( self , *_a , **_a ) -> Dict: """simple docstring""" requires_backends(self , ["""flax"""] ) @classmethod def _a ( cls , *_a , **_a ) -> List[str]: """simple docstring""" requires_backends(cls , ["""flax"""] ) @classmethod def _a ( cls , *_a , **_a ) -> str: """simple docstring""" requires_backends(cls , ["""flax"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[int] = ["""flax"""] def __init__( self , *_a , **_a ) -> int: """simple docstring""" requires_backends(self , ["""flax"""] ) @classmethod def _a ( cls , *_a , **_a ) -> Dict: """simple docstring""" requires_backends(cls , ["""flax"""] ) @classmethod def _a ( cls , *_a , **_a ) -> Tuple: """simple docstring""" requires_backends(cls , ["""flax"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = ["""flax"""] def __init__( self , *_a , **_a ) -> List[str]: """simple docstring""" requires_backends(self , ["""flax"""] ) @classmethod def _a ( cls , *_a , **_a ) -> Optional[int]: """simple docstring""" requires_backends(cls , ["""flax"""] ) @classmethod def _a ( cls , *_a , **_a ) -> int: """simple docstring""" requires_backends(cls , ["""flax"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = ["""flax"""] def __init__( self , *_a , **_a ) -> Tuple: """simple docstring""" requires_backends(self , ["""flax"""] ) @classmethod def _a ( cls , *_a , **_a ) -> Dict: """simple docstring""" requires_backends(cls , ["""flax"""] ) @classmethod def _a ( cls , *_a , **_a ) -> List[Any]: """simple docstring""" requires_backends(cls , ["""flax"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Dict = ["""flax"""] def __init__( self , *_a , **_a ) -> List[Any]: """simple docstring""" requires_backends(self , ["""flax"""] ) @classmethod def _a ( cls , *_a , **_a ) -> Optional[int]: """simple docstring""" requires_backends(cls , ["""flax"""] ) @classmethod def _a ( cls , *_a , **_a ) -> Tuple: """simple docstring""" requires_backends(cls , ["""flax"""] )
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 manim import * class __a (UpperCamelCase_): '''simple docstring''' def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = Rectangle(height=0.5 , width=0.5 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) SCREAMING_SNAKE_CASE__ : Tuple = Rectangle(height=0.25 , width=0.25 ) SCREAMING_SNAKE_CASE__ : Tuple = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE__ : Any = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE__ : List[str] = VGroup(*_a ).arrange(_a , buff=0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = VGroup(*_a ).arrange(_a , buff=0 ) SCREAMING_SNAKE_CASE__ : List[Any] = VGroup(_a , _a ).arrange(_a , buff=0 ) SCREAMING_SNAKE_CASE__ : int = Text("""CPU""" , font_size=24 ) SCREAMING_SNAKE_CASE__ : Optional[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__ : Tuple = [mem.copy() for i in range(4 )] SCREAMING_SNAKE_CASE__ : Dict = VGroup(*_a ).arrange(_a , buff=0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = Text("""GPU""" , font_size=24 ) SCREAMING_SNAKE_CASE__ : Tuple = Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a ) gpu.move_to([-1, -1, 0] ) self.add(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE__ : List[str] = VGroup(*_a ).arrange(_a , buff=0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = 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.add(_a ) SCREAMING_SNAKE_CASE__ : Dict = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] for i, rect in enumerate(_a ): SCREAMING_SNAKE_CASE__ : Tuple = fill.copy().set_fill(_a , opacity=0.8 ) target.move_to(_a ) model_arr.append(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0.0 ).set_fill(_a , opacity=0.8 ) cpu_target.move_to(cpu_left_col_base[i] ) model_cpu_arr.append(_a ) self.add(*_a , *_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [meta_mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE__ : Optional[Any] = [meta_mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE__ : Any = VGroup(*_a ).arrange(_a , buff=0 ) SCREAMING_SNAKE_CASE__ : List[str] = VGroup(*_a ).arrange(_a , buff=0 ) SCREAMING_SNAKE_CASE__ : Dict = VGroup(_a , _a ).arrange(_a , buff=0 ) SCREAMING_SNAKE_CASE__ : List[str] = Text("""Disk""" , font_size=24 ) SCREAMING_SNAKE_CASE__ : List[Any] = Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a ) disk.move_to([-4, -1.25, 0] ) self.add(_a , _a ) SCREAMING_SNAKE_CASE__ : List[Any] = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = MarkupText( f'''<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model''' , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(_a , _a ) SCREAMING_SNAKE_CASE__ : Any = MarkupText( f'''<span fgcolor=\'{BLUE}\'>●</span> Checkpoint''' , font_size=18 , ) blue_text.next_to(_a , DOWN * 2.4 , aligned_edge=key_text.get_left() ) self.add(_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = MarkupText( f'''Now watch as an input is passed through the model\nand how the memory is utilized and handled.''' , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(_a ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Square(0.3 ) input.set_fill(_a , opacity=1.0 ) input.set_stroke(width=0.0 ) input.next_to(model_base[0] , _a , buff=0.5 ) self.play(Write(_a ) ) input.generate_target() input.target.next_to(model_arr[0] , direction=_a , buff=0.02 ) self.play(MoveToTarget(_a ) ) self.play(FadeOut(_a ) ) SCREAMING_SNAKE_CASE__ : List[Any] = Arrow(start=_a , end=_a , color=_a , buff=0.5 ) a.next_to(model_arr[0].get_left() , _a , buff=0.2 ) model_cpu_arr[0].generate_target() model_cpu_arr[0].target.move_to(gpu_rect[0] ) SCREAMING_SNAKE_CASE__ : Dict = MarkupText( f'''As the input reaches a layer, the hook triggers\nand weights are moved from the CPU\nto the GPU and back.''' , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(_a , run_time=3 ) ) SCREAMING_SNAKE_CASE__ : str = {"""run_time""": 1, """fade_in""": True, """fade_out""": True, """buff""": 0.02} self.play( Write(_a ) , Circumscribe(model_arr[0] , color=_a , **_a ) , Circumscribe(model_cpu_arr[0] , color=_a , **_a ) , Circumscribe(gpu_rect[0] , color=_a , **_a ) , ) self.play(MoveToTarget(model_cpu_arr[0] ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = a.copy() for i in range(6 ): a_c.next_to(model_arr[i].get_right() + 0.02 , _a , buff=0.2 ) input.generate_target() input.target.move_to(model_arr[i].get_right() + 0.02 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = AnimationGroup( FadeOut(_a , run_time=0.5 ) , MoveToTarget(_a , run_time=0.5 ) , FadeIn(_a , run_time=0.5 ) , lag_ratio=0.2 ) self.play(_a ) model_cpu_arr[i].generate_target() model_cpu_arr[i].target.move_to(cpu_left_col_base[i] ) if i < 5: model_cpu_arr[i + 1].generate_target() model_cpu_arr[i + 1].target.move_to(gpu_rect[0] ) if i >= 1: SCREAMING_SNAKE_CASE__ : int = 0.7 self.play( Circumscribe(model_arr[i] , **_a ) , Circumscribe(cpu_left_col_base[i] , **_a ) , Circumscribe(cpu_left_col_base[i + 1] , color=_a , **_a ) , Circumscribe(gpu_rect[0] , color=_a , **_a ) , Circumscribe(model_arr[i + 1] , color=_a , **_a ) , ) if i < 1: self.play( MoveToTarget(model_cpu_arr[i] ) , MoveToTarget(model_cpu_arr[i + 1] ) , ) else: self.play( MoveToTarget(model_cpu_arr[i] , run_time=0.7 ) , MoveToTarget(model_cpu_arr[i + 1] , run_time=0.7 ) , ) else: model_cpu_arr[i].generate_target() model_cpu_arr[i].target.move_to(cpu_left_col_base[-1] ) input.generate_target() input.target.next_to(model_arr[-1].get_right() , RIGHT + 0.02 , buff=0.2 ) self.play( Circumscribe(model_arr[-1] , color=_a , **_a ) , Circumscribe(cpu_left_col_base[-1] , color=_a , **_a ) , Circumscribe(gpu_rect[0] , color=_a , **_a ) , ) self.play(MoveToTarget(model_cpu_arr[i] ) ) SCREAMING_SNAKE_CASE__ : str = a_c SCREAMING_SNAKE_CASE__ : Tuple = a_c.copy() input.generate_target() input.target.next_to(model_base[-1] , RIGHT + 0.02 , buff=0.5 ) self.play( FadeOut(_a ) , FadeOut(_a , run_time=0.5 ) , ) SCREAMING_SNAKE_CASE__ : Dict = MarkupText(f'''Inference on a model too large for GPU memory\nis successfully completed.''' , font_size=24 ) step_a.move_to([2, 2, 0] ) self.play(Write(_a , run_time=3 ) , MoveToTarget(_a ) ) self.wait()
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
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : Tuple = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Optional[Any] = { """microsoft/unispeech-sat-base-100h-libri-ft""": ( """https://huggingface.co/microsoft/unispeech-sat-base-100h-libri-ft/resolve/main/config.json""" ), # See all UniSpeechSat models at https://huggingface.co/models?filter=unispeech_sat } class lowerCamelCase_ ( lowerCamelCase ): a__ = '''unispeech-sat''' def __init__( self , __lowerCAmelCase=3_2 , __lowerCAmelCase=7_6_8 , __lowerCAmelCase=1_2 , __lowerCAmelCase=1_2 , __lowerCAmelCase=3_0_7_2 , __lowerCAmelCase="gelu" , __lowerCAmelCase=0.1 , __lowerCAmelCase=0.1 , __lowerCAmelCase=0.1 , __lowerCAmelCase=0.0 , __lowerCAmelCase=0.0 , __lowerCAmelCase=0.1 , __lowerCAmelCase=0.1 , __lowerCAmelCase=0.02 , __lowerCAmelCase=1E-5 , __lowerCAmelCase="group" , __lowerCAmelCase="gelu" , __lowerCAmelCase=(5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2) , __lowerCAmelCase=(5, 2, 2, 2, 2, 2, 2) , __lowerCAmelCase=(1_0, 3, 3, 3, 3, 2, 2) , __lowerCAmelCase=False , __lowerCAmelCase=1_2_8 , __lowerCAmelCase=1_6 , __lowerCAmelCase=False , __lowerCAmelCase=True , __lowerCAmelCase=0.05 , __lowerCAmelCase=1_0 , __lowerCAmelCase=2 , __lowerCAmelCase=0.0 , __lowerCAmelCase=1_0 , __lowerCAmelCase=0 , __lowerCAmelCase=3_2_0 , __lowerCAmelCase=2 , __lowerCAmelCase=0.1 , __lowerCAmelCase=1_0_0 , __lowerCAmelCase=2_5_6 , __lowerCAmelCase=2_5_6 , __lowerCAmelCase=0.1 , __lowerCAmelCase="mean" , __lowerCAmelCase=False , __lowerCAmelCase=False , __lowerCAmelCase=2_5_6 , __lowerCAmelCase=(5_1_2, 5_1_2, 5_1_2, 5_1_2, 1_5_0_0) , __lowerCAmelCase=(5, 3, 3, 1, 1) , __lowerCAmelCase=(1, 2, 3, 1, 1) , __lowerCAmelCase=5_1_2 , __lowerCAmelCase=0 , __lowerCAmelCase=1 , __lowerCAmelCase=2 , __lowerCAmelCase=5_0_4 , **__lowerCAmelCase , ): """simple docstring""" super().__init__(**__lowerCAmelCase , pad_token_id=__lowerCAmelCase , bos_token_id=__lowerCAmelCase , eos_token_id=__lowerCAmelCase ) __magic_name__ :Optional[int] = hidden_size __magic_name__ :Any = feat_extract_norm __magic_name__ :int = feat_extract_activation __magic_name__ :str = list(__lowerCAmelCase ) __magic_name__ :Dict = list(__lowerCAmelCase ) __magic_name__ :Tuple = list(__lowerCAmelCase ) __magic_name__ :Dict = conv_bias __magic_name__ :Dict = num_conv_pos_embeddings __magic_name__ :int = num_conv_pos_embedding_groups __magic_name__ :Any = len(self.conv_dim ) __magic_name__ :Optional[Any] = num_hidden_layers __magic_name__ :List[Any] = intermediate_size __magic_name__ :Union[str, Any] = hidden_act __magic_name__ :List[str] = num_attention_heads __magic_name__ :Tuple = hidden_dropout __magic_name__ :Tuple = attention_dropout __magic_name__ :List[str] = activation_dropout __magic_name__ :Any = feat_proj_dropout __magic_name__ :List[str] = final_dropout __magic_name__ :Tuple = layerdrop __magic_name__ :List[Any] = layer_norm_eps __magic_name__ :List[Any] = initializer_range __magic_name__ :Optional[Any] = vocab_size __magic_name__ :Tuple = num_clusters __magic_name__ :str = do_stable_layer_norm __magic_name__ :Dict = use_weighted_layer_sum if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( '''Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==''' ''' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =''' F''' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,''' F''' `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __magic_name__ :Dict = apply_spec_augment __magic_name__ :List[Any] = mask_time_prob __magic_name__ :Tuple = mask_time_length __magic_name__ :Any = mask_time_min_masks __magic_name__ :Optional[Any] = mask_feature_prob __magic_name__ :int = mask_feature_length __magic_name__ :Optional[int] = mask_feature_min_masks # parameters for pretraining with codevector quantized representations __magic_name__ :Any = num_codevectors_per_group __magic_name__ :Dict = num_codevector_groups __magic_name__ :List[str] = contrastive_logits_temperature __magic_name__ :List[Any] = feat_quantizer_dropout __magic_name__ :List[str] = num_negatives __magic_name__ :Union[str, Any] = codevector_dim __magic_name__ :Optional[int] = proj_codevector_dim __magic_name__ :Optional[Any] = diversity_loss_weight # ctc loss __magic_name__ :Tuple = ctc_loss_reduction __magic_name__ :Tuple = ctc_zero_infinity # SequenceClassification-specific parameter. Feel free to ignore for other classes. __magic_name__ :Tuple = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. __magic_name__ :Any = list(__lowerCAmelCase ) __magic_name__ :str = list(__lowerCAmelCase ) __magic_name__ :str = list(__lowerCAmelCase ) __magic_name__ :Union[str, Any] = xvector_output_dim @property def A ( self ): """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
0
"""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
0
import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class __lowerCamelCase (_a , _a ): @register_to_config def __init__( self: List[Any],*, A_: int = 4,A_: int = 768,A_: int,A_: Tuple,): '''simple docstring''' super().__init__() __UpperCamelCase = nn.Parameter(torch.zeros(A_ ) ) # parameters for additional clip time embeddings __UpperCamelCase = nn.Linear(A_,A_ ) __UpperCamelCase = nn.Linear(A_,A_ ) # parameters for encoder hidden states __UpperCamelCase = clip_extra_context_tokens __UpperCamelCase = nn.Linear( A_,self.clip_extra_context_tokens * cross_attention_dim ) __UpperCamelCase = nn.Linear(A_,A_ ) __UpperCamelCase = nn.LayerNorm(A_ ) def snake_case_ ( self: int,*, A_: Optional[int],A_: Tuple,A_: str,A_: int ): '''simple docstring''' if do_classifier_free_guidance: # Add the classifier free guidance embeddings to the image embeddings __UpperCamelCase = image_embeddings.shape[0] __UpperCamelCase = self.learned_classifier_free_guidance_embeddings.unsqueeze(0 ) __UpperCamelCase = classifier_free_guidance_embeddings.expand( A_,-1 ) __UpperCamelCase = torch.cat([classifier_free_guidance_embeddings, image_embeddings],dim=0 ) # The image embeddings batch size and the text embeddings batch size are equal assert image_embeddings.shape[0] == prompt_embeds.shape[0] __UpperCamelCase = prompt_embeds.shape[0] # "Specifically, we modify the architecture described in Nichol et al. (2021) by projecting and # adding CLIP embeddings to the existing timestep embedding, ... __UpperCamelCase = self.embedding_proj(A_ ) __UpperCamelCase = self.clip_image_embeddings_project_to_time_embeddings(A_ ) __UpperCamelCase = time_projected_image_embeddings + time_projected_prompt_embeds # ... and by projecting CLIP embeddings into four # extra tokens of context that are concatenated to the sequence of outputs from the GLIDE text encoder" __UpperCamelCase = self.clip_extra_context_tokens_proj(A_ ) __UpperCamelCase = clip_extra_context_tokens.reshape(A_,-1,self.clip_extra_context_tokens ) __UpperCamelCase = clip_extra_context_tokens.permute(0,2,1 ) __UpperCamelCase = self.encoder_hidden_states_proj(A_ ) __UpperCamelCase = self.text_encoder_hidden_states_norm(A_ ) __UpperCamelCase = torch.cat([clip_extra_context_tokens, text_encoder_hidden_states],dim=1 ) return text_encoder_hidden_states, additive_clip_time_embeddings
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
0
import json import os import tempfile import unittest import numpy as np from datasets import load_dataset from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ImageGPTImageProcessor class lowerCamelCase__ ( unittest.TestCase): """simple docstring""" def __init__( self : Union[str, Any] , __lowerCAmelCase : str , __lowerCAmelCase : Tuple=7 , __lowerCAmelCase : Any=3 , __lowerCAmelCase : str=18 , __lowerCAmelCase : Union[str, Any]=30 , __lowerCAmelCase : Optional[Any]=4_00 , __lowerCAmelCase : Dict=True , __lowerCAmelCase : Optional[Any]=None , __lowerCAmelCase : str=True , ) -> Dict: _A = size if size is not None else {'''height''': 18, '''width''': 18} _A = parent _A = batch_size _A = num_channels _A = image_size _A = min_resolution _A = max_resolution _A = do_resize _A = size _A = do_normalize def snake_case_ ( self : Dict ) -> Union[str, Any]: return { # here we create 2 clusters for the sake of simplicity "clusters": np.asarray( [ [0.8866_4436_3403_3203, 0.6618_8293_6954_4983, 0.3891_7464_0178_6804], [-0.6042_5591_4688_1104, -0.0_2295_0088_6052_8469, 0.5423_7973_6900_3296], ] ), "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, } @require_torch @require_vision class lowerCamelCase__ ( _A , unittest.TestCase): """simple docstring""" a__ : Union[str, Any] = ImageGPTImageProcessor if is_vision_available() else None def snake_case_ ( self : List[str] ) -> str: _A = ImageGPTImageProcessingTester(self ) @property def snake_case_ ( self : List[Any] ) -> int: return self.image_processor_tester.prepare_image_processor_dict() def snake_case_ ( self : Union[str, Any] ) -> Optional[int]: _A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__lowerCAmelCase , '''clusters''' ) ) self.assertTrue(hasattr(__lowerCAmelCase , '''do_resize''' ) ) self.assertTrue(hasattr(__lowerCAmelCase , '''size''' ) ) self.assertTrue(hasattr(__lowerCAmelCase , '''do_normalize''' ) ) def snake_case_ ( self : List[Any] ) -> Any: _A = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''height''': 18, '''width''': 18} ) _A = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {'''height''': 42, '''width''': 42} ) def snake_case_ ( self : str ) -> Optional[int]: _A = self.image_processing_class(**self.image_processor_dict ) _A = json.loads(image_processor.to_json_string() ) for key, value in self.image_processor_dict.items(): if key == "clusters": self.assertTrue(np.array_equal(__lowerCAmelCase , obj[key] ) ) else: self.assertEqual(obj[key] , __lowerCAmelCase ) def snake_case_ ( self : int ) -> Tuple: _A = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: _A = os.path.join(__lowerCAmelCase , '''image_processor.json''' ) image_processor_first.to_json_file(__lowerCAmelCase ) _A = self.image_processing_class.from_json_file(__lowerCAmelCase ).to_dict() _A = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(__lowerCAmelCase , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , __lowerCAmelCase ) def snake_case_ ( self : Dict ) -> int: _A = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: image_processor_first.save_pretrained(__lowerCAmelCase ) _A = self.image_processing_class.from_pretrained(__lowerCAmelCase ).to_dict() _A = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(__lowerCAmelCase , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , __lowerCAmelCase ) @unittest.skip('''ImageGPT requires clusters at initialization''' ) def snake_case_ ( self : Union[str, Any] ) -> Dict: pass def SCREAMING_SNAKE_CASE_ ( ) -> Optional[int]: _A = load_dataset('''hf-internal-testing/fixtures_image_utils''' , split='''test''' ) _A = Image.open(dataset[4]['''file'''] ) _A = Image.open(dataset[5]['''file'''] ) _A = [imagea, imagea] return images @require_vision @require_torch class lowerCamelCase__ ( unittest.TestCase): """simple docstring""" @slow def snake_case_ ( self : Optional[Any] ) -> str: _A = ImageGPTImageProcessor.from_pretrained('''openai/imagegpt-small''' ) _A = prepare_images() # test non-batched _A = image_processing(images[0] , return_tensors='''pt''' ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (1, 10_24) ) _A = [3_06, 1_91, 1_91] self.assertEqual(encoding.input_ids[0, :3].tolist() , __lowerCAmelCase ) # test batched _A = image_processing(__lowerCAmelCase , return_tensors='''pt''' ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (2, 10_24) ) _A = [3_03, 13, 13] self.assertEqual(encoding.input_ids[1, -3:].tolist() , __lowerCAmelCase )
2
"""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
0
'''simple docstring''' from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig lowerCAmelCase : Dict = logging.get_logger(__name__) # General docstring lowerCAmelCase : str = 'RegNetConfig' # Base docstring lowerCAmelCase : str = 'facebook/regnet-y-040' lowerCAmelCase : Dict = [1, 10_88, 7, 7] # Image classification docstring lowerCAmelCase : Dict = 'facebook/regnet-y-040' lowerCAmelCase : int = 'tabby, tabby cat' lowerCAmelCase : int = [ 'facebook/regnet-y-040', # See all regnet models at https://huggingface.co/models?filter=regnet ] class SCREAMING_SNAKE_CASE__ ( tf.keras.layers.Layer): def __init__( self , A_ , A_ = 3 , A_ = 1 , A_ = 1 , A_ = "relu" , **A_ , )-> str: '''simple docstring''' super().__init__(**A_ ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb UpperCamelCase = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) UpperCamelCase = tf.keras.layers.ConvaD( filters=A_ , kernel_size=A_ , strides=A_ , padding='VALID' , groups=A_ , use_bias=A_ , name='convolution' , ) UpperCamelCase = tf.keras.layers.BatchNormalization(epsilon=1e-5 , momentum=0.9 , name='normalization' ) UpperCamelCase = ACTaFN[activation] if activation is not None else tf.identity def UpperCAmelCase_ ( self , A_ )-> Any: '''simple docstring''' UpperCamelCase = self.convolution(self.padding(A_ ) ) UpperCamelCase = self.normalization(A_ ) UpperCamelCase = self.activation(A_ ) return hidden_state class SCREAMING_SNAKE_CASE__ ( tf.keras.layers.Layer): def __init__( self , A_ , **A_ )-> Optional[Any]: '''simple docstring''' super().__init__(**A_ ) UpperCamelCase = config.num_channels UpperCamelCase = TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name='embedder' , ) def UpperCAmelCase_ ( self , A_ )-> List[Any]: '''simple docstring''' UpperCamelCase = shape_list(A_ )[1] if tf.executing_eagerly() and 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.' ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) UpperCamelCase = tf.transpose(A_ , perm=(0, 2, 3, 1) ) UpperCamelCase = self.embedder(A_ ) return hidden_state class SCREAMING_SNAKE_CASE__ ( tf.keras.layers.Layer): def __init__( self , A_ , A_ = 2 , **A_ )-> List[Any]: '''simple docstring''' super().__init__(**A_ ) UpperCamelCase = tf.keras.layers.ConvaD( filters=A_ , kernel_size=1 , strides=A_ , use_bias=A_ , name='convolution' ) UpperCamelCase = tf.keras.layers.BatchNormalization(epsilon=1e-5 , momentum=0.9 , name='normalization' ) def UpperCAmelCase_ ( self , A_ , A_ = False )-> tf.Tensor: '''simple docstring''' return self.normalization(self.convolution(A_ ) , training=A_ ) class SCREAMING_SNAKE_CASE__ ( tf.keras.layers.Layer): def __init__( self , A_ , A_ , **A_ )-> Optional[Any]: '''simple docstring''' super().__init__(**A_ ) UpperCamelCase = tf.keras.layers.GlobalAveragePoolingaD(keepdims=A_ , name='pooler' ) UpperCamelCase = [ tf.keras.layers.ConvaD(filters=A_ , kernel_size=1 , activation='relu' , name='attention.0' ), tf.keras.layers.ConvaD(filters=A_ , kernel_size=1 , activation='sigmoid' , name='attention.2' ), ] def UpperCAmelCase_ ( self , A_ )-> Optional[int]: '''simple docstring''' UpperCamelCase = self.pooler(A_ ) for layer_module in self.attention: UpperCamelCase = layer_module(A_ ) UpperCamelCase = hidden_state * pooled return hidden_state class SCREAMING_SNAKE_CASE__ ( tf.keras.layers.Layer): def __init__( self , A_ , A_ , A_ , A_ = 1 , **A_ )-> Dict: '''simple docstring''' super().__init__(**A_ ) UpperCamelCase = in_channels != out_channels or stride != 1 UpperCamelCase = max(1 , out_channels // config.groups_width ) UpperCamelCase = ( TFRegNetShortCut(A_ , stride=A_ , name='shortcut' ) if should_apply_shortcut else tf.keras.layers.Activation('linear' , name='shortcut' ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. UpperCamelCase = [ TFRegNetConvLayer(A_ , kernel_size=1 , activation=config.hidden_act , name='layer.0' ), TFRegNetConvLayer( A_ , stride=A_ , groups=A_ , activation=config.hidden_act , name='layer.1' ), TFRegNetConvLayer(A_ , kernel_size=1 , activation=A_ , name='layer.2' ), ] UpperCamelCase = ACTaFN[config.hidden_act] def UpperCAmelCase_ ( self , A_ )-> Tuple: '''simple docstring''' UpperCamelCase = hidden_state for layer_module in self.layers: UpperCamelCase = layer_module(A_ ) UpperCamelCase = self.shortcut(A_ ) hidden_state += residual UpperCamelCase = self.activation(A_ ) return hidden_state class SCREAMING_SNAKE_CASE__ ( tf.keras.layers.Layer): def __init__( self , A_ , A_ , A_ , A_ = 1 , **A_ )-> Any: '''simple docstring''' super().__init__(**A_ ) UpperCamelCase = in_channels != out_channels or stride != 1 UpperCamelCase = max(1 , out_channels // config.groups_width ) UpperCamelCase = ( TFRegNetShortCut(A_ , stride=A_ , name='shortcut' ) if should_apply_shortcut else tf.keras.layers.Activation('linear' , name='shortcut' ) ) UpperCamelCase = [ TFRegNetConvLayer(A_ , kernel_size=1 , activation=config.hidden_act , name='layer.0' ), TFRegNetConvLayer( A_ , stride=A_ , groups=A_ , activation=config.hidden_act , name='layer.1' ), TFRegNetSELayer(A_ , reduced_channels=int(round(in_channels / 4 ) ) , name='layer.2' ), TFRegNetConvLayer(A_ , kernel_size=1 , activation=A_ , name='layer.3' ), ] UpperCamelCase = ACTaFN[config.hidden_act] def UpperCAmelCase_ ( self , A_ )-> List[Any]: '''simple docstring''' UpperCamelCase = hidden_state for layer_module in self.layers: UpperCamelCase = layer_module(A_ ) UpperCamelCase = self.shortcut(A_ ) hidden_state += residual UpperCamelCase = self.activation(A_ ) return hidden_state class SCREAMING_SNAKE_CASE__ ( tf.keras.layers.Layer): def __init__( self , A_ , A_ , A_ , A_ = 2 , A_ = 2 , **A_ )-> Dict: '''simple docstring''' super().__init__(**A_ ) UpperCamelCase = TFRegNetXLayer if config.layer_type == 'x' else TFRegNetYLayer UpperCamelCase = [ # downsampling is done in the first layer with stride of 2 layer(A_ , A_ , A_ , stride=A_ , name='layers.0' ), *[layer(A_ , A_ , A_ , name=F'''layers.{i+1}''' ) for i in range(depth - 1 )], ] def UpperCAmelCase_ ( self , A_ )-> List[Any]: '''simple docstring''' for layer_module in self.layers: UpperCamelCase = layer_module(A_ ) return hidden_state class SCREAMING_SNAKE_CASE__ ( tf.keras.layers.Layer): def __init__( self , A_ , **A_ )-> str: '''simple docstring''' super().__init__(**A_ ) UpperCamelCase = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( A_ , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name='stages.0' , ) ) UpperCamelCase = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(A_ , config.depths[1:] ) ): self.stages.append(TFRegNetStage(A_ , A_ , A_ , depth=A_ , name=F'''stages.{i+1}''' ) ) def UpperCAmelCase_ ( self , A_ , A_ = False , A_ = True )-> TFBaseModelOutputWithNoAttention: '''simple docstring''' UpperCamelCase = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: UpperCamelCase = hidden_states + (hidden_state,) UpperCamelCase = stage_module(A_ ) if output_hidden_states: UpperCamelCase = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=A_ , hidden_states=A_ ) @keras_serializable class SCREAMING_SNAKE_CASE__ ( tf.keras.layers.Layer): lowerCAmelCase_ = RegNetConfig def __init__( self , A_ , **A_ )-> Union[str, Any]: '''simple docstring''' super().__init__(**A_ ) UpperCamelCase = config UpperCamelCase = TFRegNetEmbeddings(A_ , name='embedder' ) UpperCamelCase = TFRegNetEncoder(A_ , name='encoder' ) UpperCamelCase = tf.keras.layers.GlobalAveragePoolingaD(keepdims=A_ , name='pooler' ) @unpack_inputs def UpperCAmelCase_ ( self , A_ , A_ = None , A_ = None , A_ = False , )-> TFBaseModelOutputWithPoolingAndNoAttention: '''simple docstring''' UpperCamelCase = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) UpperCamelCase = return_dict if return_dict is not None else self.config.use_return_dict UpperCamelCase = self.embedder(A_ , training=A_ ) UpperCamelCase = self.encoder( A_ , output_hidden_states=A_ , return_dict=A_ , training=A_ ) UpperCamelCase = encoder_outputs[0] UpperCamelCase = self.pooler(A_ ) # Change to NCHW output format have uniformity in the modules UpperCamelCase = tf.transpose(A_ , perm=(0, 3, 1, 2) ) UpperCamelCase = tf.transpose(A_ , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: UpperCamelCase = tuple([tf.transpose(A_ , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=A_ , pooler_output=A_ , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class SCREAMING_SNAKE_CASE__ ( snake_case_): lowerCAmelCase_ = RegNetConfig lowerCAmelCase_ = """regnet""" lowerCAmelCase_ = """pixel_values""" @property def UpperCAmelCase_ ( self )-> List[str]: '''simple docstring''' return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 224, 224) , dtype=tf.floataa )} lowerCAmelCase : str = r'\n Parameters:\n This model is a Tensorflow\n [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a\n regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and\n behavior.\n config ([`RegNetConfig`]): 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 [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.\n' lowerCAmelCase : List[str] = r'\n Args:\n pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConveNextImageProcessor.__call__`] for details.\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 RegNet model outputting raw features without any specific head on top.""" , snake_case_ , ) class SCREAMING_SNAKE_CASE__ ( snake_case_): def __init__( self , A_ , *A_ , **A_ )-> List[Any]: '''simple docstring''' super().__init__(A_ , *A_ , **A_ ) UpperCamelCase = TFRegNetMainLayer(A_ , name='regnet' ) @unpack_inputs @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 UpperCAmelCase_ ( self , A_ , A_ = None , A_ = None , A_=False , )-> Union[TFBaseModelOutputWithPoolingAndNoAttention, Tuple[tf.Tensor]]: '''simple docstring''' UpperCamelCase = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) UpperCamelCase = return_dict if return_dict is not None else self.config.use_return_dict UpperCamelCase = self.regnet( pixel_values=A_ , output_hidden_states=A_ , return_dict=A_ , training=A_ , ) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=outputs.hidden_states , ) @add_start_docstrings( """ RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. """ , snake_case_ , ) class SCREAMING_SNAKE_CASE__ ( snake_case_ , snake_case_): def __init__( self , A_ , *A_ , **A_ )-> str: '''simple docstring''' super().__init__(A_ , *A_ , **A_ ) UpperCamelCase = config.num_labels UpperCamelCase = TFRegNetMainLayer(A_ , name='regnet' ) # classification head UpperCamelCase = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels , name='classifier.1' ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @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 UpperCAmelCase_ ( self , A_ = None , A_ = None , A_ = None , A_ = None , A_=False , )-> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]: '''simple docstring''' UpperCamelCase = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) UpperCamelCase = return_dict if return_dict is not None else self.config.use_return_dict UpperCamelCase = self.regnet( A_ , output_hidden_states=A_ , return_dict=A_ , training=A_ ) UpperCamelCase = outputs.pooler_output if return_dict else outputs[1] UpperCamelCase = self.classifier[0](A_ ) UpperCamelCase = self.classifier[1](A_ ) UpperCamelCase = None if labels is None else self.hf_compute_loss(labels=A_ , logits=A_ ) if not return_dict: UpperCamelCase = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=A_ , logits=A_ , hidden_states=outputs.hidden_states )
3
"""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
0
"""simple docstring""" import gc import unittest import numpy as np import torch from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS, CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class a ( a__ , unittest.TestCase ): snake_case__ = DiTPipeline snake_case__ = CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS snake_case__ = PipelineTesterMixin.required_optional_params - { '''latents''', '''num_images_per_prompt''', '''callback''', '''callback_steps''', } snake_case__ = CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS snake_case__ = False def UpperCamelCase__ ( self ): """simple docstring""" torch.manual_seed(0 ) lowerCAmelCase = TransformeraDModel( sample_size=16 , num_layers=2 , patch_size=4 , attention_head_dim=8 , num_attention_heads=2 , in_channels=4 , out_channels=8 , attention_bias=_snake_case , activation_fn='gelu-approximate' , num_embeds_ada_norm=10_00 , norm_type='ada_norm_zero' , norm_elementwise_affine=_snake_case , ) lowerCAmelCase = AutoencoderKL() lowerCAmelCase = DDIMScheduler() lowerCAmelCase = {'transformer': transformer.eval(), 'vae': vae.eval(), 'scheduler': scheduler} return components def UpperCamelCase__ ( self , _snake_case , _snake_case=0 ): """simple docstring""" if str(_snake_case ).startswith('mps' ): lowerCAmelCase = torch.manual_seed(_snake_case ) else: lowerCAmelCase = torch.Generator(device=_snake_case ).manual_seed(_snake_case ) lowerCAmelCase = { 'class_labels': [1], 'generator': generator, 'num_inference_steps': 2, 'output_type': 'numpy', } return inputs def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = 'cpu' lowerCAmelCase = self.get_dummy_components() lowerCAmelCase = self.pipeline_class(**_snake_case ) pipe.to(_snake_case ) pipe.set_progress_bar_config(disable=_snake_case ) lowerCAmelCase = self.get_dummy_inputs(_snake_case ) lowerCAmelCase = pipe(**_snake_case ).images lowerCAmelCase = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 16, 16, 3) ) lowerCAmelCase = np.array([0.2_946, 0.6_601, 0.4_329, 0.3_296, 0.4_144, 0.5_319, 0.7_273, 0.5_013, 0.4_457] ) lowerCAmelCase = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_snake_case , 1E-3 ) def UpperCamelCase__ ( self ): """simple docstring""" self._test_inference_batch_single_identical(relax_max_difference=_snake_case , expected_max_diff=1E-3 ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def UpperCamelCase__ ( self ): """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @require_torch_gpu @slow class a ( unittest.TestCase ): def UpperCamelCase__ ( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = torch.manual_seed(0 ) lowerCAmelCase = DiTPipeline.from_pretrained('facebook/DiT-XL-2-256' ) pipe.to('cuda' ) lowerCAmelCase = ['vase', 'umbrella', 'white shark', 'white wolf'] lowerCAmelCase = pipe.get_label_ids(_snake_case ) lowerCAmelCase = pipe(_snake_case , generator=_snake_case , num_inference_steps=40 , output_type='np' ).images for word, image in zip(_snake_case , _snake_case ): lowerCAmelCase = load_numpy( F'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy' ) assert np.abs((expected_image - image).max() ) < 1E-2 def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = DiTPipeline.from_pretrained('facebook/DiT-XL-2-512' ) lowerCAmelCase = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.to('cuda' ) lowerCAmelCase = ['vase', 'umbrella'] lowerCAmelCase = pipe.get_label_ids(_snake_case ) lowerCAmelCase = torch.manual_seed(0 ) lowerCAmelCase = pipe(_snake_case , generator=_snake_case , num_inference_steps=25 , output_type='np' ).images for word, image in zip(_snake_case , _snake_case ): lowerCAmelCase = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' F'/dit/{word}_512.npy' ) assert np.abs((expected_image - image).max() ) < 1E-1
4
"""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
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowercase = logging.get_logger(__name__) class UpperCAmelCase_ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): '''simple docstring''' _lowercase : Optional[Any] = '''maskformer-swin''' _lowercase : Union[str, Any] = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , _lowercase=224 , _lowercase=4 , _lowercase=3 , _lowercase=96 , _lowercase=[2, 2, 6, 2] , _lowercase=[3, 6, 12, 24] , _lowercase=7 , _lowercase=4.0 , _lowercase=True , _lowercase=0.0 , _lowercase=0.0 , _lowercase=0.1 , _lowercase="gelu" , _lowercase=False , _lowercase=0.02 , _lowercase=1e-5 , _lowercase=None , _lowercase=None , **_lowercase , ): """simple docstring""" super().__init__(**_lowercase ) _lowerCAmelCase = image_size _lowerCAmelCase = patch_size _lowerCAmelCase = num_channels _lowerCAmelCase = embed_dim _lowerCAmelCase = depths _lowerCAmelCase = len(_lowercase ) _lowerCAmelCase = num_heads _lowerCAmelCase = window_size _lowerCAmelCase = mlp_ratio _lowerCAmelCase = qkv_bias _lowerCAmelCase = hidden_dropout_prob _lowerCAmelCase = attention_probs_dropout_prob _lowerCAmelCase = drop_path_rate _lowerCAmelCase = hidden_act _lowerCAmelCase = use_absolute_embeddings _lowerCAmelCase = layer_norm_eps _lowerCAmelCase = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model _lowerCAmelCase = int(embed_dim * 2 ** (len(_lowercase ) - 1) ) _lowerCAmelCase = ["""stem"""] + [F'stage{idx}' for idx in range(1 , len(_lowercase ) + 1 )] _lowerCAmelCase , _lowerCAmelCase = get_aligned_output_features_output_indices( out_features=_lowercase , out_indices=_lowercase , stage_names=self.stage_names )
5
"""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
0
_lowerCamelCase = 8.31_4462 # Unit - J mol-1 K-1 def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): if moles < 0 or kelvin < 0 or volume < 0: raise ValueError("""Invalid inputs. Enter positive value.""" ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError("""Invalid inputs. Enter positive value.""" ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure if __name__ == "__main__": from doctest import testmod testmod()
6
"""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
0
"""simple docstring""" from math import cos, sin, sqrt, tau from audio_filters.iir_filter import IIRFilter def _snake_case ( _snake_case : int , _snake_case : int , _snake_case : float = 1 / sqrt(2 ) ) -> IIRFilter: '''simple docstring''' _A = tau * frequency / samplerate _A = sin(_snake_case ) _A = cos(_snake_case ) _A = _sin / (2 * q_factor) _A = (1 - _cos) / 2 _A = 1 - _cos _A = 1 + alpha _A = -2 * _cos _A = 1 - alpha _A = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _snake_case ( _snake_case : int , _snake_case : int , _snake_case : float = 1 / sqrt(2 ) ) -> IIRFilter: '''simple docstring''' _A = tau * frequency / samplerate _A = sin(_snake_case ) _A = cos(_snake_case ) _A = _sin / (2 * q_factor) _A = (1 + _cos) / 2 _A = -1 - _cos _A = 1 + alpha _A = -2 * _cos _A = 1 - alpha _A = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _snake_case ( _snake_case : int , _snake_case : int , _snake_case : float = 1 / sqrt(2 ) ) -> IIRFilter: '''simple docstring''' _A = tau * frequency / samplerate _A = sin(_snake_case ) _A = cos(_snake_case ) _A = _sin / (2 * q_factor) _A = _sin / 2 _A = 0 _A = -ba _A = 1 + alpha _A = -2 * _cos _A = 1 - alpha _A = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _snake_case ( _snake_case : int , _snake_case : int , _snake_case : float = 1 / sqrt(2 ) ) -> IIRFilter: '''simple docstring''' _A = tau * frequency / samplerate _A = sin(_snake_case ) _A = cos(_snake_case ) _A = _sin / (2 * q_factor) _A = 1 - alpha _A = -2 * _cos _A = 1 + alpha _A = IIRFilter(2 ) filt.set_coefficients([ba, ba, ba] , [ba, ba, ba] ) return filt def _snake_case ( _snake_case : int , _snake_case : int , _snake_case : float , _snake_case : float = 1 / sqrt(2 ) , ) -> IIRFilter: '''simple docstring''' _A = tau * frequency / samplerate _A = sin(_snake_case ) _A = cos(_snake_case ) _A = _sin / (2 * q_factor) _A = 10 ** (gain_db / 40) _A = 1 + alpha * big_a _A = -2 * _cos _A = 1 - alpha * big_a _A = 1 + alpha / big_a _A = -2 * _cos _A = 1 - alpha / big_a _A = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _snake_case ( _snake_case : int , _snake_case : int , _snake_case : float , _snake_case : float = 1 / sqrt(2 ) , ) -> IIRFilter: '''simple docstring''' _A = tau * frequency / samplerate _A = sin(_snake_case ) _A = cos(_snake_case ) _A = _sin / (2 * q_factor) _A = 10 ** (gain_db / 40) _A = (big_a + 1) - (big_a - 1) * _cos _A = (big_a + 1) + (big_a - 1) * _cos _A = (big_a - 1) - (big_a + 1) * _cos _A = (big_a - 1) + (big_a + 1) * _cos _A = 2 * sqrt(_snake_case ) * alpha _A = big_a * (pmc + aaa) _A = 2 * big_a * mpc _A = big_a * (pmc - aaa) _A = ppmc + aaa _A = -2 * pmpc _A = ppmc - aaa _A = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _snake_case ( _snake_case : int , _snake_case : int , _snake_case : float , _snake_case : float = 1 / sqrt(2 ) , ) -> IIRFilter: '''simple docstring''' _A = tau * frequency / samplerate _A = sin(_snake_case ) _A = cos(_snake_case ) _A = _sin / (2 * q_factor) _A = 10 ** (gain_db / 40) _A = (big_a + 1) - (big_a - 1) * _cos _A = (big_a + 1) + (big_a - 1) * _cos _A = (big_a - 1) - (big_a + 1) * _cos _A = (big_a - 1) + (big_a + 1) * _cos _A = 2 * sqrt(_snake_case ) * alpha _A = big_a * (ppmc + aaa) _A = -2 * big_a * pmpc _A = big_a * (ppmc - aaa) _A = pmc + aaa _A = 2 * mpc _A = pmc - aaa _A = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt
7
"""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
0
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer @dataclass class SCREAMING_SNAKE_CASE (a__ ): lowerCAmelCase = 42 class SCREAMING_SNAKE_CASE (a__ , a__ ): @register_to_config def __init__( self , _UpperCAmelCase = 3 , _UpperCAmelCase = 3 , _UpperCAmelCase = ("DownEncoderBlock2D",) , _UpperCAmelCase = ("UpDecoderBlock2D",) , _UpperCAmelCase = (64,) , _UpperCAmelCase = 1 , _UpperCAmelCase = "silu" , _UpperCAmelCase = 3 , _UpperCAmelCase = 32 , _UpperCAmelCase = 256 , _UpperCAmelCase = 32 , _UpperCAmelCase = None , _UpperCAmelCase = 0.18215 , _UpperCAmelCase = "group" , ): '''simple docstring''' super().__init__() # pass init params to Encoder __A : Optional[int] = Encoder( in_channels=_UpperCAmelCase , out_channels=_UpperCAmelCase , down_block_types=_UpperCAmelCase , block_out_channels=_UpperCAmelCase , layers_per_block=_UpperCAmelCase , act_fn=_UpperCAmelCase , norm_num_groups=_UpperCAmelCase , double_z=_UpperCAmelCase , ) __A : Dict = vq_embed_dim if vq_embed_dim is not None else latent_channels __A : Union[str, Any] = nn.Convad(_UpperCAmelCase , _UpperCAmelCase , 1) __A : List[Any] = VectorQuantizer(_UpperCAmelCase , _UpperCAmelCase , beta=0.25 , remap=_UpperCAmelCase , sane_index_shape=_UpperCAmelCase) __A : Dict = nn.Convad(_UpperCAmelCase , _UpperCAmelCase , 1) # pass init params to Decoder __A : Any = Decoder( in_channels=_UpperCAmelCase , out_channels=_UpperCAmelCase , up_block_types=_UpperCAmelCase , block_out_channels=_UpperCAmelCase , layers_per_block=_UpperCAmelCase , act_fn=_UpperCAmelCase , norm_num_groups=_UpperCAmelCase , norm_type=_UpperCAmelCase , ) @apply_forward_hook def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase = True): '''simple docstring''' __A : Optional[int] = self.encoder(_UpperCAmelCase) __A : str = self.quant_conv(_UpperCAmelCase) if not return_dict: return (h,) return VQEncoderOutput(latents=_UpperCAmelCase) @apply_forward_hook def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase = False , _UpperCAmelCase = True): '''simple docstring''' if not force_not_quantize: __A ,__A ,__A : Dict = self.quantize(_UpperCAmelCase) else: __A : int = h __A : List[Any] = self.post_quant_conv(_UpperCAmelCase) __A : Union[str, Any] = self.decoder(_UpperCAmelCase , quant if self.config.norm_type == 'spatial' else None) if not return_dict: return (dec,) return DecoderOutput(sample=_UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase = True): '''simple docstring''' __A : Any = sample __A : Optional[int] = self.encode(_UpperCAmelCase).latents __A : Union[str, Any] = self.decode(_UpperCAmelCase).sample if not return_dict: return (dec,) return DecoderOutput(sample=_UpperCAmelCase)
8
"""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
0
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class __lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Any , _snake_case : Optional[int] , _snake_case : Any=7 , _snake_case : int=3 , _snake_case : Tuple=18 , _snake_case : Tuple=30 , _snake_case : Tuple=4_00 , _snake_case : List[str]=True , _snake_case : str=None , _snake_case : int=True , _snake_case : Tuple=None , _snake_case : Tuple=True , _snake_case : Optional[int]=[0.5, 0.5, 0.5] , _snake_case : Any=[0.5, 0.5, 0.5] , ): """simple docstring""" A__ = size if size is not None else {'shortest_edge': 18} A__ = crop_size if crop_size is not None else {'height': 18, 'width': 18} A__ = parent A__ = batch_size A__ = num_channels A__ = image_size A__ = min_resolution A__ = max_resolution A__ = do_resize A__ = size A__ = do_center_crop A__ = crop_size A__ = do_normalize A__ = image_mean A__ = image_std def _a ( self : Any ): """simple docstring""" return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "do_center_crop": self.do_center_crop, "size": self.size, "crop_size": self.crop_size, } @require_torch @require_vision class __lowerCAmelCase ( UpperCAmelCase_ , unittest.TestCase ): """simple docstring""" A__ : Dict = LevitImageProcessor if is_vision_available() else None def _a ( self : str ): """simple docstring""" A__ = LevitImageProcessingTester(self ) @property def _a ( self : int ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def _a ( self : Optional[int] ): """simple docstring""" A__ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_snake_case , 'image_mean' ) ) self.assertTrue(hasattr(_snake_case , 'image_std' ) ) self.assertTrue(hasattr(_snake_case , 'do_normalize' ) ) self.assertTrue(hasattr(_snake_case , 'do_resize' ) ) self.assertTrue(hasattr(_snake_case , 'do_center_crop' ) ) self.assertTrue(hasattr(_snake_case , 'size' ) ) def _a ( self : int ): """simple docstring""" A__ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18} ) self.assertEqual(image_processor.crop_size , {'height': 18, 'width': 18} ) A__ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {'shortest_edge': 42} ) self.assertEqual(image_processor.crop_size , {'height': 84, 'width': 84} ) def _a ( self : str ): """simple docstring""" pass def _a ( self : Tuple ): """simple docstring""" A__ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images A__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_snake_case ) for image in image_inputs: self.assertIsInstance(_snake_case , Image.Image ) # Test not batched input A__ = 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 A__ = image_processing(_snake_case , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def _a ( self : Dict ): """simple docstring""" A__ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors A__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_snake_case , numpify=_snake_case ) for image in image_inputs: self.assertIsInstance(_snake_case , np.ndarray ) # Test not batched input A__ = 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 A__ = image_processing(_snake_case , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def _a ( self : Any ): """simple docstring""" A__ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors A__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_snake_case , torchify=_snake_case ) for image in image_inputs: self.assertIsInstance(_snake_case , torch.Tensor ) # Test not batched input A__ = 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 A__ = image_processing(_snake_case , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , )
9
"""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
0
from __future__ import annotations def _snake_case ( __snake_case , __snake_case = None ): _UpperCamelCase = word_bank or [] # create a table _UpperCamelCase = len(__snake_case ) + 1 _UpperCamelCase = [] for _ in range(__snake_case ): table.append([] ) # seed value _UpperCamelCase = [[]] # because empty string has empty combination # iterate through the indices for i in range(__snake_case ): # condition if table[i] != []: for word in word_bank: # slice condition if target[i : i + len(__snake_case )] == word: _UpperCamelCase = [ [word, *way] for way in table[i] ] # adds the word to every combination the current position holds # now,push that combination to the table[i+len(word)] table[i + len(__snake_case )] += new_combinations # combinations are in reverse order so reverse for better output for combination in table[len(__snake_case )]: combination.reverse() return table[len(__snake_case )] if __name__ == "__main__": print(all_construct("jwajalapa", ["jwa", "j", "w", "a", "la", "lapa"])) print(all_construct("rajamati", ["s", "raj", "amat", "raja", "ma", "i", "t"])) print( all_construct( "hexagonosaurus", ["h", "ex", "hex", "ag", "ago", "ru", "auru", "rus", "go", "no", "o", "s"], ) )
10
"""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
0
'''simple docstring''' import argparse import math import os import torch from neural_compressor.utils.pytorch import load from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, StableDiffusionPipeline, UNetaDConditionModel def lowerCAmelCase (): """simple docstring""" _a = argparse.ArgumentParser() parser.add_argument( '''-m''' , '''--pretrained_model_name_or_path''' , type=__A , default=__A , required=__A , help='''Path to pretrained model or model identifier from huggingface.co/models.''' , ) parser.add_argument( '''-c''' , '''--caption''' , type=__A , default='''robotic cat with wings''' , help='''Text used to generate images.''' , ) parser.add_argument( '''-n''' , '''--images_num''' , type=__A , default=4 , help='''How much images to generate.''' , ) parser.add_argument( '''-s''' , '''--seed''' , type=__A , default=42 , help='''Seed for random process.''' , ) parser.add_argument( '''-ci''' , '''--cuda_id''' , type=__A , default=0 , help='''cuda_id.''' , ) _a = parser.parse_args() return args def lowerCAmelCase (__A , __A , __A): """simple docstring""" if not len(__A) == rows * cols: raise ValueError('''The specified number of rows and columns are not correct.''') _a , _a = imgs[0].size _a = Image.new('''RGB''' , size=(cols * w, rows * h)) _a , _a = grid.size for i, img in enumerate(__A): grid.paste(__A , box=(i % cols * w, i // cols * h)) return grid def lowerCAmelCase (__A , __A="robotic cat with wings" , __A=7.5 , __A=50 , __A=1 , __A=42 , ): """simple docstring""" _a = torch.Generator(pipeline.device).manual_seed(__A) _a = pipeline( __A , guidance_scale=__A , num_inference_steps=__A , generator=__A , num_images_per_prompt=__A , ).images _a = int(math.sqrt(__A)) _a = image_grid(__A , rows=_rows , cols=num_images_per_prompt // _rows) return grid, images lowercase_ = parse_args() # Load models and create wrapper for stable diffusion lowercase_ = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer") lowercase_ = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="text_encoder") lowercase_ = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae") lowercase_ = UNetaDConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="unet") lowercase_ = StableDiffusionPipeline.from_pretrained( args.pretrained_model_name_or_path, text_encoder=text_encoder, vae=vae, unet=unet, tokenizer=tokenizer ) lowercase_ = lambda images, clip_input: (images, False) if os.path.exists(os.path.join(args.pretrained_model_name_or_path, "best_model.pt")): lowercase_ = load(args.pretrained_model_name_or_path, model=unet) unet.eval() setattr(pipeline, "unet", unet) else: lowercase_ = unet.to(torch.device("cuda", args.cuda_id)) lowercase_ = pipeline.to(unet.device) lowercase_ , lowercase_ = generate_images(pipeline, prompt=args.caption, num_images_per_prompt=args.images_num, seed=args.seed) grid.save(os.path.join(args.pretrained_model_name_or_path, "{}.png".format("_".join(args.caption.split())))) lowercase_ = os.path.join(args.pretrained_model_name_or_path, "_".join(args.caption.split())) os.makedirs(dirname, exist_ok=True) for idx, image in enumerate(images): image.save(os.path.join(dirname, "{}.png".format(idx + 1)))
11
"""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
0
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pathlib import Path import torch from ...utils import is_npu_available, is_xpu_available from .config_args import ClusterConfig, default_json_config_file from .config_utils import SubcommandHelpFormatter lowerCamelCase__ : Any = """Create a default config file for Accelerate with only a few flags set.""" def UpperCamelCase ( lowercase_="no" , lowercase_ = default_json_config_file , lowercase_ = False ) -> Any: '''simple docstring''' lowercase__ : Any = Path(lowercase_ ) path.parent.mkdir(parents=lowercase_ , exist_ok=lowercase_ ) if path.exists(): print( F'Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.' ) return False lowercase__ : int = mixed_precision.lower() if mixed_precision not in ["no", "fp16", "bf16", "fp8"]: raise ValueError( F'`mixed_precision` should be one of \'no\', \'fp16\', \'bf16\', or \'fp8\'. Received {mixed_precision}' ) lowercase__ : Dict = { """compute_environment""": """LOCAL_MACHINE""", """mixed_precision""": mixed_precision, } if torch.cuda.is_available(): lowercase__ : Any = torch.cuda.device_count() lowercase__ : Any = num_gpus lowercase__ : Optional[int] = False if num_gpus > 1: lowercase__ : Tuple = """MULTI_GPU""" else: lowercase__ : Optional[Any] = """NO""" elif is_xpu_available() and use_xpu: lowercase__ : Union[str, Any] = torch.xpu.device_count() lowercase__ : str = num_xpus lowercase__ : List[Any] = False if num_xpus > 1: lowercase__ : str = """MULTI_XPU""" else: lowercase__ : Optional[Any] = """NO""" elif is_npu_available(): lowercase__ : Tuple = torch.npu.device_count() lowercase__ : Union[str, Any] = num_npus lowercase__ : Union[str, Any] = False if num_npus > 1: lowercase__ : List[Any] = """MULTI_NPU""" else: lowercase__ : int = """NO""" else: lowercase__ : Union[str, Any] = 0 lowercase__ : str = True lowercase__ : Union[str, Any] = 1 lowercase__ : int = """NO""" lowercase__ : Tuple = ClusterConfig(**lowercase_ ) config.to_json_file(lowercase_ ) return path def UpperCamelCase ( lowercase_ , lowercase_ ) -> Optional[Any]: '''simple docstring''' lowercase__ : List[str] = parser.add_parser("""default""" , parents=lowercase_ , help=lowercase_ , formatter_class=lowercase_ ) parser.add_argument( """--config_file""" , default=lowercase_ , help=( """The path to use to store the config file. Will default to a file named default_config.yaml in the cache """ """location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have """ """such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed """ """with 'huggingface'.""" ) , dest="""save_location""" , ) parser.add_argument( """--mixed_precision""" , choices=["""no""", """fp16""", """bf16"""] , type=lowercase_ , help="""Whether or not to use mixed precision training. """ """Choose between FP16 and BF16 (bfloat16) training. """ """BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.""" , default="""no""" , ) parser.set_defaults(func=lowercase_ ) return parser def UpperCamelCase ( lowercase_ ) -> Any: '''simple docstring''' lowercase__ : Optional[Any] = write_basic_config(args.mixed_precision , args.save_location ) if config_file: print(F'accelerate configuration saved at {config_file}' )
12
"""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
0
'''simple docstring''' import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import datasets import numpy as np import tensorflow as tf from transformers import ( AutoConfig, AutoTokenizer, EvalPrediction, HfArgumentParser, PreTrainedTokenizer, TFAutoModelForSequenceClassification, TFTrainer, TFTrainingArguments, ) from transformers.utils import logging as hf_logging hf_logging.set_verbosity_info() hf_logging.enable_default_handler() hf_logging.enable_explicit_format() def UpperCAmelCase__ ( UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : PreTrainedTokenizer , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int] = None , ) -> Tuple: __lowerCamelCase : Any = {} if train_file is not None: __lowerCamelCase : int = [train_file] if eval_file is not None: __lowerCamelCase : Any = [eval_file] if test_file is not None: __lowerCamelCase : Any = [test_file] __lowerCamelCase : Any = datasets.load_dataset('csv' , data_files=UpperCAmelCase_ ) __lowerCamelCase : Dict = list(ds[list(files.keys() )[0]].features.keys() ) __lowerCamelCase : Union[str, Any] = features_name.pop(UpperCAmelCase_ ) __lowerCamelCase : Optional[Any] = list(set(ds[list(files.keys() )[0]][label_name] ) ) __lowerCamelCase : Union[str, Any] = {label: i for i, label in enumerate(UpperCAmelCase_ )} __lowerCamelCase : Optional[Any] = tokenizer.model_input_names __lowerCamelCase : Optional[int] = {} if len(UpperCAmelCase_ ) == 1: for k in files.keys(): __lowerCamelCase : str = ds[k].map( lambda UpperCAmelCase_ : tokenizer.batch_encode_plus( example[features_name[0]] , truncation=UpperCAmelCase_ , max_length=UpperCAmelCase_ , padding='max_length' ) , batched=UpperCAmelCase_ , ) elif len(UpperCAmelCase_ ) == 2: for k in files.keys(): __lowerCamelCase : Union[str, Any] = ds[k].map( lambda UpperCAmelCase_ : tokenizer.batch_encode_plus( (example[features_name[0]], example[features_name[1]]) , truncation=UpperCAmelCase_ , max_length=UpperCAmelCase_ , padding='max_length' , ) , batched=UpperCAmelCase_ , ) def gen_train(): for ex in transformed_ds[datasets.Split.TRAIN]: __lowerCamelCase : Any = {k: v for k, v in ex.items() if k in input_names} __lowerCamelCase : Dict = labelaid[ex[label_name]] yield (d, label) def gen_val(): for ex in transformed_ds[datasets.Split.VALIDATION]: __lowerCamelCase : List[Any] = {k: v for k, v in ex.items() if k in input_names} __lowerCamelCase : int = labelaid[ex[label_name]] yield (d, label) def gen_test(): for ex in transformed_ds[datasets.Split.TEST]: __lowerCamelCase : Optional[int] = {k: v for k, v in ex.items() if k in input_names} __lowerCamelCase : List[str] = labelaid[ex[label_name]] yield (d, label) __lowerCamelCase : List[Any] = ( tf.data.Dataset.from_generator( UpperCAmelCase_ , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )) , ) if datasets.Split.TRAIN in transformed_ds else None ) if train_ds is not None: __lowerCamelCase : Optional[Any] = train_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TRAIN] ) ) ) __lowerCamelCase : Union[str, Any] = ( tf.data.Dataset.from_generator( UpperCAmelCase_ , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )) , ) if datasets.Split.VALIDATION in transformed_ds else None ) if val_ds is not None: __lowerCamelCase : Optional[int] = val_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.VALIDATION] ) ) ) __lowerCamelCase : List[Any] = ( tf.data.Dataset.from_generator( UpperCAmelCase_ , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )) , ) if datasets.Split.TEST in transformed_ds else None ) if test_ds is not None: __lowerCamelCase : List[str] = test_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TEST] ) ) ) return train_ds, val_ds, test_ds, labelaid A__ : int = logging.getLogger(__name__) @dataclass class UpperCAmelCase_ : """simple docstring""" lowerCamelCase : int = field(metadata={'help': 'Which column contains the label'} ) lowerCamelCase : str = field(default=_UpperCAmelCase , metadata={'help': 'The path of the training file'} ) lowerCamelCase : Optional[str] = field(default=_UpperCAmelCase , metadata={'help': 'The path of the development file'} ) lowerCamelCase : Optional[str] = field(default=_UpperCAmelCase , metadata={'help': 'The path of the test file'} ) lowerCamelCase : int = field( default=1_2_8 , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) lowerCamelCase : bool = field( default=_UpperCAmelCase , metadata={'help': 'Overwrite the cached training and evaluation sets'} ) @dataclass class UpperCAmelCase_ : """simple docstring""" lowerCamelCase : str = field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} ) lowerCamelCase : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) lowerCamelCase : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) lowerCamelCase : bool = field(default=_UpperCAmelCase , metadata={'help': 'Set this flag to use fast tokenization.'} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. lowerCamelCase : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) def UpperCAmelCase__ ( ) -> str: # 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. __lowerCamelCase : int = HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments) ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. Use' ' --overwrite_output_dir to overcome.' ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , level=logging.INFO , ) logger.info( F'n_replicas: {training_args.n_replicas}, distributed training: {bool(training_args.n_replicas > 1 )}, ' F'16-bits training: {training_args.fpaa}' ) logger.info(F'Training/evaluation parameters {training_args}' ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __lowerCamelCase : Optional[Any] = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : int = get_tfds( train_file=data_args.train_file , eval_file=data_args.dev_file , test_file=data_args.test_file , tokenizer=UpperCAmelCase_ , label_column_id=data_args.label_column_id , max_seq_length=data_args.max_seq_length , ) __lowerCamelCase : Any = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=len(UpperCAmelCase_ ) , labelaid=UpperCAmelCase_ , idalabel={id: label for label, id in labelaid.items()} , finetuning_task='text-classification' , cache_dir=model_args.cache_dir , ) with training_args.strategy.scope(): __lowerCamelCase : Optional[int] = TFAutoModelForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_pt=bool('.bin' in model_args.model_name_or_path ) , config=UpperCAmelCase_ , cache_dir=model_args.cache_dir , ) def compute_metrics(UpperCAmelCase_ : EvalPrediction ) -> Dict: __lowerCamelCase : Any = np.argmax(p.predictions , axis=1 ) return {"acc": (preds == p.label_ids).mean()} # Initialize our Trainer __lowerCamelCase : int = TFTrainer( model=UpperCAmelCase_ , args=UpperCAmelCase_ , train_dataset=UpperCAmelCase_ , eval_dataset=UpperCAmelCase_ , compute_metrics=UpperCAmelCase_ , ) # Training if training_args.do_train: trainer.train() trainer.save_model() tokenizer.save_pretrained(training_args.output_dir ) # Evaluation __lowerCamelCase : Optional[Any] = {} if training_args.do_eval: logger.info('*** Evaluate ***' ) __lowerCamelCase : List[str] = trainer.evaluate() __lowerCamelCase : Optional[Any] = os.path.join(training_args.output_dir , 'eval_results.txt' ) with open(UpperCAmelCase_ , 'w' ) as writer: logger.info('***** Eval results *****' ) for key, value in result.items(): logger.info(F' {key} = {value}' ) writer.write(F'{key} = {value}\n' ) results.update(UpperCAmelCase_ ) return results if __name__ == "__main__": main()
13
"""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
0
from __future__ import annotations import unittest from transformers import LEDConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFLEDForConditionalGeneration, TFLEDModel @require_tf class UpperCAmelCase_ : """simple docstring""" UpperCAmelCase__ : Optional[int] = LEDConfig UpperCAmelCase__ : Union[str, Any] = {} UpperCAmelCase__ : Dict = "gelu" def __init__( self , _a , _a=1_3 , _a=7 , _a=True , _a=False , _a=9_9 , _a=3_2 , _a=2 , _a=4 , _a=3_7 , _a=0.1 , _a=0.1 , _a=2_0 , _a=2 , _a=1 , _a=0 , _a=4 , ) -> Dict: _a : Optional[Any] = parent _a : str = batch_size _a : Dict = seq_length _a : Any = is_training _a : Any = use_labels _a : List[Any] = vocab_size _a : Tuple = hidden_size _a : Dict = num_hidden_layers _a : str = num_attention_heads _a : List[Any] = intermediate_size _a : Any = hidden_dropout_prob _a : Any = attention_probs_dropout_prob _a : Tuple = max_position_embeddings _a : List[str] = eos_token_id _a : Any = pad_token_id _a : int = bos_token_id _a : Any = attention_window # `ModelTesterMixin.test_attention_outputs` is expecting attention tensors to be of size # [num_attention_heads, encoder_seq_length, encoder_key_length], but TFLongformerSelfAttention # returns attention of shape [num_attention_heads, encoder_seq_length, self.attention_window + 1] # because its local attention only attends to `self.attention_window` and one before and one after _a : Dict = self.attention_window + 2 # because of padding `encoder_seq_length`, is different from `seq_length`. Relevant for # the `test_attention_outputs` and `test_hidden_states_output` tests _a : Tuple = ( self.seq_length + (self.attention_window - self.seq_length % self.attention_window) % self.attention_window ) def __lowercase ( self ) -> Optional[Any]: _a : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) _a : Optional[int] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) _a : Optional[Any] = tf.concat([input_ids, eos_tensor] , axis=1 ) _a : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a : Dict = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , attention_window=self.attention_window , **self.config_updates , ) _a : Optional[int] = prepare_led_inputs_dict(_a , _a , _a ) _a : int = tf.concat( [tf.zeros_like(_a )[:, :-1], tf.ones_like(_a )[:, -1:]] , axis=-1 , ) _a : str = global_attention_mask return config, inputs_dict def __lowercase ( self , _a , _a ) -> Any: _a : Dict = TFLEDModel(config=_a ).get_decoder() _a : Any = inputs_dict['''input_ids'''] _a : str = input_ids[:1, :] _a : Optional[int] = inputs_dict['''attention_mask'''][:1, :] _a : Optional[Any] = 1 # first forward pass _a : int = model(_a , attention_mask=_a , use_cache=_a ) _a , _a : Dict = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids _a : Tuple = ids_tensor((self.batch_size, 3) , config.vocab_size ) _a : int = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and _a : List[str] = tf.concat([input_ids, next_tokens] , axis=-1 ) _a : Any = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) _a : int = model(_a , attention_mask=_a )[0] _a : Optional[Any] = model(_a , attention_mask=_a , past_key_values=_a )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice _a : str = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) _a : List[str] = output_from_no_past[:, -3:, random_slice_idx] _a : Tuple = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(_a , _a , rtol=1e-3 ) def __UpperCAmelCase ( __a : int ,__a : str ,__a : Optional[Any] ,__a : Optional[int]=None ,__a : Optional[int]=None ,__a : Dict=None ,__a : List[Any]=None ,) -> str: """simple docstring""" if attention_mask is None: _a : Optional[int] = tf.cast(tf.math.not_equal(__a ,config.pad_token_id ) ,tf.inta ) if decoder_attention_mask is None: _a : List[Any] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape ,dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] ,config.pad_token_id ) ,tf.inta ), ] ,axis=-1 ,) if head_mask is None: _a : List[Any] = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: _a : Optional[Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, } @require_tf class UpperCAmelCase_ ( __lowercase , __lowercase , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Union[str, Any] = (TFLEDForConditionalGeneration, TFLEDModel) if is_tf_available() else () UpperCAmelCase__ : Optional[int] = (TFLEDForConditionalGeneration,) if is_tf_available() else () UpperCAmelCase__ : List[Any] = ( { "conversational": TFLEDForConditionalGeneration, "feature-extraction": TFLEDModel, "summarization": TFLEDForConditionalGeneration, "text2text-generation": TFLEDForConditionalGeneration, "translation": TFLEDForConditionalGeneration, } if is_tf_available() else {} ) UpperCAmelCase__ : str = True UpperCAmelCase__ : Dict = False UpperCAmelCase__ : Optional[Any] = False UpperCAmelCase__ : Dict = False def __lowercase ( self ) -> Optional[Any]: _a : Dict = TFLEDModelTester(self ) _a : Any = ConfigTester(self , config_class=_a ) def __lowercase ( self ) -> Union[str, Any]: self.config_tester.run_common_tests() def __lowercase ( self ) -> int: _a : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*_a ) def __lowercase ( self ) -> str: _a , _a : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() _a : int = tf.zeros_like(inputs_dict['''attention_mask'''] ) _a : Tuple = 2 _a : Optional[Any] = tf.where( tf.range(self.model_tester.seq_length )[None, :] < num_global_attn_indices , 1 , inputs_dict['''global_attention_mask'''] , ) _a : Tuple = True _a : Union[str, Any] = self.model_tester.seq_length _a : Dict = self.model_tester.encoder_seq_length def check_decoder_attentions_output(_a ): _a : List[str] = outputs.decoder_attentions self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) def check_encoder_attentions_output(_a ): _a : Optional[int] = [t.numpy() for t in outputs.encoder_attentions] _a : Optional[Any] = [t.numpy() for t in outputs.encoder_global_attentions] self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) self.assertListEqual( list(global_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, num_global_attn_indices] , ) for model_class in self.all_model_classes: _a : List[Any] = True _a : str = False _a : Any = False _a : List[Any] = model_class(_a ) _a : Union[str, Any] = model(self._prepare_for_class(_a , _a ) ) _a : Any = len(_a ) self.assertEqual(config.output_hidden_states , _a ) check_encoder_attentions_output(_a ) if self.is_encoder_decoder: _a : str = model_class(_a ) _a : Dict = model(self._prepare_for_class(_a , _a ) ) self.assertEqual(config.output_hidden_states , _a ) check_decoder_attentions_output(_a ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] _a : Union[str, Any] = True _a : Tuple = model_class(_a ) _a : Optional[Any] = model(self._prepare_for_class(_a , _a ) ) self.assertEqual(config.output_hidden_states , _a ) check_encoder_attentions_output(_a ) # Check attention is always last and order is fine _a : Tuple = True _a : Dict = True _a : Union[str, Any] = model_class(_a ) _a : Optional[Any] = model(self._prepare_for_class(_a , _a ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(_a ) ) self.assertEqual(model.config.output_hidden_states , _a ) check_encoder_attentions_output(_a ) @unittest.skip('''LED keeps using potentially symbolic tensors in conditionals and breaks tracing.''' ) def __lowercase ( self ) -> Union[str, Any]: pass def __lowercase ( self ) -> List[str]: # TODO: Head-masking not yet implement pass def __UpperCAmelCase ( __a : Tuple ) -> Any: """simple docstring""" return tf.constant(__a ,dtype=tf.intaa ) a__ = 1E-4 @slow @require_tf class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self ) -> List[Any]: _a : Dict = TFLEDForConditionalGeneration.from_pretrained('''allenai/led-base-16384''' ).led # change to intended input here _a : str = _long_tensor([5_1_2 * [0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9]] ) _a : Tuple = _long_tensor([1_2_8 * [0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9]] ) _a : Any = prepare_led_inputs_dict(model.config , _a , _a ) _a : Optional[int] = model(**_a )[0] _a : str = (1, 1_0_2_4, 7_6_8) self.assertEqual(output.shape , _a ) # change to expected output here _a : str = tf.convert_to_tensor( [[2.3050, 2.8279, 0.6531], [-1.8457, -0.1455, -3.5661], [-1.0186, 0.4586, -2.2043]] , ) tf.debugging.assert_near(output[:, :3, :3] , _a , atol=1e-3 ) def __lowercase ( self ) -> str: _a : Any = TFLEDForConditionalGeneration.from_pretrained('''allenai/led-base-16384''' ) # change to intended input here _a : List[str] = _long_tensor([5_1_2 * [0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9]] ) _a : Dict = _long_tensor([1_2_8 * [0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9]] ) _a : Union[str, Any] = prepare_led_inputs_dict(model.config , _a , _a ) _a : Union[str, Any] = model(**_a )[0] _a : Optional[int] = (1, 1_0_2_4, model.config.vocab_size) self.assertEqual(output.shape , _a ) # change to expected output here _a : List[str] = tf.convert_to_tensor( [[33.6507, 6.4572, 16.8089], [5.8739, -2.4238, 11.2902], [-3.2139, -4.3149, 4.2783]] , ) tf.debugging.assert_near(output[:, :3, :3] , _a , atol=1e-3 , rtol=1e-3 )
14
"""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
0
import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments A : Optional[int] = logging.getLogger(__name__) @dataclass class A ( UpperCAmelCase__ ): '''simple docstring''' A__ = field( default=0.0 , metadata={'''help''': '''The label smoothing epsilon to apply (if not zero).'''} ) A__ = field(default=UpperCAmelCase__ , metadata={'''help''': '''Whether to SortishSamler or not.'''} ) A__ = field( default=UpperCAmelCase__ , metadata={'''help''': '''Whether to use generate to calculate generative metrics (ROUGE, BLEU).'''} ) A__ = field(default=UpperCAmelCase__ , metadata={'''help''': '''whether to use adafactor'''} ) A__ = field( default=UpperCAmelCase__ , metadata={'''help''': '''Encoder layer dropout probability. Goes into model.config.'''} ) A__ = field( default=UpperCAmelCase__ , metadata={'''help''': '''Decoder layer dropout probability. Goes into model.config.'''} ) A__ = field(default=UpperCAmelCase__ , metadata={'''help''': '''Dropout probability. Goes into model.config.'''} ) A__ = field( default=UpperCAmelCase__ , metadata={'''help''': '''Attention dropout probability. Goes into model.config.'''} ) A__ = field( default='''linear''' , metadata={'''help''': F"""Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}"""} , )
15
"""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
0
from __future__ import annotations import copy import tempfile import unittest from transformers import CONFIG_MAPPING, AutoConfig, BertConfig, GPTaConfig, TaConfig, TapasConfig, is_tf_available from transformers.testing_utils import ( DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, require_tensorflow_probability, require_tf, slow, ) from ..bert.test_modeling_bert import BertModelTester if is_tf_available(): from transformers import ( TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelForTableQuestionAnswering, TFAutoModelForTokenClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFFunnelBaseModel, TFFunnelModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, TFTapasForQuestionAnswering, ) from transformers.models.auto.modeling_tf_auto import ( TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_MAPPING, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.tapas.modeling_tf_tapas import TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = "new-model" if is_tf_available(): class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = NewModelConfig @require_tf class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @slow def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = "bert-base-cased" SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) @slow def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE = "bert-base-cased" SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = TFAutoModelForPreTraining.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) @slow def _snake_case ( self : int ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = TFAutoModelForCausalLM.from_pretrained(__lowerCamelCase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = TFAutoModelForCausalLM.from_pretrained(__lowerCamelCase , output_loading_info=__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) @slow def _snake_case ( self : Tuple ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = TFAutoModelWithLMHead.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) @slow def _snake_case ( self : int ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = TFAutoModelForMaskedLM.from_pretrained(__lowerCamelCase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = TFAutoModelForMaskedLM.from_pretrained(__lowerCamelCase , output_loading_info=__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) @slow def _snake_case ( self : List[str] ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = TFAutoModelForSeqaSeqLM.from_pretrained(__lowerCamelCase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = TFAutoModelForSeqaSeqLM.from_pretrained(__lowerCamelCase , output_loading_info=__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) @slow def _snake_case ( self : Optional[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = TFAutoModelForSequenceClassification.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) @slow def _snake_case ( self : Tuple ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = TFAutoModelForQuestionAnswering.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) @slow @require_tensorflow_probability def _snake_case ( self : Union[str, Any] ): for model_name in TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST[5:6]: SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = TFAutoModelForTableQuestionAnswering.from_pretrained(__lowerCamelCase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = TFAutoModelForTableQuestionAnswering.from_pretrained( __lowerCamelCase , output_loading_info=__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) def _snake_case ( self : List[Any] ): SCREAMING_SNAKE_CASE = TFAutoModelWithLMHead.from_pretrained(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) self.assertEqual(model.num_parameters() , 14410 ) self.assertEqual(model.num_parameters(only_trainable=__lowerCamelCase ) , 14410 ) def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE = TFAutoModelWithLMHead.from_pretrained(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) self.assertEqual(model.num_parameters() , 14410 ) self.assertEqual(model.num_parameters(only_trainable=__lowerCamelCase ) , 14410 ) def _snake_case ( self : List[Any] ): # For the auto model mapping, FunnelConfig has two models: FunnelModel and FunnelBaseModel SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained("sgugger/funnel-random-tiny" ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = copy.deepcopy(model.config ) SCREAMING_SNAKE_CASE = ["FunnelBaseModel"] SCREAMING_SNAKE_CASE = TFAutoModel.from_config(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(__lowerCamelCase ) SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) def _snake_case ( self : List[Any] ): try: AutoConfig.register("new-model" , __lowerCamelCase ) SCREAMING_SNAKE_CASE = [ TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSequenceClassification, TFAutoModelForTokenClassification, ] for auto_class in auto_classes: with self.subTest(auto_class.__name__ ): # Wrong config class will raise an error with self.assertRaises(__lowerCamelCase ): auto_class.register(__lowerCamelCase , __lowerCamelCase ) auto_class.register(__lowerCamelCase , __lowerCamelCase ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(__lowerCamelCase ): auto_class.register(__lowerCamelCase , __lowerCamelCase ) # Now that the config is registered, it can be used as any other config with the auto-API SCREAMING_SNAKE_CASE = BertModelTester(self ).get_config() SCREAMING_SNAKE_CASE = NewModelConfig(**tiny_config.to_dict() ) SCREAMING_SNAKE_CASE = auto_class.from_config(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(__lowerCamelCase ) SCREAMING_SNAKE_CASE = auto_class.from_pretrained(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) finally: if "new-model" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["new-model"] for mapping in ( TF_MODEL_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, ): if NewModelConfig in mapping._extra_content: del mapping._extra_content[NewModelConfig] def _snake_case ( self : Optional[int] ): with self.assertRaisesRegex( __lowerCamelCase , "bert-base is not a local folder and is not a valid model identifier" ): SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained("bert-base" ) def _snake_case ( self : Any ): with self.assertRaisesRegex( __lowerCamelCase , r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ): SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained(__lowerCamelCase , revision="aaaaaa" ) def _snake_case ( self : str ): with self.assertRaisesRegex( __lowerCamelCase , "hf-internal-testing/config-no-model does not appear to have a file named pytorch_model.bin" , ): SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained("hf-internal-testing/config-no-model" ) def _snake_case ( self : Tuple ): with self.assertRaisesRegex(__lowerCamelCase , "Use `from_pt=True` to load this model" ): SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained("hf-internal-testing/tiny-bert-pt-only" ) def _snake_case ( self : int ): # Make sure we have cached the model. SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained("hf-internal-testing/tiny-random-bert" ) with RequestCounter() as counter: SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained("hf-internal-testing/tiny-random-bert" ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 ) # With a sharded checkpoint SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained("ArthurZ/tiny-random-bert-sharded" ) with RequestCounter() as counter: SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained("ArthurZ/tiny-random-bert-sharded" ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 )
16
"""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
0
import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer from ...utils import logging UpperCAmelCase_ : Dict = logging.get_logger(__name__) UpperCAmelCase_ : Dict = '''▁''' UpperCAmelCase_ : List[str] = { '''vocab_file''': '''vocab.json''', '''spm_file''': '''sentencepiece.bpe.model''', '''tokenizer_config_file''': '''tokenizer_config.json''', } UpperCAmelCase_ : Dict = { '''vocab_file''': { '''facebook/m2m100_418M''': '''https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json''', '''facebook/m2m100_1.2B''': '''https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json''', }, '''spm_file''': { '''facebook/m2m100_418M''': '''https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model''', '''facebook/m2m100_1.2B''': '''https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model''', }, '''tokenizer_config_file''': { '''facebook/m2m100_418M''': '''https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json''', '''facebook/m2m100_1.2B''': '''https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json''', }, } UpperCAmelCase_ : Optional[Any] = { '''facebook/m2m100_418M''': 1_024, } # fmt: off UpperCAmelCase_ : List[Any] = { '''m2m100''': ['''af''', '''am''', '''ar''', '''ast''', '''az''', '''ba''', '''be''', '''bg''', '''bn''', '''br''', '''bs''', '''ca''', '''ceb''', '''cs''', '''cy''', '''da''', '''de''', '''el''', '''en''', '''es''', '''et''', '''fa''', '''ff''', '''fi''', '''fr''', '''fy''', '''ga''', '''gd''', '''gl''', '''gu''', '''ha''', '''he''', '''hi''', '''hr''', '''ht''', '''hu''', '''hy''', '''id''', '''ig''', '''ilo''', '''is''', '''it''', '''ja''', '''jv''', '''ka''', '''kk''', '''km''', '''kn''', '''ko''', '''lb''', '''lg''', '''ln''', '''lo''', '''lt''', '''lv''', '''mg''', '''mk''', '''ml''', '''mn''', '''mr''', '''ms''', '''my''', '''ne''', '''nl''', '''no''', '''ns''', '''oc''', '''or''', '''pa''', '''pl''', '''ps''', '''pt''', '''ro''', '''ru''', '''sd''', '''si''', '''sk''', '''sl''', '''so''', '''sq''', '''sr''', '''ss''', '''su''', '''sv''', '''sw''', '''ta''', '''th''', '''tl''', '''tn''', '''tr''', '''uk''', '''ur''', '''uz''', '''vi''', '''wo''', '''xh''', '''yi''', '''yo''', '''zh''', '''zu'''], '''wmt21''': ['''en''', '''ha''', '''is''', '''ja''', '''cs''', '''ru''', '''zh''', '''de'''] } class lowerCamelCase_ ( _lowercase ): _lowercase : Optional[Any] = VOCAB_FILES_NAMES _lowercase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase : str = PRETRAINED_VOCAB_FILES_MAP _lowercase : Any = ['''input_ids''', '''attention_mask'''] _lowercase : List[int] = [] _lowercase : List[int] = [] def __init__( self : Dict , __A : Optional[Any] , __A : Any , __A : Tuple=None , __A : List[str]=None , __A : int="<s>" , __A : Union[str, Any]="</s>" , __A : Optional[Any]="</s>" , __A : Tuple="<pad>" , __A : List[str]="<unk>" , __A : Optional[Any]="m2m100" , __A : Optional[Dict[str, Any]] = None , __A : Any=8 , **__A : List[str] , ): __A : int = {} if sp_model_kwargs is None else sp_model_kwargs __A : List[Any] = language_codes __A : List[str] = FAIRSEQ_LANGUAGE_CODES[language_codes] __A : str = {lang_code: F"""__{lang_code}__""" for lang_code in fairseq_language_code} __A : Optional[int] = kwargs.get("""additional_special_tokens""" , [] ) kwargs["additional_special_tokens"] += [ self.get_lang_token(__A ) for lang_code in fairseq_language_code if self.get_lang_token(__A ) not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=__A , tgt_lang=__A , bos_token=__A , eos_token=__A , sep_token=__A , unk_token=__A , pad_token=__A , language_codes=__A , sp_model_kwargs=self.sp_model_kwargs , num_madeup_words=__A , **__A , ) __A : Any = vocab_file __A : Any = load_json(__A ) __A : Union[str, Any] = {v: k for k, v in self.encoder.items()} __A : Optional[int] = spm_file __A : Dict = load_spm(__A , self.sp_model_kwargs ) __A : int = len(self.encoder ) __A : Optional[Any] = { self.get_lang_token(__A ): self.encoder_size + i for i, lang_code in enumerate(__A ) } __A : Any = {lang_code: self.encoder_size + i for i, lang_code in enumerate(__A )} __A : Union[str, Any] = {v: k for k, v in self.lang_token_to_id.items()} __A : Tuple = src_lang if src_lang is not None else """en""" __A : Dict = tgt_lang __A : List[Any] = self.get_lang_id(self._src_lang ) self.set_src_lang_special_tokens(self._src_lang ) __A : str = num_madeup_words @property def lowerCAmelCase_ ( self : Any ): return len(self.encoder ) + len(self.lang_token_to_id ) @property def lowerCAmelCase_ ( self : int ): return self._src_lang @src_lang.setter def lowerCAmelCase_ ( self : int , __A : str ): __A : Optional[Any] = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def lowerCAmelCase_ ( self : str , __A : str ): return self.sp_model.encode(__A , out_type=__A ) def lowerCAmelCase_ ( self : str , __A : Union[str, Any] ): if token in self.lang_token_to_id: return self.lang_token_to_id[token] return self.encoder.get(__A , self.encoder[self.unk_token] ) def lowerCAmelCase_ ( self : int , __A : int ): if index in self.id_to_lang_token: return self.id_to_lang_token[index] return self.decoder.get(__A , self.unk_token ) def lowerCAmelCase_ ( self : Tuple , __A : Optional[Any] ): __A : Dict = [] __A : Tuple = """""" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(__A ) + token __A : Dict = [] else: current_sub_tokens.append(__A ) out_string += self.sp_model.decode(__A ) return out_string.strip() def lowerCAmelCase_ ( self : List[str] , __A : List[int] , __A : Optional[List[int]] = None , __A : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) __A : Optional[Any] = [1] * len(self.prefix_tokens ) __A : Optional[Any] = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__A )) + suffix_ones return prefix_ones + ([0] * len(__A )) + ([0] * len(__A )) + suffix_ones def lowerCAmelCase_ ( self : Optional[int] , __A : List[int] , __A : Optional[List[int]] = None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def lowerCAmelCase_ ( self : List[str] ): __A : Tuple = {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[int] ): __A : List[str] = self.__dict__.copy() __A : Union[str, Any] = None return state def __setstate__( self : Dict , __A : Dict ): __A : List[str] = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): __A : Union[str, Any] = {} __A : str = load_spm(self.spm_file , self.sp_model_kwargs ) def lowerCAmelCase_ ( self : str , __A : str , __A : Optional[str] = None ): __A : str = Path(__A ) if not save_dir.is_dir(): raise OSError(F"""{save_directory} should be a directory""" ) __A : str = save_dir / ( (filename_prefix + """-""" if filename_prefix else """""") + self.vocab_files_names["""vocab_file"""] ) __A : Dict = save_dir / ( (filename_prefix + """-""" if filename_prefix else """""") + self.vocab_files_names["""spm_file"""] ) save_json(self.encoder , __A ) if os.path.abspath(self.spm_file ) != os.path.abspath(__A ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , __A ) elif not os.path.isfile(self.spm_file ): with open(__A , """wb""" ) as fi: __A : str = self.sp_model.serialized_model_proto() fi.write(__A ) return (str(__A ), str(__A )) def lowerCAmelCase_ ( self : Union[str, Any] , __A : List[str] , __A : str = "en" , __A : Optional[List[str]] = None , __A : str = "ro" , **__A : Optional[int] , ): __A : Any = src_lang __A : Optional[Any] = tgt_lang self.set_src_lang_special_tokens(self.src_lang ) return super().prepare_seqaseq_batch(__A , __A , **__A ) def lowerCAmelCase_ ( self : int , __A : Dict , __A : Optional[str] , __A : Optional[str] , **__A : List[str] ): if src_lang is None or tgt_lang is None: raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model""" ) __A : List[Any] = src_lang __A : str = self(__A , add_special_tokens=__A , **__A ) __A : Optional[int] = self.get_lang_id(__A ) __A : Optional[Any] = tgt_lang_id return inputs def lowerCAmelCase_ ( self : List[str] ): self.set_src_lang_special_tokens(self.src_lang ) def lowerCAmelCase_ ( self : Optional[Any] ): self.set_tgt_lang_special_tokens(self.tgt_lang ) def lowerCAmelCase_ ( self : Dict , __A : str ): __A : Any = self.get_lang_token(__A ) __A : Any = self.lang_token_to_id[lang_token] __A : Any = [self.cur_lang_id] __A : Optional[Any] = [self.eos_token_id] def lowerCAmelCase_ ( self : int , __A : str ): __A : Tuple = self.get_lang_token(__A ) __A : Dict = self.lang_token_to_id[lang_token] __A : Union[str, Any] = [self.cur_lang_id] __A : str = [self.eos_token_id] def lowerCAmelCase_ ( self : Tuple , __A : str ): return self.lang_code_to_token[lang] def lowerCAmelCase_ ( self : str , __A : str ): __A : List[Any] = self.get_lang_token(__A ) return self.lang_token_to_id[lang_token] def __SCREAMING_SNAKE_CASE ( a__ : str ,a__ : Dict[str, Any] ) -> sentencepiece.SentencePieceProcessor: __A : Optional[int] = sentencepiece.SentencePieceProcessor(**a__ ) spm.Load(str(a__ ) ) return spm def __SCREAMING_SNAKE_CASE ( a__ : str ) -> Union[Dict, List]: with open(a__ ,"""r""" ) as f: return json.load(a__ ) def __SCREAMING_SNAKE_CASE ( a__ : Optional[Any] ,a__ : str ) -> None: with open(a__ ,"""w""" ) as f: json.dump(a__ ,a__ ,indent=2 )
17
"""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
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE = { "microsoft/markuplm-base": "https://huggingface.co/microsoft/markuplm-base/resolve/main/config.json", "microsoft/markuplm-large": "https://huggingface.co/microsoft/markuplm-large/resolve/main/config.json", } class lowerCAmelCase_ ( __magic_name__ ): __lowerCamelCase : Union[str, Any] = "markuplm" def __init__( self , _lowerCAmelCase=30522 , _lowerCAmelCase=768 , _lowerCAmelCase=12 , _lowerCAmelCase=12 , _lowerCAmelCase=3072 , _lowerCAmelCase="gelu" , _lowerCAmelCase=0.1 , _lowerCAmelCase=0.1 , _lowerCAmelCase=512 , _lowerCAmelCase=2 , _lowerCAmelCase=0.02 , _lowerCAmelCase=1E-12 , _lowerCAmelCase=0 , _lowerCAmelCase=0 , _lowerCAmelCase=2 , _lowerCAmelCase=256 , _lowerCAmelCase=1024 , _lowerCAmelCase=216 , _lowerCAmelCase=1001 , _lowerCAmelCase=32 , _lowerCAmelCase=50 , _lowerCAmelCase="absolute" , _lowerCAmelCase=True , _lowerCAmelCase=None , **_lowerCAmelCase , ) -> Optional[Any]: super().__init__( pad_token_id=_lowerCAmelCase , bos_token_id=_lowerCAmelCase , eos_token_id=_lowerCAmelCase , **_lowerCAmelCase , ) _lowerCAmelCase = vocab_size _lowerCAmelCase = hidden_size _lowerCAmelCase = num_hidden_layers _lowerCAmelCase = num_attention_heads _lowerCAmelCase = hidden_act _lowerCAmelCase = intermediate_size _lowerCAmelCase = hidden_dropout_prob _lowerCAmelCase = attention_probs_dropout_prob _lowerCAmelCase = max_position_embeddings _lowerCAmelCase = type_vocab_size _lowerCAmelCase = initializer_range _lowerCAmelCase = layer_norm_eps _lowerCAmelCase = position_embedding_type _lowerCAmelCase = use_cache _lowerCAmelCase = classifier_dropout # additional properties _lowerCAmelCase = max_depth _lowerCAmelCase = max_xpath_tag_unit_embeddings _lowerCAmelCase = max_xpath_subs_unit_embeddings _lowerCAmelCase = tag_pad_id _lowerCAmelCase = subs_pad_id _lowerCAmelCase = xpath_unit_hidden_size
18
"""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
0
"""simple docstring""" import baseaa import io import json import os from copy import deepcopy from ..optimizer import AcceleratedOptimizer from ..scheduler import AcceleratedScheduler class _UpperCAmelCase: def __init__( self , __a) -> Optional[int]: '''simple docstring''' if isinstance(__a , __a): # Don't modify user's data should they want to reuse it (e.g. in tests), because once we # modified it, it will not be accepted here again, since `auto` values would have been overridden _UpperCamelCase = deepcopy(__a) elif os.path.exists(__a): with io.open(__a , '''r''' , encoding='''utf-8''') as f: _UpperCamelCase = json.load(__a) else: try: _UpperCamelCase = baseaa.urlsafe_baadecode(__a).decode('''utf-8''') _UpperCamelCase = json.loads(__a) except (UnicodeDecodeError, AttributeError, ValueError): raise ValueError( F'''Expected a string path to an existing deepspeed config, or a dictionary, or a base64 encoded string. Received: {config_file_or_dict}''') _UpperCamelCase = config self.set_stage_and_offload() def UpperCAmelCase ( self) -> str: '''simple docstring''' # zero stage - this is done as early as possible, before model is created, to allow # ``is_deepspeed_zero3_enabled`` query and getting to the early deepspeed config object # during ``zero.Init()`` which needs to know the dtype, and some other hparams. _UpperCamelCase = self.get_value('''zero_optimization.stage''' , -1) # offload _UpperCamelCase = False if self.is_zeroa() or self.is_zeroa(): _UpperCamelCase = set(['''cpu''', '''nvme''']) _UpperCamelCase = set( [ self.get_value('''zero_optimization.offload_optimizer.device'''), self.get_value('''zero_optimization.offload_param.device'''), ]) if len(offload_devices & offload_devices_valid) > 0: _UpperCamelCase = True def UpperCAmelCase ( self , __a) -> Tuple: '''simple docstring''' _UpperCamelCase = self.config # find the config node of interest if it exists _UpperCamelCase = ds_key_long.split('''.''') _UpperCamelCase = nodes.pop() for node in nodes: _UpperCamelCase = config.get(__a) if config is None: return None, ds_key return config, ds_key def UpperCAmelCase ( self , __a , __a=None) -> Dict: '''simple docstring''' _UpperCamelCase , _UpperCamelCase = self.find_config_node(__a) if config is None: return default return config.get(__a , __a) def UpperCAmelCase ( self , __a , __a=False) -> int: '''simple docstring''' _UpperCamelCase = self.config # find the config node of interest if it exists _UpperCamelCase = ds_key_long.split('''.''') for node in nodes: _UpperCamelCase = config _UpperCamelCase = config.get(__a) if config is None: if must_exist: raise ValueError(F'''Can\'t find {ds_key_long} entry in the config: {self.config}''') else: return # if found remove it if parent_config is not None: parent_config.pop(__a) def UpperCAmelCase ( self , __a) -> Union[str, Any]: '''simple docstring''' _UpperCamelCase = self.get_value(__a) return False if value is None else bool(__a) def UpperCAmelCase ( self , __a) -> List[Any]: '''simple docstring''' _UpperCamelCase = self.get_value(__a) return False if value is None else not bool(__a) def UpperCAmelCase ( self) -> List[Any]: '''simple docstring''' return self._stage == 2 def UpperCAmelCase ( self) -> int: '''simple docstring''' return self._stage == 3 def UpperCAmelCase ( self) -> str: '''simple docstring''' return self._offload class _UpperCAmelCase: def __init__( self , __a) -> Dict: '''simple docstring''' _UpperCamelCase = engine def UpperCAmelCase ( self , __a , **__a) -> List[str]: '''simple docstring''' # runs backpropagation and handles mixed precision self.engine.backward(__a , **__a) # Deepspeed's `engine.step` performs the following operations: # - gradient accumulation check # - gradient clipping # - optimizer step # - zero grad # - checking overflow # - lr_scheduler step (only if engine.lr_scheduler is not None) self.engine.step() # and this plugin overrides the above calls with no-ops when Accelerate runs under # Deepspeed, but allows normal functionality for non-Deepspeed cases thus enabling a simple # training loop that works transparently under many training regimes. class _UpperCAmelCase( lowerCamelCase ): def __init__( self , __a) -> List[Any]: '''simple docstring''' super().__init__(__a , device_placement=__a , scaler=__a) _UpperCamelCase = hasattr(self.optimizer , '''overflow''') def UpperCAmelCase ( self , __a=None) -> Tuple: '''simple docstring''' pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed def UpperCAmelCase ( self) -> str: '''simple docstring''' pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed @property def UpperCAmelCase ( self) -> Optional[Any]: '''simple docstring''' if self.__has_overflow__: return self.optimizer.overflow return False class _UpperCAmelCase( lowerCamelCase ): def __init__( self , __a , __a) -> Dict: '''simple docstring''' super().__init__(__a , __a) def UpperCAmelCase ( self) -> str: '''simple docstring''' pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed class _UpperCAmelCase: def __init__( self , __a , __a=0.001 , __a=0 , **__a) -> Tuple: '''simple docstring''' _UpperCamelCase = params _UpperCamelCase = lr _UpperCamelCase = weight_decay _UpperCamelCase = kwargs class _UpperCAmelCase: def __init__( self , __a , __a=None , __a=0 , **__a) -> List[str]: '''simple docstring''' _UpperCamelCase = optimizer _UpperCamelCase = total_num_steps _UpperCamelCase = warmup_num_steps _UpperCamelCase = kwargs
19
"""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
0
import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available _lowerCAmelCase: Optional[Any] = logging.getLogger(__name__) @dataclass class lowercase_ : snake_case =42 snake_case =42 snake_case =42 @dataclass class lowercase_ : snake_case =42 snake_case =42 snake_case =None snake_case =None class lowercase_ (lowercase__ ): snake_case ='train' snake_case ='dev' snake_case ='test' class lowercase_ : @staticmethod def __UpperCamelCase ( lowercase_ , lowercase_) -> List[InputExample]: raise NotImplementedError @staticmethod def __UpperCamelCase ( lowercase_) -> List[str]: raise NotImplementedError @staticmethod def __UpperCamelCase ( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_=False , lowercase_="[CLS]" , lowercase_=1 , lowercase_="[SEP]" , lowercase_=False , lowercase_=False , lowercase_=0 , lowercase_=0 , lowercase_=-100 , lowercase_=0 , lowercase_=True , ) -> List[InputFeatures]: a__ ={label: i for i, label in enumerate(lowercase_)} a__ =[] for ex_index, example in enumerate(lowercase_): if ex_index % 10000 == 0: logger.info('Writing example %d of %d' , lowercase_ , len(lowercase_)) a__ =[] a__ =[] for word, label in zip(example.words , example.labels): a__ =tokenizer.tokenize(lowercase_) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(lowercase_) > 0: tokens.extend(lowercase_) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(lowercase_) - 1)) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. a__ =tokenizer.num_special_tokens_to_add() if len(lowercase_) > max_seq_length - special_tokens_count: a__ =tokens[: (max_seq_length - special_tokens_count)] a__ =label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] a__ =[sequence_a_segment_id] * len(lowercase_) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: a__ =[cls_token] + tokens a__ =[pad_token_label_id] + label_ids a__ =[cls_token_segment_id] + segment_ids a__ =tokenizer.convert_tokens_to_ids(lowercase_) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. a__ =[1 if mask_padding_with_zero else 0] * len(lowercase_) # Zero-pad up to the sequence length. a__ =max_seq_length - len(lowercase_) if pad_on_left: a__ =([pad_token] * padding_length) + input_ids a__ =([0 if mask_padding_with_zero else 1] * padding_length) + input_mask a__ =([pad_token_segment_id] * padding_length) + segment_ids a__ =([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(lowercase_) == max_seq_length assert len(lowercase_) == max_seq_length assert len(lowercase_) == max_seq_length assert len(lowercase_) == max_seq_length if ex_index < 5: logger.info('*** Example ***') logger.info('guid: %s' , example.guid) logger.info('tokens: %s' , ' '.join([str(lowercase_) for x in tokens])) logger.info('input_ids: %s' , ' '.join([str(lowercase_) for x in input_ids])) logger.info('input_mask: %s' , ' '.join([str(lowercase_) for x in input_mask])) logger.info('segment_ids: %s' , ' '.join([str(lowercase_) for x in segment_ids])) logger.info('label_ids: %s' , ' '.join([str(lowercase_) for x in label_ids])) if "token_type_ids" not in tokenizer.model_input_names: a__ =None features.append( InputFeatures( input_ids=lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , label_ids=lowercase_)) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class lowercase_ (lowercase__ ): snake_case =42 snake_case =nn.CrossEntropyLoss().ignore_index def __init__( self , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ = None , lowercase_=False , lowercase_ = Split.train , ) -> str: # Load data features from cache or dataset file a__ =os.path.join( lowercase_ , 'cached_{}_{}_{}'.format(mode.value , tokenizer.__class__.__name__ , str(lowercase_)) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. a__ =cached_features_file + '.lock' with FileLock(lowercase_): if os.path.exists(lowercase_) and not overwrite_cache: logger.info(F"""Loading features from cached file {cached_features_file}""") a__ =torch.load(lowercase_) else: logger.info(F"""Creating features from dataset file at {data_dir}""") a__ =token_classification_task.read_examples_from_file(lowercase_ , lowercase_) # TODO clean up all this to leverage built-in features of tokenizers a__ =token_classification_task.convert_examples_to_features( lowercase_ , lowercase_ , lowercase_ , lowercase_ , cls_token_at_end=bool(model_type in ['xlnet']) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['xlnet'] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=lowercase_ , pad_on_left=bool(tokenizer.padding_side == 'left') , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(F"""Saving features into cached file {cached_features_file}""") torch.save(self.features , lowercase_) def __len__( self) -> Optional[int]: return len(self.features) def __getitem__( self , lowercase_) -> InputFeatures: return self.features[i] if is_tf_available(): import tensorflow as tf class lowercase_ : snake_case =42 snake_case =-100 def __init__( self , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ = None , lowercase_=False , lowercase_ = Split.train , ) -> Union[str, Any]: a__ =token_classification_task.read_examples_from_file(lowercase_ , lowercase_) # TODO clean up all this to leverage built-in features of tokenizers a__ =token_classification_task.convert_examples_to_features( lowercase_ , lowercase_ , lowercase_ , lowercase_ , cls_token_at_end=bool(model_type in ['xlnet']) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['xlnet'] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=lowercase_ , pad_on_left=bool(tokenizer.padding_side == 'left') , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: a__ =tf.data.Dataset.from_generator( lowercase_ , ({'input_ids': tf.intaa, 'attention_mask': tf.intaa}, tf.intaa) , ( {'input_ids': tf.TensorShape([None]), 'attention_mask': tf.TensorShape([None])}, tf.TensorShape([None]), ) , ) else: a__ =tf.data.Dataset.from_generator( lowercase_ , ({'input_ids': tf.intaa, 'attention_mask': tf.intaa, 'token_type_ids': tf.intaa}, tf.intaa) , ( { 'input_ids': tf.TensorShape([None]), 'attention_mask': tf.TensorShape([None]), 'token_type_ids': tf.TensorShape([None]), }, tf.TensorShape([None]), ) , ) def __UpperCamelCase ( self) -> int: a__ =self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features))) return self.dataset def __len__( self) -> Any: return len(self.features) def __getitem__( self , lowercase_) -> InputFeatures: return self.features[i]
20
"""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
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, is_vision_available, ) UpperCAmelCase_ : Union[str, Any] = {"configuration_vit": ["VIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "ViTConfig", "ViTOnnxConfig"]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : List[str] = ["ViTFeatureExtractor"] UpperCAmelCase_ : Any = ["ViTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Optional[Any] = [ "VIT_PRETRAINED_MODEL_ARCHIVE_LIST", "ViTForImageClassification", "ViTForMaskedImageModeling", "ViTModel", "ViTPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : List[str] = [ "TFViTForImageClassification", "TFViTModel", "TFViTPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Union[str, Any] = [ "FlaxViTForImageClassification", "FlaxViTModel", "FlaxViTPreTrainedModel", ] if TYPE_CHECKING: from .configuration_vit import VIT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTConfig, ViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_vit import ViTFeatureExtractor from .image_processing_vit import ViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit import ( VIT_PRETRAINED_MODEL_ARCHIVE_LIST, ViTForImageClassification, ViTForMaskedImageModeling, ViTModel, ViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit import TFViTForImageClassification, TFViTModel, TFViTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel, FlaxViTPreTrainedModel else: import sys UpperCAmelCase_ : List[str] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
21
"""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
0
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass class A ( _a ): lowercase_ = 42 lowercase_ = 42 lowercase_ = None class A ( _a ,_a ): lowercase_ = 2 @register_to_config def __init__( self : Dict , lowerCAmelCase_ : float = 0.0_2 , lowerCAmelCase_ : float = 1_00 , lowerCAmelCase_ : float = 1.0_0_7 , lowerCAmelCase_ : float = 80 , lowerCAmelCase_ : float = 0.0_5 , lowerCAmelCase_ : float = 50 , ) -> Tuple: """simple docstring""" _a = sigma_max # setable values _a = None _a = None _a = None # sigma(t_i) def __lowerCAmelCase ( self : Any , lowerCAmelCase_ : torch.FloatTensor , lowerCAmelCase_ : Optional[int] = None ) -> torch.FloatTensor: """simple docstring""" return sample def __lowerCAmelCase ( self : Union[str, Any] , lowerCAmelCase_ : int , lowerCAmelCase_ : Union[str, torch.device] = None ) -> List[str]: """simple docstring""" _a = num_inference_steps _a = np.arange(0 , self.num_inference_steps )[::-1].copy() _a = torch.from_numpy(lowerCAmelCase_ ).to(lowerCAmelCase_ ) _a = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in self.timesteps ] _a = torch.tensor(lowerCAmelCase_ , dtype=torch.floataa , device=lowerCAmelCase_ ) def __lowerCAmelCase ( self : Dict , lowerCAmelCase_ : torch.FloatTensor , lowerCAmelCase_ : float , lowerCAmelCase_ : Optional[torch.Generator] = None ) -> Tuple[torch.FloatTensor, float]: """simple docstring""" if self.config.s_min <= sigma <= self.config.s_max: _a = min(self.config.s_churn / self.num_inference_steps , 2**0.5 - 1 ) else: _a = 0 # sample eps ~ N(0, S_noise^2 * I) _a = self.config.s_noise * randn_tensor(sample.shape , generator=lowerCAmelCase_ ).to(sample.device ) _a = sigma + gamma * sigma _a = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def __lowerCAmelCase ( self : List[str] , lowerCAmelCase_ : torch.FloatTensor , lowerCAmelCase_ : float , lowerCAmelCase_ : float , lowerCAmelCase_ : torch.FloatTensor , lowerCAmelCase_ : bool = True , ) -> Union[KarrasVeOutput, Tuple]: """simple docstring""" _a = sample_hat + sigma_hat * model_output _a = (sample_hat - pred_original_sample) / sigma_hat _a = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=lowerCAmelCase_ , derivative=lowerCAmelCase_ , pred_original_sample=lowerCAmelCase_ ) def __lowerCAmelCase ( self : Dict , lowerCAmelCase_ : torch.FloatTensor , lowerCAmelCase_ : float , lowerCAmelCase_ : float , lowerCAmelCase_ : torch.FloatTensor , lowerCAmelCase_ : torch.FloatTensor , lowerCAmelCase_ : torch.FloatTensor , lowerCAmelCase_ : bool = True , ) -> Union[KarrasVeOutput, Tuple]: """simple docstring""" _a = sample_prev + sigma_prev * model_output _a = (sample_prev - pred_original_sample) / sigma_prev _a = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=lowerCAmelCase_ , derivative=lowerCAmelCase_ , pred_original_sample=lowerCAmelCase_ ) def __lowerCAmelCase ( self : Optional[Any] , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[Any] ) -> List[str]: """simple docstring""" raise NotImplementedError()
22
"""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
0
import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.transforms.functional import InterpolationMode from transformers import ( BertTokenizer, BlipConfig, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, ) def _snake_case (__lowercase , __lowercase): UpperCamelCase_ = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg' UpperCamelCase_ = Image.open(requests.get(__lowercase , stream=__lowercase).raw).convert('RGB') UpperCamelCase_ = transforms.Compose( [ transforms.Resize((image_size, image_size) , interpolation=InterpolationMode.BICUBIC), transforms.ToTensor(), transforms.Normalize((0.48_145_466, 0.4_578_275, 0.40_821_073) , (0.26_862_954, 0.26_130_258, 0.27_577_711)), ]) UpperCamelCase_ = transform(__lowercase).unsqueeze(0).to(__lowercase) return image def _snake_case (__lowercase): if "visual_encoder" in key: UpperCamelCase_ = re.sub('visual_encoder*' , 'vision_model.encoder' , __lowercase) if "blocks" in key: UpperCamelCase_ = re.sub(r'blocks' , 'layers' , __lowercase) if "attn" in key: UpperCamelCase_ = re.sub(r'attn' , 'self_attn' , __lowercase) if "norm1" in key: UpperCamelCase_ = re.sub(r'norm1' , 'layer_norm1' , __lowercase) if "norm2" in key: UpperCamelCase_ = re.sub(r'norm2' , 'layer_norm2' , __lowercase) if "encoder.norm" in key: UpperCamelCase_ = re.sub(r'encoder.norm' , 'post_layernorm' , __lowercase) if "encoder.patch_embed.proj" in key: UpperCamelCase_ = re.sub(r'encoder.patch_embed.proj' , 'embeddings.patch_embedding' , __lowercase) if "encoder.pos_embed" in key: UpperCamelCase_ = re.sub(r'encoder.pos_embed' , 'embeddings.position_embedding' , __lowercase) if "encoder.cls_token" in key: UpperCamelCase_ = re.sub(r'encoder.cls_token' , 'embeddings.class_embedding' , __lowercase) if "self_attn" in key: UpperCamelCase_ = re.sub(r'self_attn.proj' , 'self_attn.projection' , __lowercase) return key @torch.no_grad() def _snake_case (__lowercase , __lowercase=None): if config_path is not None: UpperCamelCase_ = BlipConfig.from_pretrained(__lowercase) else: UpperCamelCase_ = BlipConfig(projection_dim=512 , text_config={} , vision_config={}) UpperCamelCase_ = BlipForConditionalGeneration(__lowercase).eval() UpperCamelCase_ = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth' UpperCamelCase_ = blip_decoder(pretrained=__lowercase , image_size=384 , vit='base') UpperCamelCase_ = pt_model.eval() UpperCamelCase_ = pt_model.state_dict() for key in modified_state_dict.copy(): UpperCamelCase_ = modified_state_dict.pop(__lowercase) UpperCamelCase_ = rename_key(__lowercase) UpperCamelCase_ = value hf_model.load_state_dict(__lowercase) UpperCamelCase_ = 384 UpperCamelCase_ = load_demo_image(image_size=__lowercase , device='cpu') UpperCamelCase_ = BertTokenizer.from_pretrained('bert-base-uncased') UpperCamelCase_ = tokenizer(['a picture of']).input_ids UpperCamelCase_ = hf_model.generate(__lowercase , __lowercase) assert out[0].tolist() == [30522, 1037, 3861, 1997, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102] UpperCamelCase_ = hf_model.generate(__lowercase) assert out[0].tolist() == [30522, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102] if pytorch_dump_folder_path is not None: hf_model.save_pretrained(__lowercase) # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth' UpperCamelCase_ = ( 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth' ) UpperCamelCase_ = blip_vqa(pretrained=__lowercase , image_size=__lowercase , vit='base') vqa_model.eval() UpperCamelCase_ = vqa_model.state_dict() for key in modified_state_dict.copy(): UpperCamelCase_ = modified_state_dict.pop(__lowercase) UpperCamelCase_ = rename_key(__lowercase) UpperCamelCase_ = value UpperCamelCase_ = BlipForQuestionAnswering(__lowercase) hf_vqa_model.load_state_dict(__lowercase) UpperCamelCase_ = ['How many dogs are in this image?'] UpperCamelCase_ = tokenizer(__lowercase , return_tensors='pt').input_ids UpperCamelCase_ = hf_vqa_model.generate(__lowercase , __lowercase) print(tokenizer.decode(answer[0])) assert tokenizer.decode(answer[0]) == "[UNK] 1 [SEP]" if pytorch_dump_folder_path is not None: hf_vqa_model.save_pretrained(pytorch_dump_folder_path + '_vqa') UpperCamelCase_ = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth' UpperCamelCase_ = blip_itm(pretrained=__lowercase , image_size=__lowercase , vit='base') itm_model.eval() UpperCamelCase_ = itm_model.state_dict() for key in modified_state_dict.copy(): UpperCamelCase_ = modified_state_dict.pop(__lowercase) UpperCamelCase_ = rename_key(__lowercase) UpperCamelCase_ = value UpperCamelCase_ = BlipForImageTextRetrieval(__lowercase) UpperCamelCase_ = ['A picture of a woman with a dog sitting in a beach'] UpperCamelCase_ = tokenizer( __lowercase , return_tensors='pt' , padding='max_length' , truncation=__lowercase , max_length=35 , ).input_ids hf_itm_model.load_state_dict(__lowercase) hf_itm_model.eval() UpperCamelCase_ = hf_itm_model(__lowercase , __lowercase , use_itm_head=__lowercase) UpperCamelCase_ = hf_itm_model(__lowercase , __lowercase , use_itm_head=__lowercase) assert out[0].item() == 0.2_110_687_494_277_954 assert torch.nn.functional.softmax(out_itm[0] , dim=1)[:, 1].item() == 0.45_698_845_386_505_127 if pytorch_dump_folder_path is not None: hf_itm_model.save_pretrained(pytorch_dump_folder_path + '_itm') if __name__ == "__main__": snake_case__ : Tuple = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") snake_case__ : Optional[Any] = parser.parse_args() convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
23
"""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
0
'''simple docstring''' from unittest.mock import patch import pyspark from datasets.packaged_modules.spark.spark import ( Spark, SparkExamplesIterable, _generate_iterable_examples, ) from ..utils import ( require_dill_gt_0_3_2, require_not_windows, ) def _UpperCamelCase (_lowerCamelCase : Union[str, Any] , _lowerCamelCase : List[Any] )-> Optional[Any]: '''simple docstring''' __snake_case = [] for part_id in partition_order: __snake_case = df.where(f'''SPARK_PARTITION_ID() = {part_id}''' ).collect() for row_idx, row in enumerate(_lowerCamelCase ): expected_row_ids_and_row_dicts.append((f'''{part_id}_{row_idx}''', row.asDict()) ) return expected_row_ids_and_row_dicts @require_not_windows @require_dill_gt_0_3_2 def _UpperCamelCase ()-> Any: '''simple docstring''' __snake_case = pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() __snake_case = spark.range(1_00 ).repartition(1 ) __snake_case = Spark(_lowerCamelCase ) # The id ints will be converted to Pyarrow int64s, so each row will be 8 bytes. Setting a max_shard_size of 16 means # that each partition can hold 2 rows. spark_builder._repartition_df_if_needed(max_shard_size=16 ) # Given that the dataframe has 100 rows and each partition has 2 rows, we expect 50 partitions. assert spark_builder.df.rdd.getNumPartitions() == 50 @require_not_windows @require_dill_gt_0_3_2 def _UpperCamelCase ()-> Tuple: '''simple docstring''' __snake_case = pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() __snake_case = spark.range(10 ).repartition(2 ) __snake_case = [1, 0] __snake_case = _generate_iterable_examples(_lowerCamelCase , _lowerCamelCase ) # Reverse the partitions. __snake_case = _get_expected_row_ids_and_row_dicts_for_partition_order(_lowerCamelCase , _lowerCamelCase ) for i, (row_id, row_dict) in enumerate(generate_fn() ): __snake_case , __snake_case = expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def _UpperCamelCase ()-> int: '''simple docstring''' __snake_case = pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() __snake_case = spark.range(10 ).repartition(1 ) __snake_case = SparkExamplesIterable(_lowerCamelCase ) assert it.n_shards == 1 for i, (row_id, row_dict) in enumerate(_lowerCamelCase ): assert row_id == f'''0_{i}''' assert row_dict == {"id": i} @require_not_windows @require_dill_gt_0_3_2 def _UpperCamelCase ()-> Union[str, Any]: '''simple docstring''' __snake_case = pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() __snake_case = spark.range(30 ).repartition(3 ) # Mock the generator so that shuffle reverses the partition indices. with patch('''numpy.random.Generator''' ) as generator_mock: __snake_case = lambda _lowerCamelCase : x.reverse() __snake_case = _get_expected_row_ids_and_row_dicts_for_partition_order(_lowerCamelCase , [2, 1, 0] ) __snake_case = SparkExamplesIterable(_lowerCamelCase ).shuffle_data_sources(_lowerCamelCase ) assert shuffled_it.n_shards == 3 for i, (row_id, row_dict) in enumerate(_lowerCamelCase ): __snake_case , __snake_case = expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def _UpperCamelCase ()-> Tuple: '''simple docstring''' __snake_case = pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() __snake_case = spark.range(20 ).repartition(4 ) # Partitions 0 and 2 __snake_case = SparkExamplesIterable(_lowerCamelCase ).shard_data_sources(worker_id=0 , num_workers=2 ) assert shard_it_a.n_shards == 2 __snake_case = _get_expected_row_ids_and_row_dicts_for_partition_order(_lowerCamelCase , [0, 2] ) for i, (row_id, row_dict) in enumerate(_lowerCamelCase ): __snake_case , __snake_case = expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict # Partitions 1 and 3 __snake_case = SparkExamplesIterable(_lowerCamelCase ).shard_data_sources(worker_id=1 , num_workers=2 ) assert shard_it_a.n_shards == 2 __snake_case = _get_expected_row_ids_and_row_dicts_for_partition_order(_lowerCamelCase , [1, 3] ) for i, (row_id, row_dict) in enumerate(_lowerCamelCase ): __snake_case , __snake_case = expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def _UpperCamelCase ()-> Optional[int]: '''simple docstring''' __snake_case = pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() __snake_case = spark.range(1_00 ).repartition(1 ) __snake_case = Spark(_lowerCamelCase ) # Choose a small max_shard_size for maximum partitioning. spark_builder._repartition_df_if_needed(max_shard_size=1 ) # The new number of partitions should not be greater than the number of rows. assert spark_builder.df.rdd.getNumPartitions() == 1_00
24
"""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
0
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_big_bird import BigBirdTokenizer else: a_ = None a_ = logging.get_logger(__name__) a_ = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} a_ = { 'vocab_file': { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model', 'google/bigbird-roberta-large': ( 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model' ), 'google/bigbird-base-trivia-itc': ( 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model' ), }, 'tokenizer_file': { 'google/bigbird-roberta-base': ( 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/tokenizer.json' ), 'google/bigbird-roberta-large': ( 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/tokenizer.json' ), 'google/bigbird-base-trivia-itc': ( 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/tokenizer.json' ), }, } a_ = { 'google/bigbird-roberta-base': 4096, 'google/bigbird-roberta-large': 4096, 'google/bigbird-base-trivia-itc': 4096, } a_ = '▁' class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ =VOCAB_FILES_NAMES lowerCamelCase__ =PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ =BigBirdTokenizer lowerCamelCase__ =['input_ids', 'attention_mask'] lowerCamelCase__ =[] def __init__( self : str , a : int=None , a : Optional[int]=None , a : Union[str, Any]="<unk>" , a : int="<s>" , a : Any="</s>" , a : List[str]="<pad>" , a : List[Any]="[SEP]" , a : Optional[Any]="[MASK]" , a : Optional[int]="[CLS]" , **a : List[str] , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : str = AddedToken(a , lstrip=a , rstrip=a ) if isinstance(a , a ) else bos_token SCREAMING_SNAKE_CASE : Tuple = AddedToken(a , lstrip=a , rstrip=a ) if isinstance(a , a ) else eos_token SCREAMING_SNAKE_CASE : List[Any] = AddedToken(a , lstrip=a , rstrip=a ) if isinstance(a , a ) else unk_token SCREAMING_SNAKE_CASE : Optional[int] = AddedToken(a , lstrip=a , rstrip=a ) if isinstance(a , a ) else pad_token SCREAMING_SNAKE_CASE : Optional[Any] = AddedToken(a , lstrip=a , rstrip=a ) if isinstance(a , a ) else cls_token SCREAMING_SNAKE_CASE : int = AddedToken(a , lstrip=a , rstrip=a ) if isinstance(a , a ) else sep_token # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE : Tuple = AddedToken(a , lstrip=a , rstrip=a ) if isinstance(a , a ) else mask_token super().__init__( a , tokenizer_file=a , bos_token=a , eos_token=a , unk_token=a , sep_token=a , pad_token=a , cls_token=a , mask_token=a , **a , ) SCREAMING_SNAKE_CASE : Tuple = vocab_file SCREAMING_SNAKE_CASE : Tuple = False if not self.vocab_file else True def __UpperCamelCase ( self : Dict , a : List[int] , a : Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = [self.sep_token_id] SCREAMING_SNAKE_CASE : Optional[Any] = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def __UpperCamelCase ( self : List[Any] , a : List[int] , a : Optional[List[int]] = None , a : bool = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: if token_ids_a is not None: raise ValueError( "You should not supply a second sequence if the provided sequence of " "ids is already formatted with special tokens for the model." ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is None: return [1] + ([0] * len(a )) + [1] return [1] + ([0] * len(a )) + [1] + ([0] * len(a )) + [1] def __UpperCamelCase ( self : List[str] , a : List[int] , a : Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = [self.sep_token_id] SCREAMING_SNAKE_CASE : str = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __UpperCamelCase ( self : Optional[Any] , a : str , a : Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not self.can_save_slow_tokenizer: raise ValueError( "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow " "tokenizer." ) if not os.path.isdir(a ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return SCREAMING_SNAKE_CASE : Optional[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 ): copyfile(self.vocab_file , a ) return (out_vocab_file,)
25
"""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
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) __UpperCamelCase = { "configuration_clip": [ "CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "CLIPConfig", "CLIPOnnxConfig", "CLIPTextConfig", "CLIPVisionConfig", ], "processing_clip": ["CLIPProcessor"], "tokenization_clip": ["CLIPTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase = ["CLIPTokenizerFast"] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase = ["CLIPFeatureExtractor"] __UpperCamelCase = ["CLIPImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase = [ "CLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "CLIPModel", "CLIPPreTrainedModel", "CLIPTextModel", "CLIPTextModelWithProjection", "CLIPVisionModel", "CLIPVisionModelWithProjection", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase = [ "TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "TFCLIPModel", "TFCLIPPreTrainedModel", "TFCLIPTextModel", "TFCLIPVisionModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase = [ "FlaxCLIPModel", "FlaxCLIPPreTrainedModel", "FlaxCLIPTextModel", "FlaxCLIPTextPreTrainedModel", "FlaxCLIPVisionModel", "FlaxCLIPVisionPreTrainedModel", ] if TYPE_CHECKING: from .configuration_clip import ( CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPConfig, CLIPOnnxConfig, CLIPTextConfig, CLIPVisionConfig, ) from .processing_clip import CLIPProcessor from .tokenization_clip import CLIPTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_clip_fast import CLIPTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clip import CLIPFeatureExtractor from .image_processing_clip import CLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clip import ( CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPModel, CLIPPreTrainedModel, CLIPTextModel, CLIPTextModelWithProjection, CLIPVisionModel, CLIPVisionModelWithProjection, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_clip import ( TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFCLIPModel, TFCLIPPreTrainedModel, TFCLIPTextModel, TFCLIPVisionModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_clip import ( FlaxCLIPModel, FlaxCLIPPreTrainedModel, FlaxCLIPTextModel, FlaxCLIPTextPreTrainedModel, FlaxCLIPVisionModel, FlaxCLIPVisionPreTrainedModel, ) else: import sys __UpperCamelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
26
"""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
0
import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_poolformer import PoolFormerConfig __A : Optional[int] = logging.get_logger(__name__) # General docstring __A : Optional[Any] = "PoolFormerConfig" # Base docstring __A : Tuple = "sail/poolformer_s12" __A : List[str] = [1, 512, 7, 7] # Image classification docstring __A : Optional[int] = "sail/poolformer_s12" __A : Union[str, Any] = "tabby, tabby cat" __A : int = [ "sail/poolformer_s12", # See all PoolFormer models at https://huggingface.co/models?filter=poolformer ] def __lowerCAmelCase( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = False ) -> str: """simple docstring""" if drop_prob == 0.0 or not training: return input _A = 1 - drop_prob _A = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets _A = keep_prob + torch.rand(_SCREAMING_SNAKE_CASE , dtype=input.dtype , device=input.device ) random_tensor.floor_() # binarize _A = input.div(_SCREAMING_SNAKE_CASE ) * random_tensor return output class lowerCamelCase( nn.Module ): '''simple docstring''' def __init__( self , snake_case_ = None ): super().__init__() _A = drop_prob def lowerCAmelCase__ ( self , snake_case_ ): return drop_path(snake_case_ , self.drop_prob , self.training ) def lowerCAmelCase__ ( self ): return "p={}".format(self.drop_prob ) class lowerCamelCase( nn.Module ): '''simple docstring''' def __init__( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_=None ): super().__init__() _A = patch_size if isinstance(snake_case_ , collections.abc.Iterable ) else (patch_size, patch_size) _A = stride if isinstance(snake_case_ , collections.abc.Iterable ) else (stride, stride) _A = padding if isinstance(snake_case_ , collections.abc.Iterable ) else (padding, padding) _A = nn.Convad(snake_case_ , snake_case_ , kernel_size=snake_case_ , stride=snake_case_ , padding=snake_case_ ) _A = norm_layer(snake_case_ ) if norm_layer else nn.Identity() def lowerCAmelCase__ ( self , snake_case_ ): _A = self.projection(snake_case_ ) _A = self.norm(snake_case_ ) return embeddings class lowerCamelCase( nn.GroupNorm ): '''simple docstring''' def __init__( self , snake_case_ , **snake_case_ ): super().__init__(1 , snake_case_ , **snake_case_ ) class lowerCamelCase( nn.Module ): '''simple docstring''' def __init__( self , snake_case_ ): super().__init__() _A = nn.AvgPoolad(snake_case_ , stride=1 , padding=pool_size // 2 , count_include_pad=snake_case_ ) def lowerCAmelCase__ ( self , snake_case_ ): return self.pool(snake_case_ ) - hidden_states class lowerCamelCase( nn.Module ): '''simple docstring''' def __init__( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ ): super().__init__() _A = nn.Convad(snake_case_ , snake_case_ , 1 ) _A = nn.Convad(snake_case_ , snake_case_ , 1 ) _A = PoolFormerDropPath(snake_case_ ) if isinstance(config.hidden_act , snake_case_ ): _A = ACTaFN[config.hidden_act] else: _A = config.hidden_act def lowerCAmelCase__ ( self , snake_case_ ): _A = self.conva(snake_case_ ) _A = self.act_fn(snake_case_ ) _A = self.drop(snake_case_ ) _A = self.conva(snake_case_ ) _A = self.drop(snake_case_ ) return hidden_states class lowerCamelCase( nn.Module ): '''simple docstring''' def __init__( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ): super().__init__() _A = PoolFormerPooling(snake_case_ ) _A = PoolFormerOutput(snake_case_ , snake_case_ , snake_case_ , snake_case_ ) _A = PoolFormerGroupNorm(snake_case_ ) _A = PoolFormerGroupNorm(snake_case_ ) # Useful for training neural nets _A = PoolFormerDropPath(snake_case_ ) if drop_path > 0.0 else nn.Identity() _A = config.use_layer_scale if config.use_layer_scale: _A = nn.Parameter( config.layer_scale_init_value * torch.ones((snake_case_) ) , requires_grad=snake_case_ ) _A = nn.Parameter( config.layer_scale_init_value * torch.ones((snake_case_) ) , requires_grad=snake_case_ ) def lowerCAmelCase__ ( self , snake_case_ ): if self.use_layer_scale: _A = self.pooling(self.before_norm(snake_case_ ) ) _A = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * pooling_output # First residual connection _A = hidden_states + self.drop_path(snake_case_ ) _A = () _A = self.output(self.after_norm(snake_case_ ) ) _A = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * layer_output # Second residual connection _A = hidden_states + self.drop_path(snake_case_ ) _A = (output,) + outputs return outputs else: _A = self.drop_path(self.pooling(self.before_norm(snake_case_ ) ) ) # First residual connection _A = pooling_output + hidden_states _A = () # Second residual connection inside the PoolFormerOutput block _A = self.drop_path(self.output(self.after_norm(snake_case_ ) ) ) _A = hidden_states + layer_output _A = (output,) + outputs return outputs class lowerCamelCase( nn.Module ): '''simple docstring''' def __init__( self , snake_case_ ): super().__init__() _A = config # stochastic depth decay rule _A = [x.item() for x in torch.linspace(0 , config.drop_path_rate , sum(config.depths ) )] # patch embeddings _A = [] for i in range(config.num_encoder_blocks ): embeddings.append( PoolFormerEmbeddings( patch_size=config.patch_sizes[i] , stride=config.strides[i] , padding=config.padding[i] , num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] , hidden_size=config.hidden_sizes[i] , ) ) _A = nn.ModuleList(snake_case_ ) # Transformer blocks _A = [] _A = 0 for i in range(config.num_encoder_blocks ): # each block consists of layers _A = [] if i != 0: cur += config.depths[i - 1] for j in range(config.depths[i] ): layers.append( PoolFormerLayer( snake_case_ , num_channels=config.hidden_sizes[i] , pool_size=config.pool_size , hidden_size=config.hidden_sizes[i] , intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio ) , drop_path=dpr[cur + j] , ) ) blocks.append(nn.ModuleList(snake_case_ ) ) _A = nn.ModuleList(snake_case_ ) def lowerCAmelCase__ ( self , snake_case_ , snake_case_=False , snake_case_=True ): _A = () if output_hidden_states else None _A = pixel_values for idx, layers in enumerate(zip(self.patch_embeddings , self.block ) ): _A, _A = layers # Get patch embeddings from hidden_states _A = embedding_layer(snake_case_ ) # Send the embeddings through the blocks for _, blk in enumerate(snake_case_ ): _A = blk(snake_case_ ) _A = layer_outputs[0] if output_hidden_states: _A = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=snake_case_ , hidden_states=snake_case_ ) class lowerCamelCase( __snake_case ): '''simple docstring''' __magic_name__ = PoolFormerConfig __magic_name__ = 'poolformer' __magic_name__ = 'pixel_values' __magic_name__ = True def lowerCAmelCase__ ( self , snake_case_ ): if isinstance(snake_case_ , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(snake_case_ , nn.LayerNorm ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) def lowerCAmelCase__ ( self , snake_case_ , snake_case_=False ): if isinstance(snake_case_ , snake_case_ ): _A = value __A : Tuple = r"\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n it 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 ([`PoolFormerConfig`]): 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 [`PoolFormerImageProcessor.__call__`] for details.\n" @add_start_docstrings( 'The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top.' , __snake_case , ) class lowerCamelCase( __snake_case ): '''simple docstring''' def __init__( self , snake_case_ ): super().__init__(snake_case_ ) _A = config _A = PoolFormerEncoder(snake_case_ ) # Initialize weights and apply final processing self.post_init() def lowerCAmelCase__ ( self ): return self.embeddings.patch_embeddings @add_start_docstrings_to_model_forward(snake_case_ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=snake_case_ , config_class=_CONFIG_FOR_DOC , modality='vision' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def lowerCAmelCase__ ( self , snake_case_ = None , snake_case_ = None , snake_case_ = None , ): _A = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _A = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('You have to specify pixel_values' ) _A = self.encoder( snake_case_ , output_hidden_states=snake_case_ , return_dict=snake_case_ , ) _A = encoder_outputs[0] if not return_dict: return (sequence_output, None) + encoder_outputs[1:] return BaseModelOutputWithNoAttention( last_hidden_state=snake_case_ , hidden_states=encoder_outputs.hidden_states , ) class lowerCamelCase( nn.Module ): '''simple docstring''' def __init__( self , snake_case_ ): super().__init__() _A = nn.Linear(config.hidden_size , config.hidden_size ) def lowerCAmelCase__ ( self , snake_case_ ): _A = self.dense(snake_case_ ) return output @add_start_docstrings( '\n PoolFormer Model transformer with an image classification head on top\n ' , __snake_case , ) class lowerCamelCase( __snake_case ): '''simple docstring''' def __init__( self , snake_case_ ): super().__init__(snake_case_ ) _A = config.num_labels _A = PoolFormerModel(snake_case_ ) # Final norm _A = PoolFormerGroupNorm(config.hidden_sizes[-1] ) # Classifier head _A = ( 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(snake_case_ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=snake_case_ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def lowerCAmelCase__ ( self , snake_case_ = None , snake_case_ = None , snake_case_ = None , snake_case_ = None , ): _A = return_dict if return_dict is not None else self.config.use_return_dict _A = self.poolformer( snake_case_ , output_hidden_states=snake_case_ , return_dict=snake_case_ , ) _A = outputs[0] _A = self.classifier(self.norm(snake_case_ ).mean([-2, -1] ) ) _A = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: _A = 'regression' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): _A = 'single_label_classification' else: _A = 'multi_label_classification' if self.config.problem_type == "regression": _A = MSELoss() if self.num_labels == 1: _A = loss_fct(logits.squeeze() , labels.squeeze() ) else: _A = loss_fct(snake_case_ , snake_case_ ) elif self.config.problem_type == "single_label_classification": _A = CrossEntropyLoss() _A = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": _A = BCEWithLogitsLoss() _A = loss_fct(snake_case_ , snake_case_ ) if not return_dict: _A = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=snake_case_ , logits=snake_case_ , hidden_states=outputs.hidden_states )
27
"""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
0
'''simple docstring''' import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, ByTaTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): UpperCamelCase_ = "pt" elif is_tf_available(): UpperCamelCase_ = "tf" else: UpperCamelCase_ = "jax" class _a ( SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' A : Optional[int] = ByTaTokenizer A : Tuple = False def UpperCamelCase_ ( self ): '''simple docstring''' super().setUp() SCREAMING_SNAKE_CASE : List[Any] = ByTaTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def UpperCamelCase_ ( self ): '''simple docstring''' return ByTaTokenizer.from_pretrained('google/byt5-small' ) def UpperCamelCase_ ( self, **A ): '''simple docstring''' return self.tokenizer_class.from_pretrained(self.tmpdirname, **A ) def UpperCamelCase_ ( self, A, A=False, A=20, A=5 ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = [] for i in range(len(A ) ): try: SCREAMING_SNAKE_CASE : int = tokenizer.decode([i], clean_up_tokenization_spaces=A ) except UnicodeDecodeError: pass toks.append((i, tok) ) SCREAMING_SNAKE_CASE : Tuple = list(filter(lambda A : re.match(r'^[ a-zA-Z]+$', t[1] ), A ) ) SCREAMING_SNAKE_CASE : Any = list(filter(lambda A : [t[0]] == tokenizer.encode(t[1], add_special_tokens=A ), A ) ) if max_length is not None and len(A ) > max_length: SCREAMING_SNAKE_CASE : List[Any] = toks[:max_length] if min_length is not None and len(A ) < min_length and len(A ) > 0: while len(A ) < min_length: SCREAMING_SNAKE_CASE : str = toks + toks # toks_str = [t[1] for t in toks] SCREAMING_SNAKE_CASE : str = [t[0] for t in toks] # Ensure consistency SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.decode(A, clean_up_tokenization_spaces=A ) if " " not in output_txt and len(A ) > 1: SCREAMING_SNAKE_CASE : Optional[int] = ( tokenizer.decode([toks_ids[0]], clean_up_tokenization_spaces=A ) + ' ' + tokenizer.decode(toks_ids[1:], clean_up_tokenization_spaces=A ) ) if with_prefix_space: SCREAMING_SNAKE_CASE : Dict = ' ' + output_txt SCREAMING_SNAKE_CASE : Any = tokenizer.encode(A, add_special_tokens=A ) return output_txt, output_ids def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self.ta_base_tokenizer SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer(['hi</s>', 'I went to the gym</s>', '</s>'] ) SCREAMING_SNAKE_CASE : str = tokenizer(['hi', 'I went to the gym', ''] ) self.assertListEqual(batch_with_eos_added['input_ids'], batch_without_eos_added['input_ids'] ) def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.ta_base_tokenizer SCREAMING_SNAKE_CASE : Dict = 'Unicode €.' SCREAMING_SNAKE_CASE : Any = tokenizer(A ) SCREAMING_SNAKE_CASE : List[Any] = [88, 113, 108, 102, 114, 103, 104, 35, 229, 133, 175, 49, 1] self.assertEqual(encoded['input_ids'], A ) # decoding SCREAMING_SNAKE_CASE : Dict = tokenizer.decode(A ) self.assertEqual(A, 'Unicode €.</s>' ) SCREAMING_SNAKE_CASE : int = tokenizer('e è é ê ë' ) SCREAMING_SNAKE_CASE : Optional[int] = [104, 35, 198, 171, 35, 198, 172, 35, 198, 173, 35, 198, 174, 1] self.assertEqual(encoded['input_ids'], A ) # decoding SCREAMING_SNAKE_CASE : str = tokenizer.decode(A ) self.assertEqual(A, 'e è é ê ë</s>' ) # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode('e è é ê ë' ) ), 'e è é ê ë</s>' ) def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.ta_base_tokenizer SCREAMING_SNAKE_CASE : Tuple = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] # fmt: off SCREAMING_SNAKE_CASE : Tuple = [68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 1, 0] # fmt: on SCREAMING_SNAKE_CASE : Any = tokenizer(A, padding=A, return_tensors=A ) self.assertIsInstance(A, A ) if FRAMEWORK != "jax": SCREAMING_SNAKE_CASE : List[str] = list(batch.input_ids.numpy()[0] ) else: SCREAMING_SNAKE_CASE : List[Any] = list(batch.input_ids.tolist()[0] ) self.assertListEqual(A, A ) self.assertEqual((2, 37), batch.input_ids.shape ) self.assertEqual((2, 37), batch.attention_mask.shape ) def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = self.ta_base_tokenizer SCREAMING_SNAKE_CASE : Optional[Any] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer(A, padding=A, return_tensors=A ) # check if input_ids are returned and no decoder_input_ids self.assertIn('input_ids', A ) self.assertIn('attention_mask', A ) self.assertNotIn('decoder_input_ids', A ) self.assertNotIn('decoder_attention_mask', A ) def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = self.ta_base_tokenizer SCREAMING_SNAKE_CASE : List[Any] = [ 'Summary of the text.', 'Another summary.', ] SCREAMING_SNAKE_CASE : str = tokenizer( text_target=A, max_length=32, padding='max_length', truncation=A, return_tensors=A ) self.assertEqual(32, targets['input_ids'].shape[1] ) def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.ta_base_tokenizer SCREAMING_SNAKE_CASE : List[str] = ['A long paragraph for summarization. </s>'] SCREAMING_SNAKE_CASE : Tuple = ['Summary of the text. </s>'] # fmt: off SCREAMING_SNAKE_CASE : Dict = [68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 35, 1] SCREAMING_SNAKE_CASE : Optional[Any] = [86, 120, 112, 112, 100, 117, 124, 35, 114, 105, 35, 119, 107, 104, 35, 119, 104, 123, 119, 49, 35, 1] # fmt: on SCREAMING_SNAKE_CASE : int = tokenizer(A, text_target=A ) self.assertEqual(A, batch['input_ids'][0] ) self.assertEqual(A, batch['labels'][0] ) def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}" ): self.assertNotEqual(tokenizer.model_max_length, 42 ) # Now let's start the test SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}" ): # Isolate this from the other tests because we save additional tokens/etc SCREAMING_SNAKE_CASE : Union[str, Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE : int = ' He is very happy, UNwant\u00E9d,running' SCREAMING_SNAKE_CASE : Any = tokenizer.encode(A, add_special_tokens=A ) tokenizer.save_pretrained(A ) SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.__class__.from_pretrained(A ) SCREAMING_SNAKE_CASE : Union[str, Any] = after_tokenizer.encode(A, add_special_tokens=A ) self.assertListEqual(A, A ) shutil.rmtree(A ) SCREAMING_SNAKE_CASE : Optional[Any] = self.get_tokenizers(model_max_length=42 ) for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}" ): # Isolate this from the other tests because we save additional tokens/etc SCREAMING_SNAKE_CASE : str = tempfile.mkdtemp() SCREAMING_SNAKE_CASE : int = ' He is very happy, UNwant\u00E9d,running' tokenizer.add_tokens(['bim', 'bambam'] ) SCREAMING_SNAKE_CASE : Tuple = tokenizer.additional_special_tokens additional_special_tokens.append('new_additional_special_token' ) tokenizer.add_special_tokens({'additional_special_tokens': additional_special_tokens} ) SCREAMING_SNAKE_CASE : str = tokenizer.encode(A, add_special_tokens=A ) tokenizer.save_pretrained(A ) SCREAMING_SNAKE_CASE : Tuple = tokenizer.__class__.from_pretrained(A ) SCREAMING_SNAKE_CASE : List[Any] = after_tokenizer.encode(A, add_special_tokens=A ) self.assertListEqual(A, A ) self.assertIn('new_additional_special_token', after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length, 42 ) SCREAMING_SNAKE_CASE : Dict = tokenizer.__class__.from_pretrained(A, model_max_length=43 ) self.assertEqual(tokenizer.model_max_length, 43 ) shutil.rmtree(A ) def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(A ) with open(os.path.join(A, 'special_tokens_map.json' ), encoding='utf-8' ) as json_file: SCREAMING_SNAKE_CASE : List[Any] = json.load(A ) with open(os.path.join(A, 'tokenizer_config.json' ), encoding='utf-8' ) as json_file: SCREAMING_SNAKE_CASE : Any = json.load(A ) SCREAMING_SNAKE_CASE : Optional[Any] = [F"<extra_id_{i}>" for i in range(125 )] SCREAMING_SNAKE_CASE : List[Any] = added_tokens_extra_ids + [ 'an_additional_special_token' ] SCREAMING_SNAKE_CASE : Union[str, Any] = added_tokens_extra_ids + [ 'an_additional_special_token' ] with open(os.path.join(A, 'special_tokens_map.json' ), 'w', encoding='utf-8' ) as outfile: json.dump(A, A ) with open(os.path.join(A, 'tokenizer_config.json' ), 'w', encoding='utf-8' ) as outfile: json.dump(A, A ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files SCREAMING_SNAKE_CASE : Dict = tokenizer_class.from_pretrained( A, ) self.assertIn( 'an_additional_special_token', tokenizer_without_change_in_init.additional_special_tokens ) # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( ['an_additional_special_token'], tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(['an_additional_special_token'] ) ), ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained SCREAMING_SNAKE_CASE : Any = added_tokens_extra_ids + [AddedToken('a_new_additional_special_token', lstrip=A )] SCREAMING_SNAKE_CASE : Optional[int] = tokenizer_class.from_pretrained( A, additional_special_tokens=A, ) self.assertIn('a_new_additional_special_token', tokenizer.additional_special_tokens ) self.assertEqual( ['a_new_additional_special_token'], tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(['a_new_additional_special_token'] ) ), ) def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(A ) SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer_class.from_pretrained(A ) self.assertTrue(tokenizer.decode([255] ) == '' ) def UpperCamelCase_ ( self ): '''simple docstring''' pass def UpperCamelCase_ ( self ): '''simple docstring''' pass def UpperCamelCase_ ( self ): '''simple docstring''' pass def UpperCamelCase_ ( self ): '''simple docstring''' pass def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = self.get_tokenizers(fast=A, do_lower_case=A ) for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}" ): SCREAMING_SNAKE_CASE : Optional[Any] = ['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 'x', 't', '</s>'] SCREAMING_SNAKE_CASE : List[str] = tokenizer.convert_tokens_to_string(A ) self.assertIsInstance(A, A ) def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}" ): SCREAMING_SNAKE_CASE : Union[str, Any] = [ 'bos_token', 'eos_token', 'unk_token', 'sep_token', 'pad_token', 'cls_token', 'mask_token', ] SCREAMING_SNAKE_CASE : Any = 0 SCREAMING_SNAKE_CASE : Tuple = tokenizer.convert_ids_to_tokens( A, skip_special_tokens=A ) for attr in attributes_list: setattr(A, attr + '_id', A ) self.assertEqual(getattr(A, A ), A ) self.assertEqual(getattr(A, attr + '_id' ), A ) setattr(A, attr + '_id', A ) self.assertEqual(getattr(A, A ), A ) self.assertEqual(getattr(A, attr + '_id' ), A ) setattr(A, 'additional_special_tokens_ids', [] ) self.assertListEqual(getattr(A, 'additional_special_tokens' ), [] ) self.assertListEqual(getattr(A, 'additional_special_tokens_ids' ), [] ) setattr(A, 'additional_special_tokens_ids', [token_id_to_test_setters] ) self.assertListEqual(getattr(A, 'additional_special_tokens' ), [token_to_test_setters] ) self.assertListEqual(getattr(A, 'additional_special_tokens_ids' ), [token_id_to_test_setters] )
28
"""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
0
"""simple docstring""" from cva import destroyAllWindows, imread, imshow, waitKey def lowercase ( lowerCAmelCase__ ): # getting number of pixels in the image lowerCamelCase_ , lowerCamelCase_ = img.shape[0], img.shape[1] # converting each pixel's color to its negative for i in range(lowerCAmelCase__ ): for j in range(lowerCAmelCase__ ): lowerCamelCase_ = [255, 255, 255] - img[i][j] return img if __name__ == "__main__": # read original image A_ = imread("""image_data/lena.jpg""", 1) # convert to its negative A_ = convert_to_negative(img) # show result image imshow("""negative of original image""", img) waitKey(0) destroyAllWindows()
29
"""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
0
import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness __a = '\\n@misc{chen2021evaluating,\n title={Evaluating Large Language Models Trained on Code},\n author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \\nand Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \\nand Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \\nand Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \\nand Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \\nand Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \\nand Mohammad Bavarian and Clemens Winter and Philippe Tillet \\nand Felipe Petroski Such and Dave Cummings and Matthias Plappert \\nand Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \\nand William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \\nand Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \\nand William Saunders and Christopher Hesse and Andrew N. Carr \\nand Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \\nand Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \\nand Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \\nand Sam McCandlish and Ilya Sutskever and Wojciech Zaremba},\n year={2021},\n eprint={2107.03374},\n archivePrefix={arXiv},\n primaryClass={cs.LG}\n}\n' __a = '\\nThis metric implements the evaluation harness for the HumanEval problem solving dataset\ndescribed in the paper "Evaluating Large Language Models Trained on Code"\n(https://arxiv.org/abs/2107.03374).\n' __a = '\nCalculates how good are predictions given some references, using certain scores\nArgs:\n predictions: list of candidates to evaluate. Each candidates should be a list\n of strings with several code candidates to solve the problem.\n references: a list with a test for each prediction. Each test should evaluate the\n correctness of a code candidate.\n k: number of code candidates to consider in the evaluation (Default: [1, 10, 100])\n num_workers: number of workers used to evaluate the canidate programs (Default: 4).\n timeout:\nReturns:\n pass_at_k: dict with pass rates for each k\n results: dict with granular results of each unittest\nExamples:\n >>> code_eval = datasets.load_metric("code_eval")\n >>> test_cases = ["assert add(2,3)==5"]\n >>> candidates = [["def add(a,b): return a*b", "def add(a, b): return a+b"]]\n >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2])\n >>> print(pass_at_k)\n {\'pass@1\': 0.5, \'pass@2\': 1.0}\n' __a = '\n################################################################################\n !!!WARNING!!!\n################################################################################\nThe "code_eval" metric executes untrusted model-generated code in Python.\nAlthough it is highly unlikely that model-generated code will do something\novertly malicious in response to this test suite, model-generated code may act\ndestructively due to a lack of model capability or alignment.\nUsers are strongly encouraged to sandbox this evaluation suite so that it\ndoes not perform destructive actions on their host or network. For more\ninformation on how OpenAI sandboxes its code, see the paper "Evaluating Large\nLanguage Models Trained on Code" (https://arxiv.org/abs/2107.03374).\n\nOnce you have read this disclaimer and taken appropriate precautions,\nset the environment variable HF_ALLOW_CODE_EVAL="1". Within Python you can to this\nwith:\n\n>>> import os\n>>> os.environ["HF_ALLOW_CODE_EVAL"] = "1"\n\n################################################################################\\n' __a = 'The MIT License\n\nCopyright (c) OpenAI (https://openai.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the "Software"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __a( datasets.Metric ): """simple docstring""" def a__ ( self ) -> Optional[Any]: return datasets.MetricInfo( # This is the description that will appear on the metrics page. description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''' ) ), '''references''': datasets.Value('''string''' ), } ) ,homepage='''https://github.com/openai/human-eval''' ,codebase_urls=['''https://github.com/openai/human-eval'''] ,reference_urls=['''https://github.com/openai/human-eval'''] ,license=_LICENSE ,) def a__ ( self ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE=[1, 10, 100] ,_SCREAMING_SNAKE_CASE=4 ,_SCREAMING_SNAKE_CASE=3.0 ) -> int: if os.getenv('''HF_ALLOW_CODE_EVAL''' ,0 ) != "1": raise ValueError(_WARNING ) if os.name == "nt": raise NotImplementedError('''This metric is currently not supported on Windows.''' ) with ThreadPoolExecutor(max_workers=_SCREAMING_SNAKE_CASE ) as executor: UpperCAmelCase_ : Union[str, Any] = [] UpperCAmelCase_ : List[Any] = Counter() UpperCAmelCase_ : Any = 0 UpperCAmelCase_ : Union[str, Any] = defaultdict(_SCREAMING_SNAKE_CASE ) for task_id, (candidates, test_case) in enumerate(zip(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) ): for candidate in candidates: UpperCAmelCase_ : Union[str, Any] = candidate + '''\n''' + test_case UpperCAmelCase_ : Any = (test_program, timeout, task_id, completion_id[task_id]) UpperCAmelCase_ : List[str] = executor.submit(_SCREAMING_SNAKE_CASE ,*_SCREAMING_SNAKE_CASE ) futures.append(_SCREAMING_SNAKE_CASE ) completion_id[task_id] += 1 n_samples += 1 for future in as_completed(_SCREAMING_SNAKE_CASE ): UpperCAmelCase_ : Tuple = future.result() results[result["task_id"]].append((result['''completion_id'''], result) ) UpperCAmelCase_, UpperCAmelCase_ : str = [], [] for result in results.values(): result.sort() UpperCAmelCase_ : Dict = [r[1]['''passed'''] for r in result] total.append(len(_SCREAMING_SNAKE_CASE ) ) correct.append(sum(_SCREAMING_SNAKE_CASE ) ) UpperCAmelCase_ : List[Any] = np.array(_SCREAMING_SNAKE_CASE ) UpperCAmelCase_ : int = np.array(_SCREAMING_SNAKE_CASE ) UpperCAmelCase_ : Optional[Any] = k UpperCAmelCase_ : str = {f'''pass@{k}''': estimate_pass_at_k(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ).mean() for k in ks if (total >= k).all()} return pass_at_k, results def lowerCamelCase__ ( _lowercase , _lowercase , _lowercase ): '''simple docstring''' def estimator(_lowercase , _lowercase , _lowercase ) -> float: if n - c < k: return 1.0 return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1 , n + 1 ) ) if isinstance(_lowercase , _lowercase ): UpperCAmelCase_ : Union[str, Any] = itertools.repeat(_lowercase , len(_lowercase ) ) else: assert len(_lowercase ) == len(_lowercase ) UpperCAmelCase_ : Optional[Any] = iter(_lowercase ) return np.array([estimator(int(_lowercase ) , int(_lowercase ) , _lowercase ) for n, c in zip(_lowercase , _lowercase )] )
30
"""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
0
import numpy as np from nltk.translate import meteor_score import datasets from datasets.config import importlib_metadata, version lowerCamelCase__ : Dict = version.parse(importlib_metadata.version('nltk')) if NLTK_VERSION >= version.Version('3.6.4'): from nltk import word_tokenize lowerCamelCase__ : List[Any] = '\\n@inproceedings{banarjee2005,\n title = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments},\n author = {Banerjee, Satanjeev and Lavie, Alon},\n booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization},\n month = jun,\n year = {2005},\n address = {Ann Arbor, Michigan},\n publisher = {Association for Computational Linguistics},\n url = {https://www.aclweb.org/anthology/W05-0909},\n pages = {65--72},\n}\n' lowerCamelCase__ : Optional[int] = '\\nMETEOR, an automatic metric for machine translation evaluation\nthat is based on a generalized concept of unigram matching between the\nmachine-produced translation and human-produced reference translations.\nUnigrams can be matched based on their surface forms, stemmed forms,\nand meanings; furthermore, METEOR can be easily extended to include more\nadvanced matching strategies. Once all generalized unigram matches\nbetween the two strings have been found, METEOR computes a score for\nthis matching using a combination of unigram-precision, unigram-recall, and\na measure of fragmentation that is designed to directly capture how\nwell-ordered the matched words in the machine translation are in relation\nto the reference.\n\nMETEOR gets an R correlation value of 0.347 with human evaluation on the Arabic\ndata and 0.331 on the Chinese data. This is shown to be an improvement on\nusing simply unigram-precision, unigram-recall and their harmonic F1\ncombination.\n' lowerCamelCase__ : int = '\nComputes METEOR score of translated segments against one or more references.\nArgs:\n predictions: list of predictions to score. Each prediction\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\n alpha: Parameter for controlling relative weights of precision and recall. default: 0.9\n beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3\n gamma: Relative weight assigned to fragmentation penalty. default: 0.5\nReturns:\n \'meteor\': meteor score.\nExamples:\n\n >>> meteor = datasets.load_metric(\'meteor\')\n >>> predictions = ["It is a guide to action which ensures that the military always obeys the commands of the party"]\n >>> references = ["It is a guide to action that ensures that the military will forever heed Party commands"]\n >>> results = meteor.compute(predictions=predictions, references=references)\n >>> print(round(results["meteor"], 4))\n 0.6944\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCamelCase_ ( datasets.Metric ): '''simple docstring''' def lowerCAmelCase_ ( self : List[Any] ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence' ), 'references': datasets.Value('string' , id='sequence' ), } ) , codebase_urls=['https://github.com/nltk/nltk/blob/develop/nltk/translate/meteor_score.py'] , reference_urls=[ 'https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score', 'https://en.wikipedia.org/wiki/METEOR', ] , ) def lowerCAmelCase_ ( self : Optional[int] , _lowerCAmelCase : Optional[Any] ): import nltk nltk.download('wordnet' ) if NLTK_VERSION >= version.Version('3.6.5' ): nltk.download('punkt' ) if NLTK_VERSION >= version.Version('3.6.6' ): nltk.download('omw-1.4' ) def lowerCAmelCase_ ( self : List[Any] , _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : Tuple , _lowerCAmelCase : Dict=0.9 , _lowerCAmelCase : Tuple=3 , _lowerCAmelCase : List[str]=0.5 ): if NLTK_VERSION >= version.Version('3.6.5' ): SCREAMING_SNAKE_CASE_ = [ meteor_score.single_meteor_score( word_tokenize(_lowerCAmelCase ) , word_tokenize(_lowerCAmelCase ) , alpha=_lowerCAmelCase , beta=_lowerCAmelCase , gamma=_lowerCAmelCase ) for ref, pred in zip(_lowerCAmelCase , _lowerCAmelCase ) ] else: SCREAMING_SNAKE_CASE_ = [ meteor_score.single_meteor_score(_lowerCAmelCase , _lowerCAmelCase , alpha=_lowerCAmelCase , beta=_lowerCAmelCase , gamma=_lowerCAmelCase ) for ref, pred in zip(_lowerCAmelCase , _lowerCAmelCase ) ] return {"meteor": np.mean(_lowerCAmelCase )}
31
"""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
0
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ = logging.get_logger(__name__) UpperCAmelCase_ = { "microsoft/wavlm-base": "https://huggingface.co/microsoft/wavlm-base/resolve/main/config.json", # See all WavLM models at https://huggingface.co/models?filter=wavlm } class __UpperCamelCase ( A__ ): __A : Union[str, Any] = """wavlm""" def __init__( self , _UpperCamelCase=32 , _UpperCamelCase=768 , _UpperCamelCase=12 , _UpperCamelCase=12 , _UpperCamelCase=3072 , _UpperCamelCase="gelu" , _UpperCamelCase=0.1 , _UpperCamelCase=0.1 , _UpperCamelCase=0.1 , _UpperCamelCase=0.0 , _UpperCamelCase=0.1 , _UpperCamelCase=0.1 , _UpperCamelCase=0.02 , _UpperCamelCase=1e-5 , _UpperCamelCase="group" , _UpperCamelCase="gelu" , _UpperCamelCase=(512, 512, 512, 512, 512, 512, 512) , _UpperCamelCase=(5, 2, 2, 2, 2, 2, 2) , _UpperCamelCase=(10, 3, 3, 3, 3, 2, 2) , _UpperCamelCase=False , _UpperCamelCase=128 , _UpperCamelCase=16 , _UpperCamelCase=320 , _UpperCamelCase=800 , _UpperCamelCase=False , _UpperCamelCase=True , _UpperCamelCase=0.05 , _UpperCamelCase=10 , _UpperCamelCase=2 , _UpperCamelCase=0.0 , _UpperCamelCase=10 , _UpperCamelCase=320 , _UpperCamelCase=2 , _UpperCamelCase=0.1 , _UpperCamelCase=100 , _UpperCamelCase=256 , _UpperCamelCase=256 , _UpperCamelCase=0.1 , _UpperCamelCase="mean" , _UpperCamelCase=False , _UpperCamelCase=False , _UpperCamelCase=256 , _UpperCamelCase=(512, 512, 512, 512, 1500) , _UpperCamelCase=(5, 3, 3, 1, 1) , _UpperCamelCase=(1, 2, 3, 1, 1) , _UpperCamelCase=512 , _UpperCamelCase=80 , _UpperCamelCase=0 , _UpperCamelCase=1 , _UpperCamelCase=2 , _UpperCamelCase=False , _UpperCamelCase=3 , _UpperCamelCase=2 , _UpperCamelCase=3 , _UpperCamelCase=None , **_UpperCamelCase , ): super().__init__(**_UpperCamelCase , pad_token_id=_UpperCamelCase , bos_token_id=_UpperCamelCase , eos_token_id=_UpperCamelCase ) _UpperCAmelCase = hidden_size _UpperCAmelCase = feat_extract_norm _UpperCAmelCase = feat_extract_activation _UpperCAmelCase = list(_UpperCamelCase ) _UpperCAmelCase = list(_UpperCamelCase ) _UpperCAmelCase = list(_UpperCamelCase ) _UpperCAmelCase = conv_bias _UpperCAmelCase = num_buckets _UpperCAmelCase = max_bucket_distance _UpperCAmelCase = num_conv_pos_embeddings _UpperCAmelCase = num_conv_pos_embedding_groups _UpperCAmelCase = len(self.conv_dim ) _UpperCAmelCase = num_hidden_layers _UpperCAmelCase = intermediate_size _UpperCAmelCase = hidden_act _UpperCAmelCase = num_attention_heads _UpperCAmelCase = hidden_dropout _UpperCAmelCase = attention_dropout _UpperCAmelCase = activation_dropout _UpperCAmelCase = feat_proj_dropout _UpperCAmelCase = final_dropout _UpperCAmelCase = layerdrop _UpperCAmelCase = layer_norm_eps _UpperCAmelCase = initializer_range _UpperCAmelCase = num_ctc_classes _UpperCAmelCase = vocab_size _UpperCAmelCase = do_stable_layer_norm _UpperCAmelCase = use_weighted_layer_sum _UpperCAmelCase = classifier_proj_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)`, but is `len(config.conv_dim) =''' f''' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,''' f''' `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 _UpperCAmelCase = apply_spec_augment _UpperCAmelCase = mask_time_prob _UpperCAmelCase = mask_time_length _UpperCAmelCase = mask_time_min_masks _UpperCAmelCase = mask_feature_prob _UpperCAmelCase = mask_feature_length # parameters for pretraining with codevector quantized representations _UpperCAmelCase = num_codevectors_per_group _UpperCAmelCase = num_codevector_groups _UpperCAmelCase = contrastive_logits_temperature _UpperCAmelCase = num_negatives _UpperCAmelCase = codevector_dim _UpperCAmelCase = proj_codevector_dim _UpperCAmelCase = diversity_loss_weight # ctc loss _UpperCAmelCase = ctc_loss_reduction _UpperCAmelCase = ctc_zero_infinity # adapter _UpperCAmelCase = add_adapter _UpperCAmelCase = adapter_kernel_size _UpperCAmelCase = adapter_stride _UpperCAmelCase = num_adapter_layers _UpperCAmelCase = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. _UpperCAmelCase = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. _UpperCAmelCase = list(_UpperCamelCase ) _UpperCAmelCase = list(_UpperCamelCase ) _UpperCAmelCase = list(_UpperCamelCase ) _UpperCAmelCase = xvector_output_dim @property def UpperCamelCase( self ): return functools.reduce(operator.mul , self.conv_stride , 1 )
32
"""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
0
import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer import diffusers from diffusers import ( AutoencoderKL, EulerDiscreteScheduler, StableDiffusionLatentUpscalePipeline, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.schedulers import KarrasDiffusionSchedulers from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() def SCREAMING_SNAKE_CASE ( __lowerCAmelCase ) -> List[Any]: snake_case__ = [tensor.shape for tensor in tensor_list] return all(shape == shapes[0] for shape in shapes[1:] ) class __magic_name__ (snake_case_ ,snake_case_ ,snake_case_ ,unittest.TestCase ): '''simple docstring''' __lowercase : Dict = StableDiffusionLatentUpscalePipeline __lowercase : List[str] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - { 'height', 'width', 'cross_attention_kwargs', 'negative_prompt_embeds', 'prompt_embeds', } __lowercase : List[Any] = PipelineTesterMixin.required_optional_params - {'num_images_per_prompt'} __lowercase : Any = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS __lowercase : int = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess __lowercase : List[Any] = frozenset([] ) __lowercase : Any = True @property def SCREAMING_SNAKE_CASE__ ( self:List[str] ): snake_case__ = 1 snake_case__ = 4 snake_case__ = (16, 16) snake_case__ = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(_a ) return image def SCREAMING_SNAKE_CASE__ ( self:Union[str, Any] ): torch.manual_seed(0 ) snake_case__ = UNetaDConditionModel( act_fn='''gelu''' , attention_head_dim=8 , norm_num_groups=_a , block_out_channels=[32, 32, 64, 64] , time_cond_proj_dim=1_60 , conv_in_kernel=1 , conv_out_kernel=1 , cross_attention_dim=32 , down_block_types=( '''KDownBlock2D''', '''KCrossAttnDownBlock2D''', '''KCrossAttnDownBlock2D''', '''KCrossAttnDownBlock2D''', ) , in_channels=8 , mid_block_type=_a , only_cross_attention=_a , out_channels=5 , resnet_time_scale_shift='''scale_shift''' , time_embedding_type='''fourier''' , timestep_post_act='''gelu''' , up_block_types=('''KCrossAttnUpBlock2D''', '''KCrossAttnUpBlock2D''', '''KCrossAttnUpBlock2D''', '''KUpBlock2D''') , ) snake_case__ = AutoencoderKL( block_out_channels=[32, 32, 64, 64] , in_channels=3 , out_channels=3 , down_block_types=[ '''DownEncoderBlock2D''', '''DownEncoderBlock2D''', '''DownEncoderBlock2D''', '''DownEncoderBlock2D''', ] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''', '''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) snake_case__ = EulerDiscreteScheduler(prediction_type='''sample''' ) snake_case__ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , hidden_act='''quick_gelu''' , projection_dim=5_12 , ) snake_case__ = CLIPTextModel(_a ) snake_case__ = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) snake_case__ = { '''unet''': model.eval(), '''vae''': vae.eval(), '''scheduler''': scheduler, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, } return components def SCREAMING_SNAKE_CASE__ ( self:List[Any] , _a:Optional[Any] , _a:List[str]=0 ): if str(_a ).startswith('''mps''' ): snake_case__ = torch.manual_seed(_a ) else: snake_case__ = torch.Generator(device=_a ).manual_seed(_a ) snake_case__ = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': self.dummy_image.cpu(), '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def SCREAMING_SNAKE_CASE__ ( self:str ): snake_case__ = '''cpu''' snake_case__ = self.get_dummy_components() snake_case__ = self.pipeline_class(**_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) snake_case__ = self.get_dummy_inputs(_a ) snake_case__ = pipe(**_a ).images snake_case__ = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 2_56, 2_56, 3) ) snake_case__ = np.array( [0.47222412, 0.41921633, 0.44717434, 0.46874192, 0.42588258, 0.46150726, 0.4677534, 0.45583832, 0.48579055] ) snake_case__ = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_a , 1e-3 ) def SCREAMING_SNAKE_CASE__ ( self:Union[str, Any] ): super().test_attention_slicing_forward_pass(expected_max_diff=7e-3 ) def SCREAMING_SNAKE_CASE__ ( self:List[Any] ): super().test_cpu_offload_forward_pass(expected_max_diff=3e-3 ) def SCREAMING_SNAKE_CASE__ ( self:str ): super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE__ ( self:Any ): super().test_inference_batch_single_identical(expected_max_diff=7e-3 ) def SCREAMING_SNAKE_CASE__ ( self:Tuple ): super().test_pt_np_pil_outputs_equivalent(expected_max_diff=3e-3 ) def SCREAMING_SNAKE_CASE__ ( self:Dict ): super().test_save_load_local(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE__ ( self:str ): super().test_save_load_optional_components(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE__ ( self:Any ): snake_case__ = [ '''DDIMScheduler''', '''DDPMScheduler''', '''PNDMScheduler''', '''HeunDiscreteScheduler''', '''EulerAncestralDiscreteScheduler''', '''KDPM2DiscreteScheduler''', '''KDPM2AncestralDiscreteScheduler''', '''DPMSolverSDEScheduler''', ] snake_case__ = self.get_dummy_components() snake_case__ = self.pipeline_class(**_a ) # make sure that PNDM does not need warm-up pipe.scheduler.register_to_config(skip_prk_steps=_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) snake_case__ = self.get_dummy_inputs(_a ) snake_case__ = 2 snake_case__ = [] for scheduler_enum in KarrasDiffusionSchedulers: if scheduler_enum.name in skip_schedulers: # no sigma schedulers are not supported # no schedulers continue snake_case__ = getattr(_a , scheduler_enum.name ) snake_case__ = scheduler_cls.from_config(pipe.scheduler.config ) snake_case__ = pipe(**_a )[0] outputs.append(_a ) assert check_same_shape(_a ) @require_torch_gpu @slow class __magic_name__ (unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self:Optional[Any] ): super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self:str ): snake_case__ = torch.manual_seed(33 ) snake_case__ = StableDiffusionPipeline.from_pretrained('''CompVis/stable-diffusion-v1-4''' , torch_dtype=torch.floataa ) pipe.to('''cuda''' ) snake_case__ = StableDiffusionLatentUpscalePipeline.from_pretrained( '''stabilityai/sd-x2-latent-upscaler''' , torch_dtype=torch.floataa ) upscaler.to('''cuda''' ) snake_case__ = '''a photo of an astronaut high resolution, unreal engine, ultra realistic''' snake_case__ = pipe(_a , generator=_a , output_type='''latent''' ).images snake_case__ = upscaler( prompt=_a , image=_a , num_inference_steps=20 , guidance_scale=0 , generator=_a , output_type='''np''' , ).images[0] snake_case__ = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/astronaut_1024.npy''' ) assert np.abs((expected_image - image).mean() ) < 5e-2 def SCREAMING_SNAKE_CASE__ ( self:Optional[int] ): snake_case__ = torch.manual_seed(33 ) snake_case__ = StableDiffusionLatentUpscalePipeline.from_pretrained( '''stabilityai/sd-x2-latent-upscaler''' , torch_dtype=torch.floataa ) upscaler.to('''cuda''' ) snake_case__ = '''the temple of fire by Ross Tran and Gerardo Dottori, oil on canvas''' snake_case__ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_512.png''' ) snake_case__ = upscaler( prompt=_a , image=_a , num_inference_steps=20 , guidance_scale=0 , generator=_a , output_type='''np''' , ).images[0] snake_case__ = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_1024.npy''' ) assert np.abs((expected_image - image).max() ) < 5e-2
33
"""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
0
"""simple docstring""" # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. SCREAMING_SNAKE_CASE_ = abspath(join(dirname(dirname(__file__)), 'src')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='ignore', category=FutureWarning) def __snake_case ( _lowercase ): """simple docstring""" from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(_lowercase ) def __snake_case ( _lowercase ): """simple docstring""" from diffusers.utils.testing_utils import pytest_terminal_summary_main UpperCamelCase = terminalreporter.config.getoption('''--make-reports''' ) if make_reports: pytest_terminal_summary_main(_lowercase ,id=_lowercase )
34
"""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
0
import warnings from ...utils import logging from .image_processing_deformable_detr import DeformableDetrImageProcessor a_ :List[Any] = logging.get_logger(__name__) class lowercase ( _UpperCAmelCase ): def __init__( self : List[str] , *_lowercase : Tuple , **_lowercase : Optional[Any] ): warnings.warn( '''The class DeformableDetrFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use DeformableDetrImageProcessor instead.''' , _lowercase , ) super().__init__(*_lowercase , **_lowercase )
35
"""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
0
# coding=utf-8 # Copyright 2023 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # this script dumps information about the environment import os import platform import sys __lowercase : Optional[int] = '''3''' print('''Python version:''', sys.version) print('''OS platform:''', platform.platform()) print('''OS architecture:''', platform.machine()) try: import torch print('''Torch version:''', torch.__version__) print('''Cuda available:''', torch.cuda.is_available()) print('''Cuda version:''', torch.version.cuda) print('''CuDNN version:''', torch.backends.cudnn.version()) print('''Number of GPUs available:''', torch.cuda.device_count()) except ImportError: print('''Torch version:''', None) try: import transformers print('''transformers version:''', transformers.__version__) except ImportError: print('''transformers version:''', None)
36
"""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
0
import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin UpperCamelCase : Tuple = random.Random() if is_torch_available(): import torch def UpperCamelCase_ ( __a , __a=1.0 , __a=None , __a=None ) -> Dict: if rng is None: a__ : int = global_rng a__ : Union[str, Any] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class A__ ( unittest.TestCase ): """simple docstring""" def __init__( self : List[Any] , lowerCamelCase__ : List[Any] , lowerCamelCase__ : Tuple=7 , lowerCamelCase__ : Tuple=400 , lowerCamelCase__ : List[str]=2_000 , lowerCamelCase__ : Union[str, Any]=1 , lowerCamelCase__ : Optional[Any]=0.0 , lowerCamelCase__ : Any=16_000 , lowerCamelCase__ : str=True , lowerCamelCase__ : List[str]=True , ): a__ : List[Any] = parent a__ : Dict = batch_size a__ : List[Any] = min_seq_length a__ : Tuple = max_seq_length a__ : Tuple = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) a__ : Dict = feature_size a__ : Any = padding_value a__ : List[Any] = sampling_rate a__ : Tuple = return_attention_mask a__ : int = do_normalize def _UpperCamelCase( self : Tuple ): return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def _UpperCamelCase( self : str , lowerCamelCase__ : str=False , lowerCamelCase__ : Optional[Any]=False ): def _flatten(lowerCamelCase__ : Dict ): return list(itertools.chain(*lowerCamelCase__ ) ) if equal_length: a__ : List[str] = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size a__ : Tuple = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: a__ : Any = [np.asarray(lowerCamelCase__ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class A__ ( A__ , unittest.TestCase ): """simple docstring""" _lowercase = ASTFeatureExtractor def _UpperCamelCase( self : Dict ): a__ : List[Any] = ASTFeatureExtractionTester(self ) def _UpperCamelCase( self : str ): # Tests that all call wrap to encode_plus and batch_encode_plus a__ : Optional[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 a__ : List[Any] = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] a__ : str = [np.asarray(lowerCamelCase__ ) for speech_input in speech_inputs] # Test not batched input a__ : Tuple = feat_extract(speech_inputs[0] , return_tensors="np" ).input_values a__ : Union[str, Any] = feat_extract(np_speech_inputs[0] , return_tensors="np" ).input_values self.assertTrue(np.allclose(lowerCamelCase__ , lowerCamelCase__ , atol=1E-3 ) ) # Test batched a__ : List[str] = feat_extract(lowerCamelCase__ , padding=lowerCamelCase__ , return_tensors="np" ).input_values a__ : str = feat_extract(lowerCamelCase__ , padding=lowerCamelCase__ , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(lowerCamelCase__ , lowerCamelCase__ ): self.assertTrue(np.allclose(lowerCamelCase__ , lowerCamelCase__ , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. a__ : str = [floats_list((1, x) )[0] for x in (800, 800, 800)] a__ : List[Any] = np.asarray(lowerCamelCase__ ) a__ : int = feat_extract(lowerCamelCase__ , return_tensors="np" ).input_values a__ : str = feat_extract(lowerCamelCase__ , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(lowerCamelCase__ , lowerCamelCase__ ): self.assertTrue(np.allclose(lowerCamelCase__ , lowerCamelCase__ , atol=1E-3 ) ) @require_torch def _UpperCamelCase( self : str ): import torch a__ : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) a__ : int = np.random.rand(100 ).astype(np.floataa ) a__ : List[str] = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: a__ : Union[str, Any] = feature_extractor.pad([{"input_values": inputs}] , return_tensors="np" ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) a__ : str = feature_extractor.pad([{"input_values": inputs}] , return_tensors="pt" ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def _UpperCamelCase( self : Dict , lowerCamelCase__ : List[str] ): from datasets import load_dataset a__ : Optional[Any] = load_dataset("hf-internal-testing/librispeech_asr_dummy" , "clean" , split="validation" ) # automatic decoding with librispeech a__ : Union[str, Any] = ds.sort("id" ).select(range(lowerCamelCase__ ) )[:num_samples]["audio"] return [x["array"] for x in speech_samples] @require_torch def _UpperCamelCase( self : str ): # fmt: off a__ : List[Any] = torch.tensor( [-0.9894, -1.2776, -0.9066, -1.2776, -0.9349, -1.2609, -1.0386, -1.2776, -1.1561, -1.2776, -1.2052, -1.2723, -1.2190, -1.2132, -1.2776, -1.1133, -1.1953, -1.1343, -1.1584, -1.2203, -1.1770, -1.2474, -1.2381, -1.1936, -0.9270, -0.8317, -0.8049, -0.7706, -0.7565, -0.7869] ) # fmt: on a__ : Union[str, Any] = self._load_datasamples(1 ) a__ : Dict = ASTFeatureExtractor() a__ : List[str] = feature_extractor(lowerCamelCase__ , return_tensors="pt" ).input_values self.assertEquals(input_values.shape , (1, 1_024, 128) ) self.assertTrue(torch.allclose(input_values[0, 0, :30] , lowerCamelCase__ , atol=1E-4 ) )
37
"""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
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, CycleDiffusionPipeline, DDIMScheduler, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = CycleDiffusionPipeline lowerCamelCase__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - { '''negative_prompt''', '''height''', '''width''', '''negative_prompt_embeds''', } lowerCamelCase__ = PipelineTesterMixin.required_optional_params - {'''latents'''} lowerCamelCase__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''source_prompt'''} ) lowerCamelCase__ = IMAGE_TO_IMAGE_IMAGE_PARAMS lowerCamelCase__ = IMAGE_TO_IMAGE_IMAGE_PARAMS def __UpperCamelCase ( self ): torch.manual_seed(0 ) snake_case__ : Tuple = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=3_2 , ) snake_case__ : List[str] = DDIMScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , num_train_timesteps=1_0_0_0 , clip_sample=__SCREAMING_SNAKE_CASE , set_alpha_to_one=__SCREAMING_SNAKE_CASE , ) torch.manual_seed(0 ) snake_case__ : List[Any] = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) snake_case__ : Any = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) snake_case__ : Any = CLIPTextModel(__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) snake_case__ : List[Any] = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=0 ): snake_case__ : List[str] = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = image / 2 + 0.5 if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): snake_case__ : Union[str, Any] = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: snake_case__ : int = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) snake_case__ : Any = { """prompt""": """An astronaut riding an elephant""", """source_prompt""": """An astronaut riding a horse""", """image""": image, """generator""": generator, """num_inference_steps""": 2, """eta""": 0.1, """strength""": 0.8, """guidance_scale""": 3, """source_guidance_scale""": 1, """output_type""": """numpy""", } return inputs def __UpperCamelCase ( self ): snake_case__ : Tuple = """cpu""" # ensure determinism for the device-dependent torch.Generator snake_case__ : Union[str, Any] = self.get_dummy_components() snake_case__ : int = CycleDiffusionPipeline(**__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) snake_case__ : Any = pipe(**__SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = output.images snake_case__ : Dict = images[0, -3:, -3:, -1] assert images.shape == (1, 3_2, 3_2, 3) snake_case__ : Optional[int] = np.array([0.4459, 0.4943, 0.4544, 0.6643, 0.5474, 0.4327, 0.5701, 0.5959, 0.5179] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf(torch_device != """cuda""" , """This test requires a GPU""" ) def __UpperCamelCase ( self ): snake_case__ : str = self.get_dummy_components() for name, module in components.items(): if hasattr(__SCREAMING_SNAKE_CASE , """half""" ): snake_case__ : Dict = module.half() snake_case__ : Any = CycleDiffusionPipeline(**__SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = pipe(**__SCREAMING_SNAKE_CASE ) snake_case__ : int = output.images snake_case__ : Dict = images[0, -3:, -3:, -1] assert images.shape == (1, 3_2, 3_2, 3) snake_case__ : Tuple = np.array([0.3506, 0.4543, 0.446, 0.4575, 0.5195, 0.4155, 0.5273, 0.518, 0.4116] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @skip_mps def __UpperCamelCase ( self ): return super().test_save_load_local() @unittest.skip("""non-deterministic pipeline""" ) def __UpperCamelCase ( self ): return super().test_inference_batch_single_identical() @skip_mps def __UpperCamelCase ( self ): return super().test_dict_tuple_outputs_equivalent() @skip_mps def __UpperCamelCase ( self ): return super().test_save_load_optional_components() @skip_mps def __UpperCamelCase ( self ): return super().test_attention_slicing_forward_pass() @slow @require_torch_gpu class __snake_case ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCamelCase ( self ): snake_case__ : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/cycle-diffusion/black_colored_car.png""" ) snake_case__ : List[str] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car_fp16.npy""" ) snake_case__ : Dict = init_image.resize((5_1_2, 5_1_2) ) snake_case__ : Tuple = """CompVis/stable-diffusion-v1-4""" snake_case__ : Any = DDIMScheduler.from_pretrained(__SCREAMING_SNAKE_CASE , subfolder="""scheduler""" ) snake_case__ : Optional[Any] = CycleDiffusionPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , revision="""fp16""" ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() snake_case__ : Optional[int] = """A black colored car""" snake_case__ : int = """A blue colored car""" snake_case__ : Optional[Any] = torch.manual_seed(0 ) snake_case__ : Any = pipe( prompt=__SCREAMING_SNAKE_CASE , source_prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , num_inference_steps=1_0_0 , eta=0.1 , strength=0.85 , guidance_scale=3 , source_guidance_scale=1 , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) snake_case__ : List[Any] = output.images # the values aren't exactly equal, but the images look the same visually assert np.abs(image - expected_image ).max() < 5e-1 def __UpperCamelCase ( self ): snake_case__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/cycle-diffusion/black_colored_car.png""" ) snake_case__ : Dict = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car.npy""" ) snake_case__ : Any = init_image.resize((5_1_2, 5_1_2) ) snake_case__ : List[str] = """CompVis/stable-diffusion-v1-4""" snake_case__ : Dict = DDIMScheduler.from_pretrained(__SCREAMING_SNAKE_CASE , subfolder="""scheduler""" ) snake_case__ : Dict = CycleDiffusionPipeline.from_pretrained(__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() snake_case__ : Tuple = """A black colored car""" snake_case__ : List[str] = """A blue colored car""" snake_case__ : Tuple = torch.manual_seed(0 ) snake_case__ : List[str] = pipe( prompt=__SCREAMING_SNAKE_CASE , source_prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , num_inference_steps=1_0_0 , eta=0.1 , strength=0.85 , guidance_scale=3 , source_guidance_scale=1 , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) snake_case__ : int = output.images assert np.abs(image - expected_image ).max() < 2e-2
38
"""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
0
from __future__ import annotations import math def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ ): if num <= 0: snake_case_ = F'''{num}: Invalid input, please enter a positive integer.''' raise ValueError(SCREAMING_SNAKE_CASE__ ) snake_case_ = [True] * (num + 1) snake_case_ = [] snake_case_ = 2 snake_case_ = int(math.sqrt(SCREAMING_SNAKE_CASE__ ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(SCREAMING_SNAKE_CASE__ ) # Set multiples of start be False for i in range(start * start , num + 1 , SCREAMING_SNAKE_CASE__ ): if sieve[i] is True: snake_case_ = False start += 1 for j in range(end + 1 , num + 1 ): if sieve[j] is True: prime.append(SCREAMING_SNAKE_CASE__ ) return prime if __name__ == "__main__": print(prime_sieve(int(input('''Enter a positive integer: ''').strip())))
39
"""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
0
from unittest.mock import Mock, patch from file_transfer.send_file import send_file @patch('socket.socket' ) @patch('builtins.open' ) def UpperCamelCase ( snake_case__ : Dict , snake_case__ : Tuple ) -> Optional[int]: # ===== initialization ===== UpperCamelCase : List[str] = Mock() UpperCamelCase : Any = conn, Mock() UpperCamelCase : Any = iter([1, None] ) UpperCamelCase : Optional[Any] = lambda snake_case__ : next(snake_case__ ) # ===== invoke ===== send_file(filename='mytext.txt' , testing=snake_case__ ) # ===== ensurance ===== sock.assert_called_once() sock.return_value.bind.assert_called_once() sock.return_value.listen.assert_called_once() sock.return_value.accept.assert_called_once() conn.recv.assert_called_once() file.return_value.__enter__.assert_called_once() file.return_value.__enter__.return_value.read.assert_called() conn.send.assert_called_once() conn.close.assert_called_once() sock.return_value.shutdown.assert_called_once() sock.return_value.close.assert_called_once()
40
"""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
0
'''simple docstring''' import os import unittest from transformers import MobileBertTokenizer, MobileBertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class lowercase_ (lowerCamelCase__ , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = MobileBertTokenizer SCREAMING_SNAKE_CASE : int = MobileBertTokenizerFast SCREAMING_SNAKE_CASE : str = True SCREAMING_SNAKE_CASE : Optional[int] = True SCREAMING_SNAKE_CASE : List[Any] = filter_non_english SCREAMING_SNAKE_CASE : Any = 'google/mobilebert-uncased' def SCREAMING_SNAKE_CASE ( self : Any ): super().setUp() __lowercase = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] __lowercase = 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] ) ) __lowercase = [ (tokenizer_def[0], self.pre_trained_model_path, tokenizer_def[2]) # else the 'google/' prefix is stripped for tokenizer_def in self.tokenizers_list ] def SCREAMING_SNAKE_CASE ( self : List[Any] ,lowercase__ : Optional[int] ): __lowercase = '''UNwant\u00E9d,running''' __lowercase = '''unwanted, running''' return input_text, output_text def SCREAMING_SNAKE_CASE ( self : str ): __lowercase = self.tokenizer_class(self.vocab_file ) __lowercase = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(lowercase__ ,['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase__ ) ,[9, 6, 7, 1_2, 1_0, 1_1] ) def SCREAMING_SNAKE_CASE ( self : List[Any] ): if not self.test_rust_tokenizer: return __lowercase = self.get_tokenizer() __lowercase = self.get_rust_tokenizer() __lowercase = '''UNwant\u00E9d,running''' __lowercase = tokenizer.tokenize(lowercase__ ) __lowercase = rust_tokenizer.tokenize(lowercase__ ) self.assertListEqual(lowercase__ ,lowercase__ ) __lowercase = tokenizer.encode(lowercase__ ,add_special_tokens=lowercase__ ) __lowercase = rust_tokenizer.encode(lowercase__ ,add_special_tokens=lowercase__ ) self.assertListEqual(lowercase__ ,lowercase__ ) __lowercase = self.get_rust_tokenizer() __lowercase = tokenizer.encode(lowercase__ ) __lowercase = rust_tokenizer.encode(lowercase__ ) self.assertListEqual(lowercase__ ,lowercase__ ) # With lower casing __lowercase = self.get_tokenizer(do_lower_case=lowercase__ ) __lowercase = self.get_rust_tokenizer(do_lower_case=lowercase__ ) __lowercase = '''UNwant\u00E9d,running''' __lowercase = tokenizer.tokenize(lowercase__ ) __lowercase = rust_tokenizer.tokenize(lowercase__ ) self.assertListEqual(lowercase__ ,lowercase__ ) __lowercase = tokenizer.encode(lowercase__ ,add_special_tokens=lowercase__ ) __lowercase = rust_tokenizer.encode(lowercase__ ,add_special_tokens=lowercase__ ) self.assertListEqual(lowercase__ ,lowercase__ ) __lowercase = self.get_rust_tokenizer() __lowercase = tokenizer.encode(lowercase__ ) __lowercase = rust_tokenizer.encode(lowercase__ ) self.assertListEqual(lowercase__ ,lowercase__ ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): __lowercase = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) ,['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def SCREAMING_SNAKE_CASE ( self : int ): __lowercase = BasicTokenizer(do_lower_case=lowercase__ ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) ,['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) ,['''hello'''] ) def SCREAMING_SNAKE_CASE ( self : Dict ): __lowercase = BasicTokenizer(do_lower_case=lowercase__ ,strip_accents=lowercase__ ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) ,['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) ,['''h\u00E9llo'''] ) def SCREAMING_SNAKE_CASE ( self : int ): __lowercase = BasicTokenizer(do_lower_case=lowercase__ ,strip_accents=lowercase__ ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) ,['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) ,['''hello'''] ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): __lowercase = BasicTokenizer(do_lower_case=lowercase__ ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) ,['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) ,['''hello'''] ) def SCREAMING_SNAKE_CASE ( self : Dict ): __lowercase = BasicTokenizer(do_lower_case=lowercase__ ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) ,['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self : str ): __lowercase = BasicTokenizer(do_lower_case=lowercase__ ,strip_accents=lowercase__ ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) ,['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): __lowercase = BasicTokenizer(do_lower_case=lowercase__ ,strip_accents=lowercase__ ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) ,['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self : int ): __lowercase = BasicTokenizer(do_lower_case=lowercase__ ,never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) ,['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def SCREAMING_SNAKE_CASE ( self : List[Any] ): __lowercase = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing'''] __lowercase = {} for i, token in enumerate(lowercase__ ): __lowercase = i __lowercase = WordpieceTokenizer(vocab=lowercase__ ,unk_token='''[UNK]''' ) self.assertListEqual(tokenizer.tokenize('''''' ) ,[] ) self.assertListEqual(tokenizer.tokenize('''unwanted running''' ) ,['''un''', '''##want''', '''##ed''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.tokenize('''unwantedX running''' ) ,['''[UNK]''', '''runn''', '''##ing'''] ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): self.assertTrue(_is_whitespace(''' ''' ) ) self.assertTrue(_is_whitespace('''\t''' ) ) self.assertTrue(_is_whitespace('''\r''' ) ) self.assertTrue(_is_whitespace('''\n''' ) ) self.assertTrue(_is_whitespace('''\u00A0''' ) ) self.assertFalse(_is_whitespace('''A''' ) ) self.assertFalse(_is_whitespace('''-''' ) ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): self.assertTrue(_is_control('''\u0005''' ) ) self.assertFalse(_is_control('''A''' ) ) self.assertFalse(_is_control(''' ''' ) ) self.assertFalse(_is_control('''\t''' ) ) self.assertFalse(_is_control('''\r''' ) ) def SCREAMING_SNAKE_CASE ( self : int ): self.assertTrue(_is_punctuation('''-''' ) ) self.assertTrue(_is_punctuation('''$''' ) ) self.assertTrue(_is_punctuation('''`''' ) ) self.assertTrue(_is_punctuation('''.''' ) ) self.assertFalse(_is_punctuation('''A''' ) ) self.assertFalse(_is_punctuation(''' ''' ) ) def SCREAMING_SNAKE_CASE ( self : int ): __lowercase = self.get_tokenizer() __lowercase = self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(lowercase__ ) for t in ['''Test''', '''\xad''', '''test''']] ,[['''[UNK]'''], [], ['''[UNK]''']] ) self.assertListEqual( [rust_tokenizer.tokenize(lowercase__ ) for t in ['''Test''', '''\xad''', '''test''']] ,[['''[UNK]'''], [], ['''[UNK]''']] ) @slow def SCREAMING_SNAKE_CASE ( self : Any ): __lowercase = self.tokenizer_class.from_pretrained('''google/mobilebert-uncased''' ) __lowercase = tokenizer.encode('''sequence builders''' ,add_special_tokens=lowercase__ ) __lowercase = tokenizer.encode('''multi-sequence build''' ,add_special_tokens=lowercase__ ) __lowercase = tokenizer.build_inputs_with_special_tokens(lowercase__ ) __lowercase = tokenizer.build_inputs_with_special_tokens(lowercase__ ,lowercase__ ) assert encoded_sentence == [1_0_1] + text + [1_0_2] assert encoded_pair == [1_0_1] + text + [1_0_2] + text_a + [1_0_2] def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): __lowercase = self.rust_tokenizer_class.from_pretrained(lowercase__ ,**lowercase__ ) __lowercase = F"A, naïve {tokenizer_r.mask_token} AllenNLP sentence." __lowercase = tokenizer_r.encode_plus( lowercase__ ,return_attention_mask=lowercase__ ,return_token_type_ids=lowercase__ ,return_offsets_mapping=lowercase__ ,add_special_tokens=lowercase__ ,) __lowercase = tokenizer_r.do_lower_case if hasattr(lowercase__ ,'''do_lower_case''' ) else False __lowercase = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), '''A'''), ((1, 2), ''','''), ((3, 5), '''na'''), ((5, 6), '''##ï'''), ((6, 8), '''##ve'''), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), '''Allen'''), ((2_1, 2_3), '''##NL'''), ((2_3, 2_4), '''##P'''), ((2_5, 3_3), '''sentence'''), ((3_3, 3_4), '''.'''), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), '''a'''), ((1, 2), ''','''), ((3, 8), '''naive'''), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), '''allen'''), ((2_1, 2_3), '''##nl'''), ((2_3, 2_4), '''##p'''), ((2_5, 3_3), '''sentence'''), ((3_3, 3_4), '''.'''), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] ,tokenizer_r.convert_ids_to_tokens(tokens['''input_ids'''] ) ) self.assertEqual([e[0] for e in expected_results] ,tokens['''offset_mapping'''] ) def SCREAMING_SNAKE_CASE ( self : Dict ): __lowercase = ['''的''', '''人''', '''有'''] __lowercase = ''''''.join(lowercase__ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): __lowercase = True __lowercase = self.tokenizer_class.from_pretrained(lowercase__ ,**lowercase__ ) __lowercase = self.rust_tokenizer_class.from_pretrained(lowercase__ ,**lowercase__ ) __lowercase = tokenizer_p.encode(lowercase__ ,add_special_tokens=lowercase__ ) __lowercase = tokenizer_r.encode(lowercase__ ,add_special_tokens=lowercase__ ) __lowercase = tokenizer_r.convert_ids_to_tokens(lowercase__ ) __lowercase = tokenizer_p.convert_ids_to_tokens(lowercase__ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(lowercase__ ,lowercase__ ) self.assertListEqual(lowercase__ ,lowercase__ ) __lowercase = False __lowercase = self.rust_tokenizer_class.from_pretrained(lowercase__ ,**lowercase__ ) __lowercase = self.tokenizer_class.from_pretrained(lowercase__ ,**lowercase__ ) __lowercase = tokenizer_r.encode(lowercase__ ,add_special_tokens=lowercase__ ) __lowercase = tokenizer_p.encode(lowercase__ ,add_special_tokens=lowercase__ ) __lowercase = tokenizer_r.convert_ids_to_tokens(lowercase__ ) __lowercase = tokenizer_p.convert_ids_to_tokens(lowercase__ ) # it is expected that only the first Chinese character is not preceded by "##". __lowercase = [ F"##{token}" if idx != 0 else token for idx, token in enumerate(lowercase__ ) ] self.assertListEqual(lowercase__ ,lowercase__ ) self.assertListEqual(lowercase__ ,lowercase__ )
41
"""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
0
'''simple docstring''' import itertools from dataclasses import dataclass from typing import Optional import pandas as pd import pyarrow as pa import datasets from datasets.table import table_cast @dataclass class UpperCAmelCase ( datasets.BuilderConfig ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = None class UpperCAmelCase ( datasets.ArrowBasedBuilder ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = PandasConfig def UpperCamelCase( self ) -> str: '''simple docstring''' return datasets.DatasetInfo(features=self.config.features ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Dict: '''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}''' ) lowerCamelCase_ = dl_manager.download_and_extract(self.config.data_files ) if isinstance(SCREAMING_SNAKE_CASE_ , (str, list, tuple) ): lowerCamelCase_ = data_files if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive lowerCamelCase_ = [dl_manager.iter_files(SCREAMING_SNAKE_CASE_ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'files': files} )] lowerCamelCase_ = [] for split_name, files in data_files.items(): if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive lowerCamelCase_ = [dl_manager.iter_files(SCREAMING_SNAKE_CASE_ ) for file in files] splits.append(datasets.SplitGenerator(name=SCREAMING_SNAKE_CASE_ , gen_kwargs={'files': files} ) ) return splits def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> pa.Table: '''simple docstring''' if self.config.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example lowerCamelCase_ = table_cast(SCREAMING_SNAKE_CASE_ , self.config.features.arrow_schema ) return pa_table def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> str: '''simple docstring''' for i, file in enumerate(itertools.chain.from_iterable(SCREAMING_SNAKE_CASE_ ) ): with open(SCREAMING_SNAKE_CASE_ , 'rb' ) as f: lowerCamelCase_ = pa.Table.from_pandas(pd.read_pickle(SCREAMING_SNAKE_CASE_ ) ) yield i, self._cast_table(SCREAMING_SNAKE_CASE_ )
42
"""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
0
import os import tempfile import unittest from transformers import FlaubertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( FlaubertForMultipleChoice, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertModel, FlaubertWithLMHeadModel, ) from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST class _a ( UpperCamelCase__ ): def __init__( self: Optional[int] , UpperCamelCase_: Dict , UpperCamelCase_: Optional[int]=13 , UpperCamelCase_: List[Any]=7 , UpperCamelCase_: Tuple=True , UpperCamelCase_: List[Any]=True , UpperCamelCase_: Dict=True , UpperCamelCase_: Optional[Any]=True , UpperCamelCase_: Dict=True , UpperCamelCase_: Optional[int]=False , UpperCamelCase_: str=False , UpperCamelCase_: Any=False , UpperCamelCase_: int=2 , UpperCamelCase_: Dict=99 , UpperCamelCase_: Tuple=0 , UpperCamelCase_: Tuple=32 , UpperCamelCase_: List[str]=5 , UpperCamelCase_: Tuple=4 , UpperCamelCase_: Union[str, Any]=0.1 , UpperCamelCase_: Tuple=0.1 , UpperCamelCase_: Any=512 , UpperCamelCase_: Union[str, Any]=12 , UpperCamelCase_: Optional[Any]=2 , UpperCamelCase_: Any=0.02 , UpperCamelCase_: Tuple=3 , UpperCamelCase_: Optional[int]=4 , UpperCamelCase_: Dict="last" , UpperCamelCase_: Optional[Any]=None , UpperCamelCase_: Union[str, Any]=None , ) -> List[str]: """simple docstring""" lowercase__ = parent lowercase__ = batch_size lowercase__ = seq_length lowercase__ = is_training lowercase__ = use_input_lengths lowercase__ = use_token_type_ids lowercase__ = use_labels lowercase__ = gelu_activation lowercase__ = sinusoidal_embeddings lowercase__ = causal lowercase__ = asm lowercase__ = n_langs lowercase__ = vocab_size lowercase__ = n_special lowercase__ = hidden_size lowercase__ = num_hidden_layers lowercase__ = num_attention_heads lowercase__ = hidden_dropout_prob lowercase__ = attention_probs_dropout_prob lowercase__ = max_position_embeddings lowercase__ = type_vocab_size lowercase__ = type_sequence_label_size lowercase__ = initializer_range lowercase__ = num_labels lowercase__ = num_choices lowercase__ = summary_type lowercase__ = use_proj lowercase__ = scope def lowerCamelCase_ ( self: Optional[Any] ) -> str: """simple docstring""" lowercase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase__ = random_attention_mask([self.batch_size, self.seq_length] ) lowercase__ = None if self.use_input_lengths: lowercase__ = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length lowercase__ = None if self.use_token_type_ids: lowercase__ = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) lowercase__ = None lowercase__ = None lowercase__ = None if self.use_labels: lowercase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowercase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowercase__ = ids_tensor([self.batch_size] , 2 ).float() lowercase__ = ids_tensor([self.batch_size] , self.num_choices ) lowercase__ = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def lowerCamelCase_ ( self: int ) -> Optional[Any]: """simple docstring""" return FlaubertConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , ) def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase_: Tuple , UpperCamelCase_: List[Any] , UpperCamelCase_: Union[str, Any] , UpperCamelCase_: List[Any] , UpperCamelCase_: List[Any] , UpperCamelCase_: Optional[int] , UpperCamelCase_: Dict , UpperCamelCase_: Any , UpperCamelCase_: Any , ) -> Optional[int]: """simple docstring""" lowercase__ = FlaubertModel(config=UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() lowercase__ = model(UpperCamelCase_ , lengths=UpperCamelCase_ , langs=UpperCamelCase_ ) lowercase__ = model(UpperCamelCase_ , langs=UpperCamelCase_ ) lowercase__ = model(UpperCamelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase_ ( self: Any , UpperCamelCase_: Tuple , UpperCamelCase_: List[str] , UpperCamelCase_: List[Any] , UpperCamelCase_: Optional[int] , UpperCamelCase_: Dict , UpperCamelCase_: Dict , UpperCamelCase_: str , UpperCamelCase_: Optional[int] , UpperCamelCase_: Any , ) -> str: """simple docstring""" lowercase__ = FlaubertWithLMHeadModel(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() lowercase__ = model(UpperCamelCase_ , token_type_ids=UpperCamelCase_ , labels=UpperCamelCase_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCamelCase_ ( self: str , UpperCamelCase_: Any , UpperCamelCase_: Optional[int] , UpperCamelCase_: Optional[int] , UpperCamelCase_: int , UpperCamelCase_: List[str] , UpperCamelCase_: Tuple , UpperCamelCase_: List[str] , UpperCamelCase_: List[Any] , UpperCamelCase_: Optional[Any] , ) -> Dict: """simple docstring""" lowercase__ = FlaubertForQuestionAnsweringSimple(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() lowercase__ = model(UpperCamelCase_ ) lowercase__ = model(UpperCamelCase_ , start_positions=UpperCamelCase_ , end_positions=UpperCamelCase_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase_: Any , UpperCamelCase_: Union[str, Any] , UpperCamelCase_: Optional[int] , UpperCamelCase_: str , UpperCamelCase_: Optional[int] , UpperCamelCase_: Optional[int] , UpperCamelCase_: List[str] , UpperCamelCase_: Any , UpperCamelCase_: int , ) -> Optional[int]: """simple docstring""" lowercase__ = FlaubertForQuestionAnswering(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() lowercase__ = model(UpperCamelCase_ ) lowercase__ = model( UpperCamelCase_ , start_positions=UpperCamelCase_ , end_positions=UpperCamelCase_ , cls_index=UpperCamelCase_ , is_impossible=UpperCamelCase_ , p_mask=UpperCamelCase_ , ) lowercase__ = model( UpperCamelCase_ , start_positions=UpperCamelCase_ , end_positions=UpperCamelCase_ , cls_index=UpperCamelCase_ , is_impossible=UpperCamelCase_ , ) ((lowercase__) , ) = result_with_labels.to_tuple() lowercase__ = model(UpperCamelCase_ , start_positions=UpperCamelCase_ , end_positions=UpperCamelCase_ ) ((lowercase__) , ) = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def lowerCamelCase_ ( self: List[Any] , UpperCamelCase_: Any , UpperCamelCase_: Dict , UpperCamelCase_: str , UpperCamelCase_: Optional[int] , UpperCamelCase_: str , UpperCamelCase_: str , UpperCamelCase_: Any , UpperCamelCase_: Optional[Any] , UpperCamelCase_: Tuple , ) -> Optional[Any]: """simple docstring""" lowercase__ = FlaubertForSequenceClassification(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() lowercase__ = model(UpperCamelCase_ ) lowercase__ = model(UpperCamelCase_ , labels=UpperCamelCase_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase_: Dict , UpperCamelCase_: Optional[Any] , UpperCamelCase_: Dict , UpperCamelCase_: int , UpperCamelCase_: Union[str, Any] , UpperCamelCase_: Union[str, Any] , UpperCamelCase_: Any , UpperCamelCase_: List[str] , UpperCamelCase_: List[str] , ) -> int: """simple docstring""" lowercase__ = self.num_labels lowercase__ = FlaubertForTokenClassification(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() lowercase__ = model(UpperCamelCase_ , attention_mask=UpperCamelCase_ , labels=UpperCamelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCamelCase_ ( self: Any , UpperCamelCase_: Optional[int] , UpperCamelCase_: Union[str, Any] , UpperCamelCase_: Optional[Any] , UpperCamelCase_: Optional[int] , UpperCamelCase_: Any , UpperCamelCase_: Dict , UpperCamelCase_: Optional[Any] , UpperCamelCase_: Tuple , UpperCamelCase_: int , ) -> List[str]: """simple docstring""" lowercase__ = self.num_choices lowercase__ = FlaubertForMultipleChoice(config=UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() lowercase__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowercase__ = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowercase__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowercase__ = model( UpperCamelCase_ , attention_mask=UpperCamelCase_ , token_type_ids=UpperCamelCase_ , labels=UpperCamelCase_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def lowerCamelCase_ ( self: List[str] ) -> Optional[int]: """simple docstring""" lowercase__ = self.prepare_config_and_inputs() ( ( lowercase__ ) , ( lowercase__ ) , ( lowercase__ ) , ( lowercase__ ) , ( lowercase__ ) , ( lowercase__ ) , ( lowercase__ ) , ( lowercase__ ) , ( lowercase__ ) , ) = config_and_inputs lowercase__ = { '''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''lengths''': input_lengths, '''attention_mask''': input_mask, } return config, inputs_dict @require_torch class _a ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): _lowercase : Optional[int] = ( ( FlaubertModel, FlaubertWithLMHeadModel, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertForMultipleChoice, ) if is_torch_available() else () ) _lowercase : str = ( { '''feature-extraction''': FlaubertModel, '''fill-mask''': FlaubertWithLMHeadModel, '''question-answering''': FlaubertForQuestionAnsweringSimple, '''text-classification''': FlaubertForSequenceClassification, '''token-classification''': FlaubertForTokenClassification, '''zero-shot''': FlaubertForSequenceClassification, } if is_torch_available() else {} ) def lowerCamelCase_ ( self: Any , UpperCamelCase_: str , UpperCamelCase_: Union[str, Any] , UpperCamelCase_: Tuple , UpperCamelCase_: Dict , UpperCamelCase_: Any ) -> Dict: """simple docstring""" if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith('''Fast''' ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def lowerCamelCase_ ( self: Tuple , UpperCamelCase_: Optional[int] , UpperCamelCase_: int , UpperCamelCase_: Any=False ) -> Tuple: """simple docstring""" lowercase__ = super()._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ , return_labels=UpperCamelCase_ ) if return_labels: if model_class.__name__ == "FlaubertForQuestionAnswering": lowercase__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCamelCase_ ) lowercase__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCamelCase_ ) return inputs_dict def lowerCamelCase_ ( self: Any ) -> Dict: """simple docstring""" lowercase__ = FlaubertModelTester(self ) lowercase__ = ConfigTester(self , config_class=UpperCamelCase_ , emb_dim=37 ) def lowerCamelCase_ ( self: int ) -> int: """simple docstring""" self.config_tester.run_common_tests() def lowerCamelCase_ ( self: str ) -> Union[str, Any]: """simple docstring""" lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*UpperCamelCase_ ) def lowerCamelCase_ ( self: List[Any] ) -> List[str]: """simple docstring""" lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*UpperCamelCase_ ) def lowerCamelCase_ ( self: int ) -> Union[str, Any]: """simple docstring""" lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_simple_qa(*UpperCamelCase_ ) def lowerCamelCase_ ( self: Union[str, Any] ) -> str: """simple docstring""" lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*UpperCamelCase_ ) def lowerCamelCase_ ( self: Optional[int] ) -> List[Any]: """simple docstring""" lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*UpperCamelCase_ ) def lowerCamelCase_ ( self: Union[str, Any] ) -> List[Any]: """simple docstring""" lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_token_classif(*UpperCamelCase_ ) def lowerCamelCase_ ( self: int ) -> Tuple: """simple docstring""" lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_multiple_choice(*UpperCamelCase_ ) @slow def lowerCamelCase_ ( self: int ) -> List[str]: """simple docstring""" for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase__ = FlaubertModel.from_pretrained(UpperCamelCase_ ) self.assertIsNotNone(UpperCamelCase_ ) @slow @require_torch_gpu def lowerCamelCase_ ( self: Union[str, Any] ) -> List[Any]: """simple docstring""" lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # FlauBertForMultipleChoice behaves incorrectly in JIT environments. if model_class == FlaubertForMultipleChoice: return lowercase__ = True lowercase__ = model_class(config=UpperCamelCase_ ) lowercase__ = self._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ ) lowercase__ = torch.jit.trace( UpperCamelCase_ , (inputs_dict['''input_ids'''].to('''cpu''' ), inputs_dict['''attention_mask'''].to('''cpu''' )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(UpperCamelCase_ , os.path.join(UpperCamelCase_ , '''traced_model.pt''' ) ) lowercase__ = torch.jit.load(os.path.join(UpperCamelCase_ , '''traced_model.pt''' ) , map_location=UpperCamelCase_ ) loaded(inputs_dict['''input_ids'''].to(UpperCamelCase_ ) , inputs_dict['''attention_mask'''].to(UpperCamelCase_ ) ) @require_torch class _a ( unittest.TestCase ): @slow def lowerCamelCase_ ( self: Any ) -> Optional[int]: """simple docstring""" lowercase__ = FlaubertModel.from_pretrained('''flaubert/flaubert_base_cased''' ) lowercase__ = torch.tensor([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]] ) with torch.no_grad(): lowercase__ = model(UpperCamelCase_ )[0] lowercase__ = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , UpperCamelCase_ ) lowercase__ = torch.tensor( [[[-2.6251, -1.4298, -0.0227], [-2.8510, -1.6387, 0.2258], [-2.8114, -1.1832, -0.3066]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCamelCase_ , atol=1E-4 ) )
43
"""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
0
'''simple docstring''' from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_torch_available, is_torch_tpu_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_torch_available(): import torch if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm UpperCAmelCase_ : Union[str, Any] = logging.get_logger(__name__) @dataclass class UpperCAmelCase__ ( A ): lowerCAmelCase_ = [ 'no_inference', 'no_cuda', 'no_tpu', 'no_speed', 'no_memory', 'no_env_print', 'no_multi_process', ] def __init__( self : str,**__A : List[Any] ): for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: _lowerCamelCase : Any = deprecated_arg[3:] setattr(self,__A,not kwargs.pop(__A ) ) logger.warning( f'{deprecated_arg} is depreciated. Please use --no_{positive_arg} or' f' {positive_arg}={kwargs[positive_arg]}' ) _lowerCamelCase : str = kwargs.pop("torchscript",self.torchscript ) _lowerCamelCase : Tuple = kwargs.pop("torch_xla_tpu_print_metrics",self.torch_xla_tpu_print_metrics ) _lowerCamelCase : str = kwargs.pop("fp16_opt_level",self.fpaa_opt_level ) super().__init__(**__A ) lowerCAmelCase_ = field(default=A , metadata={'help': 'Trace the models using torchscript'} ) lowerCAmelCase_ = field(default=A , metadata={'help': 'Print Xla/PyTorch tpu metrics'} ) lowerCAmelCase_ = field( default='O1' , metadata={ 'help': ( 'For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\']. ' 'See details at https://nvidia.github.io/apex/amp.html' ) } , ) @cached_property def lowerCamelCase_ ( self : Any ): requires_backends(self,["torch"] ) logger.info("PyTorch: setting up devices" ) if not self.cuda: _lowerCamelCase : Union[str, Any] = torch.device("cpu" ) _lowerCamelCase : List[str] = 0 elif is_torch_tpu_available(): _lowerCamelCase : Dict = xm.xla_device() _lowerCamelCase : Dict = 0 else: _lowerCamelCase : Union[str, Any] = torch.device("cuda" if torch.cuda.is_available() else "cpu" ) _lowerCamelCase : Any = torch.cuda.device_count() return device, n_gpu @property def lowerCamelCase_ ( self : Any ): return is_torch_tpu_available() and self.tpu @property def lowerCamelCase_ ( self : Optional[Any] ): requires_backends(self,["torch"] ) # TODO(PVP): currently only single GPU is supported return torch.cuda.current_device() @property def lowerCamelCase_ ( self : Dict ): requires_backends(self,["torch"] ) return self._setup_devices[0] @property def lowerCamelCase_ ( self : Optional[int] ): requires_backends(self,["torch"] ) return self._setup_devices[1] @property def lowerCamelCase_ ( self : str ): return self.n_gpu > 0
44
"""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
0
from __future__ import annotations import copy import tempfile import unittest from transformers import CONFIG_MAPPING, AutoConfig, BertConfig, GPTaConfig, TaConfig, TapasConfig, is_tf_available from transformers.testing_utils import ( DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, require_tensorflow_probability, require_tf, slow, ) from ..bert.test_modeling_bert import BertModelTester if is_tf_available(): from transformers import ( TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelForTableQuestionAnswering, TFAutoModelForTokenClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFFunnelBaseModel, TFFunnelModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, TFTapasForQuestionAnswering, ) from transformers.models.auto.modeling_tf_auto import ( TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_MAPPING, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.tapas.modeling_tf_tapas import TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase_ ( lowercase ): """simple docstring""" _snake_case : str = """new-model""" if is_tf_available(): class lowerCAmelCase_ ( lowercase ): """simple docstring""" _snake_case : Any = NewModelConfig @require_tf class lowerCAmelCase_ ( unittest.TestCase ): """simple docstring""" @slow def __a ( self :str ): UpperCamelCase__ :Optional[Any] = """bert-base-cased""" UpperCamelCase__ :Any = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) UpperCamelCase__ :Tuple = TFAutoModel.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) @slow def __a ( self :List[Any] ): UpperCamelCase__ :Dict = """bert-base-cased""" UpperCamelCase__ :Union[str, Any] = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) UpperCamelCase__ :Optional[Any] = TFAutoModelForPreTraining.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) @slow def __a ( self :List[Any] ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ :Any = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) UpperCamelCase__ :Union[str, Any] = TFAutoModelForCausalLM.from_pretrained(lowerCamelCase__ ) UpperCamelCase__ , UpperCamelCase__ :str = TFAutoModelForCausalLM.from_pretrained(lowerCamelCase__ , output_loading_info=lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) @slow def __a ( self :Any ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ :int = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) UpperCamelCase__ :List[Any] = TFAutoModelWithLMHead.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) @slow def __a ( self :Any ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ :List[Any] = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) UpperCamelCase__ :Optional[Any] = TFAutoModelForMaskedLM.from_pretrained(lowerCamelCase__ ) UpperCamelCase__ , UpperCamelCase__ :Optional[Any] = TFAutoModelForMaskedLM.from_pretrained(lowerCamelCase__ , output_loading_info=lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) @slow def __a ( self :str ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ :List[str] = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) UpperCamelCase__ :Any = TFAutoModelForSeqaSeqLM.from_pretrained(lowerCamelCase__ ) UpperCamelCase__ , UpperCamelCase__ :List[Any] = TFAutoModelForSeqaSeqLM.from_pretrained(lowerCamelCase__ , output_loading_info=lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) @slow def __a ( self :Dict ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: UpperCamelCase__ :List[Any] = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) UpperCamelCase__ :Optional[int] = TFAutoModelForSequenceClassification.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) @slow def __a ( self :str ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: UpperCamelCase__ :Tuple = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) UpperCamelCase__ :int = TFAutoModelForQuestionAnswering.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) @slow @require_tensorflow_probability def __a ( self :Optional[Any] ): for model_name in TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST[5:6]: UpperCamelCase__ :Dict = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) UpperCamelCase__ :str = TFAutoModelForTableQuestionAnswering.from_pretrained(lowerCamelCase__ ) UpperCamelCase__ , UpperCamelCase__ :Union[str, Any] = TFAutoModelForTableQuestionAnswering.from_pretrained( lowerCamelCase__ , output_loading_info=lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) def __a ( self :int ): UpperCamelCase__ :Dict = TFAutoModelWithLMHead.from_pretrained(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=lowerCamelCase__ ) , 1_44_10 ) def __a ( self :str ): UpperCamelCase__ :List[Any] = TFAutoModelWithLMHead.from_pretrained(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=lowerCamelCase__ ) , 1_44_10 ) def __a ( self :Tuple ): # For the auto model mapping, FunnelConfig has two models: FunnelModel and FunnelBaseModel UpperCamelCase__ :Optional[Any] = TFAutoModel.from_pretrained("""sgugger/funnel-random-tiny""" ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) UpperCamelCase__ :List[Any] = copy.deepcopy(model.config ) UpperCamelCase__ :int = ["""FunnelBaseModel"""] UpperCamelCase__ :Union[str, Any] = TFAutoModel.from_config(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(lowerCamelCase__ ) UpperCamelCase__ :List[str] = TFAutoModel.from_pretrained(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) def __a ( self :Optional[Any] ): try: AutoConfig.register("""new-model""" , lowerCamelCase__ ) UpperCamelCase__ :List[Any] = [ TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSequenceClassification, TFAutoModelForTokenClassification, ] for auto_class in auto_classes: with self.subTest(auto_class.__name__ ): # Wrong config class will raise an error with self.assertRaises(lowerCamelCase__ ): auto_class.register(lowerCamelCase__ , lowerCamelCase__ ) auto_class.register(lowerCamelCase__ , lowerCamelCase__ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(lowerCamelCase__ ): auto_class.register(lowerCamelCase__ , lowerCamelCase__ ) # Now that the config is registered, it can be used as any other config with the auto-API UpperCamelCase__ :Dict = BertModelTester(self ).get_config() UpperCamelCase__ :Optional[Any] = NewModelConfig(**tiny_config.to_dict() ) UpperCamelCase__ :Any = auto_class.from_config(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(lowerCamelCase__ ) UpperCamelCase__ :int = auto_class.from_pretrained(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) finally: if "new-model" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["new-model"] for mapping in ( TF_MODEL_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, ): if NewModelConfig in mapping._extra_content: del mapping._extra_content[NewModelConfig] def __a ( self :List[str] ): with self.assertRaisesRegex( lowerCamelCase__ , """bert-base is not a local folder and is not a valid model identifier""" ): UpperCamelCase__ :Optional[Any] = TFAutoModel.from_pretrained("""bert-base""" ) def __a ( self :int ): with self.assertRaisesRegex( lowerCamelCase__ , r"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)""" ): UpperCamelCase__ :Optional[int] = TFAutoModel.from_pretrained(lowerCamelCase__ , revision="""aaaaaa""" ) def __a ( self :Optional[int] ): with self.assertRaisesRegex( lowerCamelCase__ , """hf-internal-testing/config-no-model does not appear to have a file named pytorch_model.bin""" , ): UpperCamelCase__ :List[str] = TFAutoModel.from_pretrained("""hf-internal-testing/config-no-model""" ) def __a ( self :Tuple ): with self.assertRaisesRegex(lowerCamelCase__ , """Use `from_pt=True` to load this model""" ): UpperCamelCase__ :Tuple = TFAutoModel.from_pretrained("""hf-internal-testing/tiny-bert-pt-only""" ) def __a ( self :Optional[int] ): # Make sure we have cached the model. UpperCamelCase__ :Tuple = TFAutoModel.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) with RequestCounter() as counter: UpperCamelCase__ :List[Any] = TFAutoModel.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 ) # With a sharded checkpoint UpperCamelCase__ :Optional[int] = TFAutoModel.from_pretrained("""ArthurZ/tiny-random-bert-sharded""" ) with RequestCounter() as counter: UpperCamelCase__ :Dict = TFAutoModel.from_pretrained("""ArthurZ/tiny-random-bert-sharded""" ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 )
45
"""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
0
"""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 _lowerCAmelCase : Optional[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name class A_ ( _a , _a ): @register_to_config def __init__( self: Optional[Any] ,__lowerCAmelCase: bool ,__lowerCAmelCase: Optional[int] = None ,__lowerCAmelCase: Optional[int] = None ): '''simple docstring''' super().__init__() _lowerCamelCase : List[str] = 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" _lowerCamelCase : List[Any] = torch.zeros(__lowerCAmelCase ,__lowerCAmelCase ) else: _lowerCamelCase : Optional[int] = None _lowerCamelCase : Union[str, Any] = torch.nn.Parameter(__lowerCAmelCase ) class A_ ( _a ): lowerCAmelCase__ = 42 lowerCAmelCase__ = 42 lowerCAmelCase__ = 42 lowerCAmelCase__ = 42 lowerCAmelCase__ = 42 lowerCAmelCase__ = 42 def __init__( self: Tuple ,__lowerCAmelCase: VQModel ,__lowerCAmelCase: CLIPTextModel ,__lowerCAmelCase: CLIPTokenizer ,__lowerCAmelCase: TransformeraDModel ,__lowerCAmelCase: VQDiffusionScheduler ,__lowerCAmelCase: LearnedClassifierFreeSamplingEmbeddings ,): '''simple docstring''' super().__init__() self.register_modules( vqvae=__lowerCAmelCase ,transformer=__lowerCAmelCase ,text_encoder=__lowerCAmelCase ,tokenizer=__lowerCAmelCase ,scheduler=__lowerCAmelCase ,learned_classifier_free_sampling_embeddings=__lowerCAmelCase ,) def _lowercase ( self: List[str] ,__lowerCAmelCase: List[Any] ,__lowerCAmelCase: Optional[Any] ,__lowerCAmelCase: str ): '''simple docstring''' _lowerCamelCase : Tuple = len(__lowerCAmelCase ) if isinstance(__lowerCAmelCase ,__lowerCAmelCase ) else 1 # get prompt text embeddings _lowerCamelCase : Dict = self.tokenizer( __lowerCAmelCase ,padding="max_length" ,max_length=self.tokenizer.model_max_length ,return_tensors="pt" ,) _lowerCamelCase : Any = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: _lowerCamelCase : Optional[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}""" ) _lowerCamelCase : Any = text_input_ids[:, : self.tokenizer.model_max_length] _lowerCamelCase : List[Any] = 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 _lowerCamelCase : int = prompt_embeds / prompt_embeds.norm(dim=-1 ,keepdim=__lowerCAmelCase ) # duplicate text embeddings for each generation per prompt _lowerCamelCase : Union[str, Any] = prompt_embeds.repeat_interleave(__lowerCAmelCase ,dim=0 ) if do_classifier_free_guidance: if self.learned_classifier_free_sampling_embeddings.learnable: _lowerCamelCase : Optional[int] = self.learned_classifier_free_sampling_embeddings.embeddings _lowerCamelCase : int = negative_prompt_embeds.unsqueeze(0 ).repeat(__lowerCAmelCase ,1 ,1 ) else: _lowerCamelCase : str = [""] * batch_size _lowerCamelCase : Optional[Any] = text_input_ids.shape[-1] _lowerCamelCase : Dict = self.tokenizer( __lowerCAmelCase ,padding="max_length" ,max_length=__lowerCAmelCase ,truncation=__lowerCAmelCase ,return_tensors="pt" ,) _lowerCamelCase : Tuple = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # See comment for normalizing text embeddings _lowerCamelCase : Union[str, Any] = negative_prompt_embeds / negative_prompt_embeds.norm(dim=-1 ,keepdim=__lowerCAmelCase ) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method _lowerCamelCase : Any = negative_prompt_embeds.shape[1] _lowerCamelCase : int = negative_prompt_embeds.repeat(1 ,__lowerCAmelCase ,1 ) _lowerCamelCase : str = negative_prompt_embeds.view(batch_size * num_images_per_prompt ,__lowerCAmelCase ,-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 _lowerCamelCase : int = torch.cat([negative_prompt_embeds, prompt_embeds] ) return prompt_embeds @torch.no_grad() def __call__( self: Tuple ,__lowerCAmelCase: Union[str, List[str]] ,__lowerCAmelCase: int = 100 ,__lowerCAmelCase: float = 5.0 ,__lowerCAmelCase: float = 1.0 ,__lowerCAmelCase: int = 1 ,__lowerCAmelCase: Optional[Union[torch.Generator, List[torch.Generator]]] = None ,__lowerCAmelCase: Optional[torch.FloatTensor] = None ,__lowerCAmelCase: Optional[str] = "pil" ,__lowerCAmelCase: bool = True ,__lowerCAmelCase: Optional[Callable[[int, int, torch.FloatTensor], None]] = None ,__lowerCAmelCase: int = 1 ,): '''simple docstring''' if isinstance(__lowerCAmelCase ,__lowerCAmelCase ): _lowerCamelCase : str = 1 elif isinstance(__lowerCAmelCase ,__lowerCAmelCase ): _lowerCamelCase : str = len(__lowerCAmelCase ) else: raise ValueError(F"""`prompt` has to be of type `str` or `list` but is {type(__lowerCAmelCase )}""" ) _lowerCamelCase : Dict = batch_size * num_images_per_prompt _lowerCamelCase : Tuple = guidance_scale > 1.0 _lowerCamelCase : Optional[Any] = self._encode_prompt(__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(__lowerCAmelCase ,__lowerCAmelCase ) or callback_steps <= 0) ): raise ValueError( F"""`callback_steps` has to be a positive integer but is {callback_steps} of type""" F""" {type(__lowerCAmelCase )}.""" ) # get the initial completely masked latents unless the user supplied it _lowerCamelCase : Any = (batch_size, self.transformer.num_latent_pixels) if latents is None: _lowerCamelCase : int = self.transformer.num_vector_embeds - 1 _lowerCamelCase : List[Any] = torch.full(__lowerCAmelCase ,__lowerCAmelCase ).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).""" ) _lowerCamelCase : Union[str, Any] = latents.to(self.device ) # set timesteps self.scheduler.set_timesteps(__lowerCAmelCase ,device=self.device ) _lowerCamelCase : List[Any] = self.scheduler.timesteps.to(self.device ) _lowerCamelCase : List[Any] = latents for i, t in enumerate(self.progress_bar(__lowerCAmelCase ) ): # expand the sample if we are doing classifier free guidance _lowerCamelCase : Union[str, Any] = torch.cat([sample] * 2 ) if do_classifier_free_guidance else sample # predict the un-noised image # model_output == `log_p_x_0` _lowerCamelCase : List[Any] = self.transformer(__lowerCAmelCase ,encoder_hidden_states=__lowerCAmelCase ,timestep=__lowerCAmelCase ).sample if do_classifier_free_guidance: _lowerCamelCase, _lowerCamelCase : Optional[int] = model_output.chunk(2 ) _lowerCamelCase : Optional[int] = model_output_uncond + guidance_scale * (model_output_text - model_output_uncond) model_output -= torch.logsumexp(__lowerCAmelCase ,dim=1 ,keepdim=__lowerCAmelCase ) _lowerCamelCase : Dict = self.truncate(__lowerCAmelCase ,__lowerCAmelCase ) # remove `log(0)`'s (`-inf`s) _lowerCamelCase : Any = model_output.clamp(-70 ) # compute the previous noisy sample x_t -> x_t-1 _lowerCamelCase : Dict = self.scheduler.step(__lowerCAmelCase ,timestep=__lowerCAmelCase ,sample=__lowerCAmelCase ,generator=__lowerCAmelCase ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ) _lowerCamelCase : Optional[int] = self.vqvae.config.vq_embed_dim _lowerCamelCase : Any = (batch_size, self.transformer.height, self.transformer.width, embedding_channels) _lowerCamelCase : List[Any] = self.vqvae.quantize.get_codebook_entry(__lowerCAmelCase ,shape=__lowerCAmelCase ) _lowerCamelCase : Any = self.vqvae.decode(__lowerCAmelCase ,force_not_quantize=__lowerCAmelCase ).sample _lowerCamelCase : List[Any] = (image / 2 + 0.5).clamp(0 ,1 ) _lowerCamelCase : Union[str, Any] = image.cpu().permute(0 ,2 ,3 ,1 ).numpy() if output_type == "pil": _lowerCamelCase : Dict = self.numpy_to_pil(__lowerCAmelCase ) if not return_dict: return (image,) return ImagePipelineOutput(images=__lowerCAmelCase ) def _lowercase ( self: Tuple ,__lowerCAmelCase: torch.FloatTensor ,__lowerCAmelCase: float ): '''simple docstring''' _lowerCamelCase, _lowerCamelCase : Tuple = torch.sort(__lowerCAmelCase ,1 ,descending=__lowerCAmelCase ) _lowerCamelCase : int = torch.exp(__lowerCAmelCase ) _lowerCamelCase : Optional[Any] = sorted_p_x_0.cumsum(dim=1 ) < truncation_rate # Ensure that at least the largest probability is not zeroed out _lowerCamelCase : Tuple = torch.full_like(keep_mask[:, 0:1, :] ,__lowerCAmelCase ) _lowerCamelCase : List[Any] = torch.cat((all_true, keep_mask) ,dim=1 ) _lowerCamelCase : List[str] = keep_mask[:, :-1, :] _lowerCamelCase : Optional[Any] = keep_mask.gather(1 ,indices.argsort(1 ) ) _lowerCamelCase : List[str] = log_p_x_0.clone() _lowerCamelCase : Optional[Any] = -torch.inf # -inf = log(0) return rv
46
"""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
0
from string import ascii_lowercase, ascii_uppercase def UpperCAmelCase__ ( lowerCamelCase_ : str ): if not sentence: return "" __a : Union[str, Any] = dict(zip(lowerCamelCase_ , lowerCamelCase_ ) ) return lower_to_upper.get(sentence[0] , sentence[0] ) + sentence[1:] if __name__ == "__main__": from doctest import testmod testmod()
47
"""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
0
'''simple docstring''' import re def A ( UpperCamelCase_ : str ) -> str: '''simple docstring''' if len(re.findall("[ATCG]" , UpperCamelCase_ ) ) != len(UpperCamelCase_ ): raise ValueError("Invalid Strand" ) return dna.translate(dna.maketrans("ATCG" , "TAGC" ) ) if __name__ == "__main__": import doctest doctest.testmod()
48
"""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
0
"""simple docstring""" import unittest import numpy as np from transformers import is_flax_available from transformers.testing_utils import require_flax from ..test_modeling_flax_common import ids_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.generation import ( FlaxForcedBOSTokenLogitsProcessor, FlaxForcedEOSTokenLogitsProcessor, FlaxLogitsProcessorList, FlaxMinLengthLogitsProcessor, FlaxTemperatureLogitsWarper, FlaxTopKLogitsWarper, FlaxTopPLogitsWarper, ) @require_flax class _UpperCAmelCase ( unittest.TestCase ): def a ( self : int , _lowercase : int , _lowercase : int ): __UpperCAmelCase = jnp.ones((batch_size, length) ) / length return scores def a ( self : str ): __UpperCAmelCase = None __UpperCAmelCase = 20 __UpperCAmelCase = self._get_uniform_logits(batch_size=2 , length=_lowercase ) # tweak scores to not be uniform anymore __UpperCAmelCase = scores.at[1, 5].set((1 / length) + 0.1 ) # peak, 1st batch __UpperCAmelCase = scores.at[1, 10].set((1 / length) - 0.4 ) # valley, 1st batch # compute softmax __UpperCAmelCase = jax.nn.softmax(_lowercase , axis=-1 ) __UpperCAmelCase = FlaxTemperatureLogitsWarper(temperature=0.5 ) __UpperCAmelCase = FlaxTemperatureLogitsWarper(temperature=1.3 ) __UpperCAmelCase = jax.nn.softmax(temp_dist_warper_sharper(_lowercase , scores.copy() , cur_len=_lowercase ) , axis=-1 ) __UpperCAmelCase = jax.nn.softmax(temp_dist_warper_smoother(_lowercase , scores.copy() , cur_len=_lowercase ) , axis=-1 ) # uniform distribution stays uniform self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_sharp[0, :] , atol=1E-3 ) ) self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_smooth[0, :] , atol=1E-3 ) ) # sharp peaks get higher, valleys get lower self.assertLess(probs[1, :].max() , warped_prob_sharp[1, :].max() ) self.assertGreater(probs[1, :].min() , warped_prob_sharp[1, :].min() ) # smooth peaks get lower, valleys get higher self.assertGreater(probs[1, :].max() , warped_prob_smooth[1, :].max() ) self.assertLess(probs[1, :].min() , warped_prob_smooth[1, :].min() ) def a ( self : List[Any] ): __UpperCAmelCase = None __UpperCAmelCase = 10 __UpperCAmelCase = 2 # create ramp distribution __UpperCAmelCase = np.broadcast_to(np.arange(_lowercase )[None, :] , (batch_size, vocab_size) ).copy() __UpperCAmelCase = ramp_logits[1:, : vocab_size // 2] + vocab_size __UpperCAmelCase = FlaxTopKLogitsWarper(3 ) __UpperCAmelCase = top_k_warp(_lowercase , _lowercase , cur_len=_lowercase ) # check that correct tokens are filtered self.assertListEqual(jnp.isinf(scores[0] ).tolist() , 7 * [True] + 3 * [False] ) self.assertListEqual(jnp.isinf(scores[1] ).tolist() , 2 * [True] + 3 * [False] + 5 * [True] ) # check special case __UpperCAmelCase = 5 __UpperCAmelCase = FlaxTopKLogitsWarper(top_k=1 , filter_value=0.0 , min_tokens_to_keep=3 ) __UpperCAmelCase = np.broadcast_to(np.arange(_lowercase )[None, :] , (batch_size, length) ).copy() __UpperCAmelCase = top_k_warp_safety_check(_lowercase , _lowercase , cur_len=_lowercase ) # min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified self.assertListEqual((scores == 0.0).sum(axis=-1 ).tolist() , [2, 2] ) def a ( self : str ): __UpperCAmelCase = None __UpperCAmelCase = 10 __UpperCAmelCase = 2 # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper) __UpperCAmelCase = np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.15, 0.3, 0.3, 0.25]] ) ) __UpperCAmelCase = FlaxTopPLogitsWarper(0.8 ) __UpperCAmelCase = np.exp(top_p_warp(_lowercase , _lowercase , cur_len=_lowercase ) ) # dist should be filtered to keep min num values so that sum is >= top_p # exp (-inf) => 0 __UpperCAmelCase = np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.25]] ) self.assertTrue(np.allclose(_lowercase , _lowercase , atol=1E-3 ) ) # check edge cases with negative and extreme logits __UpperCAmelCase = np.broadcast_to(np.arange(_lowercase )[None, :] , (batch_size, vocab_size) ).copy() - ( vocab_size // 2 ) # make ramp_logits more extreme __UpperCAmelCase = ramp_logits[1] * 100.0 # make sure at least 2 tokens are kept __UpperCAmelCase = FlaxTopPLogitsWarper(0.9 , min_tokens_to_keep=2 , filter_value=0.0 ) __UpperCAmelCase = top_p_warp(_lowercase , _lowercase , cur_len=_lowercase ) # first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2. self.assertListEqual((filtered_dist != 0.0).sum(axis=-1 ).tolist() , [3, 2] ) def a ( self : List[str] ): __UpperCAmelCase = 20 __UpperCAmelCase = 4 __UpperCAmelCase = 0 __UpperCAmelCase = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=_lowercase ) # check that min length is applied at length 5 __UpperCAmelCase = ids_tensor((batch_size, 20) , vocab_size=20 ) __UpperCAmelCase = 5 __UpperCAmelCase = self._get_uniform_logits(_lowercase , _lowercase ) __UpperCAmelCase = min_dist_processor(_lowercase , _lowercase , cur_len=_lowercase ) self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist() , 4 * [-float('''inf''' )] ) # check that min length is not applied anymore at length 15 __UpperCAmelCase = self._get_uniform_logits(_lowercase , _lowercase ) __UpperCAmelCase = 15 __UpperCAmelCase = min_dist_processor(_lowercase , _lowercase , cur_len=_lowercase ) self.assertFalse(jnp.isinf(_lowercase ).any() ) def a ( self : List[Any] ): __UpperCAmelCase = 20 __UpperCAmelCase = 4 __UpperCAmelCase = 0 __UpperCAmelCase = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=_lowercase ) # check that all scores are -inf except the bos_token_id score __UpperCAmelCase = ids_tensor((batch_size, 1) , vocab_size=20 ) __UpperCAmelCase = 1 __UpperCAmelCase = self._get_uniform_logits(_lowercase , _lowercase ) __UpperCAmelCase = logits_processor(_lowercase , _lowercase , cur_len=_lowercase ) self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, bos_token_id].tolist() , 4 * [0] ) # score for bos_token_id shold be zero # check that bos_token_id is not forced if current length is greater than 1 __UpperCAmelCase = 3 __UpperCAmelCase = self._get_uniform_logits(_lowercase , _lowercase ) __UpperCAmelCase = logits_processor(_lowercase , _lowercase , cur_len=_lowercase ) self.assertFalse(jnp.isinf(_lowercase ).any() ) def a ( self : Optional[int] ): __UpperCAmelCase = 20 __UpperCAmelCase = 4 __UpperCAmelCase = 0 __UpperCAmelCase = 5 __UpperCAmelCase = FlaxForcedEOSTokenLogitsProcessor(max_length=_lowercase , eos_token_id=_lowercase ) # check that all scores are -inf except the eos_token_id when max_length is reached __UpperCAmelCase = ids_tensor((batch_size, 4) , vocab_size=20 ) __UpperCAmelCase = 4 __UpperCAmelCase = self._get_uniform_logits(_lowercase , _lowercase ) __UpperCAmelCase = logits_processor(_lowercase , _lowercase , cur_len=_lowercase ) self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, eos_token_id].tolist() , 4 * [0] ) # score for eos_token_id should be zero # check that eos_token_id is not forced if max_length is not reached __UpperCAmelCase = 3 __UpperCAmelCase = self._get_uniform_logits(_lowercase , _lowercase ) __UpperCAmelCase = logits_processor(_lowercase , _lowercase , cur_len=_lowercase ) self.assertFalse(jnp.isinf(_lowercase ).any() ) def a ( self : Any ): __UpperCAmelCase = 4 __UpperCAmelCase = 10 __UpperCAmelCase = 15 __UpperCAmelCase = 2 __UpperCAmelCase = 1 __UpperCAmelCase = 15 # dummy input_ids and scores __UpperCAmelCase = ids_tensor((batch_size, sequence_length) , _lowercase ) __UpperCAmelCase = input_ids.copy() __UpperCAmelCase = self._get_uniform_logits(_lowercase , _lowercase ) __UpperCAmelCase = scores.copy() # instantiate all dist processors __UpperCAmelCase = FlaxTemperatureLogitsWarper(temperature=0.5 ) __UpperCAmelCase = FlaxTopKLogitsWarper(3 ) __UpperCAmelCase = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors __UpperCAmelCase = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=_lowercase ) __UpperCAmelCase = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=_lowercase ) __UpperCAmelCase = FlaxForcedEOSTokenLogitsProcessor(max_length=_lowercase , eos_token_id=_lowercase ) __UpperCAmelCase = 10 # no processor list __UpperCAmelCase = temp_dist_warp(_lowercase , _lowercase , cur_len=_lowercase ) __UpperCAmelCase = top_k_warp(_lowercase , _lowercase , cur_len=_lowercase ) __UpperCAmelCase = top_p_warp(_lowercase , _lowercase , cur_len=_lowercase ) __UpperCAmelCase = min_dist_proc(_lowercase , _lowercase , cur_len=_lowercase ) __UpperCAmelCase = bos_dist_proc(_lowercase , _lowercase , cur_len=_lowercase ) __UpperCAmelCase = eos_dist_proc(_lowercase , _lowercase , cur_len=_lowercase ) # with processor list __UpperCAmelCase = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) __UpperCAmelCase = processor(_lowercase , _lowercase , cur_len=_lowercase ) # scores should be equal self.assertTrue(jnp.allclose(_lowercase , _lowercase , atol=1E-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() ) def a ( self : int ): __UpperCAmelCase = 4 __UpperCAmelCase = 10 __UpperCAmelCase = 15 __UpperCAmelCase = 2 __UpperCAmelCase = 1 __UpperCAmelCase = 15 # dummy input_ids and scores __UpperCAmelCase = ids_tensor((batch_size, sequence_length) , _lowercase ) __UpperCAmelCase = input_ids.copy() __UpperCAmelCase = self._get_uniform_logits(_lowercase , _lowercase ) __UpperCAmelCase = scores.copy() # instantiate all dist processors __UpperCAmelCase = FlaxTemperatureLogitsWarper(temperature=0.5 ) __UpperCAmelCase = FlaxTopKLogitsWarper(3 ) __UpperCAmelCase = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors __UpperCAmelCase = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=_lowercase ) __UpperCAmelCase = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=_lowercase ) __UpperCAmelCase = FlaxForcedEOSTokenLogitsProcessor(max_length=_lowercase , eos_token_id=_lowercase ) __UpperCAmelCase = 10 # no processor list def run_no_processor_list(_lowercase : List[str] , _lowercase : Optional[Any] , _lowercase : List[Any] ): __UpperCAmelCase = temp_dist_warp(_lowercase , _lowercase , cur_len=_lowercase ) __UpperCAmelCase = top_k_warp(_lowercase , _lowercase , cur_len=_lowercase ) __UpperCAmelCase = top_p_warp(_lowercase , _lowercase , cur_len=_lowercase ) __UpperCAmelCase = min_dist_proc(_lowercase , _lowercase , cur_len=_lowercase ) __UpperCAmelCase = bos_dist_proc(_lowercase , _lowercase , cur_len=_lowercase ) __UpperCAmelCase = eos_dist_proc(_lowercase , _lowercase , cur_len=_lowercase ) return scores # with processor list def run_processor_list(_lowercase : Union[str, Any] , _lowercase : Tuple , _lowercase : int ): __UpperCAmelCase = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) __UpperCAmelCase = processor(_lowercase , _lowercase , cur_len=_lowercase ) return scores __UpperCAmelCase = jax.jit(_lowercase ) __UpperCAmelCase = jax.jit(_lowercase ) __UpperCAmelCase = jitted_run_no_processor_list(_lowercase , _lowercase , _lowercase ) __UpperCAmelCase = jitted_run_processor_list(_lowercase , _lowercase , _lowercase ) # scores should be equal self.assertTrue(jnp.allclose(_lowercase , _lowercase , atol=1E-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() )
49
"""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
0
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer UpperCamelCase : List[Any] = logging.get_logger(__name__) UpperCamelCase : Any = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} UpperCamelCase : Union[str, Any] = { 'vocab_file': { 'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt', 'distilbert-base-uncased-distilled-squad': ( 'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt' ), 'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt', 'distilbert-base-cased-distilled-squad': ( 'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt' ), 'distilbert-base-german-cased': 'https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt', 'distilbert-base-multilingual-cased': ( 'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json', 'distilbert-base-uncased-distilled-squad': ( 'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json' ), 'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json', 'distilbert-base-cased-distilled-squad': ( 'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json' ), 'distilbert-base-german-cased': ( 'https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json' ), 'distilbert-base-multilingual-cased': ( 'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json' ), }, } UpperCamelCase : List[str] = { 'distilbert-base-uncased': 5_12, 'distilbert-base-uncased-distilled-squad': 5_12, 'distilbert-base-cased': 5_12, 'distilbert-base-cased-distilled-squad': 5_12, 'distilbert-base-german-cased': 5_12, 'distilbert-base-multilingual-cased': 5_12, } UpperCamelCase : int = { 'distilbert-base-uncased': {'do_lower_case': True}, 'distilbert-base-uncased-distilled-squad': {'do_lower_case': True}, 'distilbert-base-cased': {'do_lower_case': False}, 'distilbert-base-cased-distilled-squad': {'do_lower_case': False}, 'distilbert-base-german-cased': {'do_lower_case': False}, 'distilbert-base-multilingual-cased': {'do_lower_case': False}, } class UpperCamelCase__ (a ): '''simple docstring''' _UpperCamelCase = VOCAB_FILES_NAMES _UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCamelCase = PRETRAINED_INIT_CONFIGURATION _UpperCamelCase = ['input_ids', 'attention_mask'] _UpperCamelCase = DistilBertTokenizer def __init__( self ,_lowerCAmelCase=None ,_lowerCAmelCase=None ,_lowerCAmelCase=True ,_lowerCAmelCase="[UNK]" ,_lowerCAmelCase="[SEP]" ,_lowerCAmelCase="[PAD]" ,_lowerCAmelCase="[CLS]" ,_lowerCAmelCase="[MASK]" ,_lowerCAmelCase=True ,_lowerCAmelCase=None ,**_lowerCAmelCase ,): super().__init__( _lowerCAmelCase ,tokenizer_file=_lowerCAmelCase ,do_lower_case=_lowerCAmelCase ,unk_token=_lowerCAmelCase ,sep_token=_lowerCAmelCase ,pad_token=_lowerCAmelCase ,cls_token=_lowerCAmelCase ,mask_token=_lowerCAmelCase ,tokenize_chinese_chars=_lowerCAmelCase ,strip_accents=_lowerCAmelCase ,**_lowerCAmelCase ,) lowerCamelCase__ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" ,_lowerCAmelCase ) != do_lower_case or normalizer_state.get("""strip_accents""" ,_lowerCAmelCase ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" ,_lowerCAmelCase ) != tokenize_chinese_chars ): lowerCamelCase__ = getattr(_lowerCAmelCase ,normalizer_state.pop("""type""" ) ) lowerCamelCase__ = do_lower_case lowerCamelCase__ = strip_accents lowerCamelCase__ = tokenize_chinese_chars lowerCamelCase__ = normalizer_class(**_lowerCAmelCase ) lowerCamelCase__ = do_lower_case def UpperCamelCase_ ( self ,_lowerCAmelCase ,_lowerCAmelCase=None ): lowerCamelCase__ = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCamelCase_ ( self ,_lowerCAmelCase ,_lowerCAmelCase = None ): lowerCamelCase__ = [self.sep_token_id] lowerCamelCase__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase_ ( self ,_lowerCAmelCase ,_lowerCAmelCase = None ): lowerCamelCase__ = self._tokenizer.model.save(_lowerCAmelCase ,name=_lowerCAmelCase ) return tuple(_lowerCAmelCase )
50
"""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
0
'''simple docstring''' import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowerCAmelCase__ : '''simple docstring''' def __init__( self : List[Any] , a__ : Optional[Any] , a__ : Any=13 , a__ : str=32 , a__ : Optional[int]=3 , a__ : Tuple=4 , a__ : Any=[10, 20, 30, 40] , a__ : Any=[2, 2, 3, 2] , a__ : List[Any]=True , a__ : List[str]=True , a__ : Union[str, Any]=37 , a__ : Tuple="gelu" , a__ : Any=10 , a__ : List[str]=0.02 , a__ : List[Any]=["stage2", "stage3", "stage4"] , a__ : Any=[2, 3, 4] , a__ : int=None , ): UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = image_size UpperCAmelCase = num_channels UpperCAmelCase = num_stages UpperCAmelCase = hidden_sizes UpperCAmelCase = depths UpperCAmelCase = is_training UpperCAmelCase = use_labels UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_act UpperCAmelCase = num_labels UpperCAmelCase = initializer_range UpperCAmelCase = out_features UpperCAmelCase = out_indices UpperCAmelCase = scope def __snake_case ( self : Dict ): UpperCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCAmelCase = None if self.use_labels: UpperCAmelCase = ids_tensor([self.batch_size] , self.num_labels ) UpperCAmelCase = self.get_config() return config, pixel_values, labels def __snake_case ( self : Dict ): return ConvNextVaConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=a__ , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def __snake_case ( self : Dict , a__ : Tuple , a__ : Union[str, Any] , a__ : List[Any] ): UpperCAmelCase = ConvNextVaModel(config=a__ ) model.to(a__ ) model.eval() UpperCAmelCase = model(a__ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def __snake_case ( self : Dict , a__ : Any , a__ : Dict , a__ : List[Any] ): UpperCAmelCase = ConvNextVaForImageClassification(a__ ) model.to(a__ ) model.eval() UpperCAmelCase = model(a__ , labels=a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __snake_case ( self : Any , a__ : Optional[Any] , a__ : List[Any] , a__ : Dict ): UpperCAmelCase = ConvNextVaBackbone(config=a__ ) model.to(a__ ) model.eval() UpperCAmelCase = model(a__ ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None UpperCAmelCase = None UpperCAmelCase = ConvNextVaBackbone(config=a__ ) model.to(a__ ) model.eval() UpperCAmelCase = model(a__ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def __snake_case ( self : Any ): UpperCAmelCase = self.prepare_config_and_inputs() UpperCAmelCase, UpperCAmelCase, UpperCAmelCase = config_and_inputs UpperCAmelCase = {'''pixel_values''': pixel_values} return config, inputs_dict def __snake_case ( self : List[str] ): UpperCAmelCase = self.prepare_config_and_inputs() UpperCAmelCase, UpperCAmelCase, UpperCAmelCase = config_and_inputs UpperCAmelCase = {'''pixel_values''': pixel_values, '''labels''': labels} return config, inputs_dict @require_torch class lowerCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' _lowerCamelCase =( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) _lowerCamelCase =( {"feature-extraction": ConvNextVaModel, "image-classification": ConvNextVaForImageClassification} if is_torch_available() else {} ) _lowerCamelCase =False _lowerCamelCase =False _lowerCamelCase =False _lowerCamelCase =False _lowerCamelCase =False def __snake_case ( self : List[Any] ): UpperCAmelCase = ConvNextVaModelTester(self ) UpperCAmelCase = ConfigTester(self , config_class=a__ , has_text_modality=a__ , hidden_size=37 ) def __snake_case ( self : Tuple ): 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 __snake_case ( self : Optional[Any] ): return @unittest.skip(reason='''ConvNextV2 does not use inputs_embeds''' ) def __snake_case ( self : List[str] ): pass @unittest.skip(reason='''ConvNextV2 does not support input and output embeddings''' ) def __snake_case ( self : Union[str, Any] ): pass @unittest.skip(reason='''ConvNextV2 does not use feedforward chunking''' ) def __snake_case ( self : str ): pass def __snake_case ( self : Optional[Any] ): if not self.model_tester.is_training: return for model_class in self.all_model_classes: UpperCAmelCase, UpperCAmelCase = self.model_tester.prepare_config_and_inputs_with_labels() UpperCAmelCase = True if model_class.__name__ in [ *get_values(a__ ), *get_values(a__ ), ]: continue UpperCAmelCase = model_class(a__ ) model.to(a__ ) model.train() UpperCAmelCase = self._prepare_for_class(a__ , a__ , return_labels=a__ ) UpperCAmelCase = model(**a__ ).loss loss.backward() def __snake_case ( self : Union[str, Any] ): if not self.model_tester.is_training: return for model_class in self.all_model_classes: UpperCAmelCase, UpperCAmelCase = self.model_tester.prepare_config_and_inputs_with_labels() UpperCAmelCase = False UpperCAmelCase = True if ( model_class.__name__ in [*get_values(a__ ), *get_values(a__ )] or not model_class.supports_gradient_checkpointing ): continue UpperCAmelCase = model_class(a__ ) model.to(a__ ) model.gradient_checkpointing_enable() model.train() UpperCAmelCase = self._prepare_for_class(a__ , a__ , return_labels=a__ ) UpperCAmelCase = model(**a__ ).loss loss.backward() def __snake_case ( self : str ): UpperCAmelCase, UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase = model_class(a__ ) UpperCAmelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase = [*signature.parameters.keys()] UpperCAmelCase = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , a__ ) def __snake_case ( self : Any ): UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a__ ) def __snake_case ( self : Any ): def check_hidden_states_output(a__ : Dict , a__ : str , a__ : Dict ): UpperCAmelCase = model_class(a__ ) model.to(a__ ) model.eval() with torch.no_grad(): UpperCAmelCase = model(**self._prepare_for_class(a__ , a__ ) ) UpperCAmelCase = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states UpperCAmelCase = self.model_tester.num_stages self.assertEqual(len(a__ ) , expected_num_stages + 1 ) # ConvNextV2'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] , ) UpperCAmelCase, UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase = True check_hidden_states_output(a__ , a__ , a__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCAmelCase = True check_hidden_states_output(a__ , a__ , a__ ) def __snake_case ( self : Union[str, Any] ): UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a__ ) @slow def __snake_case ( self : Tuple ): for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase = ConvNextVaModel.from_pretrained(a__ ) self.assertIsNotNone(a__ ) def __snake_case ( ) -> int: """simple docstring""" UpperCAmelCase = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @cached_property def __snake_case ( self : Dict ): return AutoImageProcessor.from_pretrained('''facebook/convnextv2-tiny-1k-224''' ) if is_vision_available() else None @slow def __snake_case ( self : Dict ): UpperCAmelCase = ConvNextVaForImageClassification.from_pretrained('''facebook/convnextv2-tiny-1k-224''' ).to(a__ ) UpperCAmelCase = self.default_image_processor UpperCAmelCase = prepare_img() UpperCAmelCase = preprocessor(images=a__ , return_tensors='''pt''' ).to(a__ ) # forward pass with torch.no_grad(): UpperCAmelCase = model(**a__ ) # verify the logits UpperCAmelCase = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , a__ ) UpperCAmelCase = torch.tensor([0.9_996, 0.1_966, -0.4_386] ).to(a__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a__ , atol=1e-4 ) )
51
"""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
0
"""simple docstring""" import torch from transformers import CamembertForMaskedLM, CamembertTokenizer def __A ( a_ :Union[str, Any] , a_ :Union[str, Any] , a_ :Optional[Any] , a_ :Optional[int]=5) -> List[Any]: # Adapted from https://github.com/pytorch/fairseq/blob/master/fairseq/models/roberta/hub_interface.py assert masked_input.count('''<mask>''') == 1 __a : Optional[Any] = torch.tensor(tokenizer.encode(a_ , add_special_tokens=a_)).unsqueeze(0) # Batch size 1 __a : Dict = model(a_)[0] # The last hidden-state is the first element of the output tuple __a : Tuple = (input_ids.squeeze() == tokenizer.mask_token_id).nonzero().item() __a : Any = logits[0, masked_index, :] __a : Any = logits.softmax(dim=0) __a , __a : Optional[Any] = prob.topk(k=a_ , dim=0) __a : Optional[int] = ''' '''.join( [tokenizer.convert_ids_to_tokens(indices[i].item()) for i in range(len(a_))]) __a : List[str] = tokenizer.mask_token __a : Optional[int] = [] for index, predicted_token_bpe in enumerate(topk_predicted_token_bpe.split(''' ''')): __a : Optional[Any] = predicted_token_bpe.replace('''\u2581''' , ''' ''') if " {0}".format(a_) in masked_input: topk_filled_outputs.append( ( masked_input.replace(''' {0}'''.format(a_) , a_), values[index].item(), predicted_token, )) else: topk_filled_outputs.append( ( masked_input.replace(a_ , a_), values[index].item(), predicted_token, )) return topk_filled_outputs A = CamembertTokenizer.from_pretrained('''camembert-base''') A = CamembertForMaskedLM.from_pretrained('''camembert-base''') model.eval() A = '''Le camembert est <mask> :)''' print(fill_mask(masked_input, model, tokenizer, topk=3))
52
"""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
0
import csv from collections import defaultdict from dataclasses import dataclass, field from typing import List, Optional import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import ScalarFormatter from transformers import HfArgumentParser def a_ ( lowerCAmelCase_ : str=None, lowerCAmelCase_ : Any=None ): return field(default_factory=lambda: default, metadata=lowerCAmelCase_ ) @dataclass class _UpperCAmelCase : """simple docstring""" a_ = field( metadata={"""help""": """The csv file to plot."""} , ) a_ = field( default=_UpperCamelCase , metadata={"""help""": """Whether to plot along batch size or sequence length. Defaults to sequence length."""} , ) a_ = field( default=_UpperCamelCase , metadata={"""help""": """Whether the csv file has time results or memory results. Defaults to memory results."""} , ) a_ = field( default=_UpperCamelCase , metadata={"""help""": """Disable logarithmic scale when plotting"""} , ) a_ = field( default=_UpperCamelCase , metadata={ """help""": """Whether the csv file has training results or inference results. Defaults to inference results.""" } , ) a_ = field( default=_UpperCamelCase , metadata={"""help""": """Filename under which the plot will be saved. If unused no plot is saved."""} , ) a_ = list_field( default=_UpperCamelCase , metadata={"""help""": """List of model names that are used instead of the ones in the csv file."""} ) def a_ ( lowerCAmelCase_ : Tuple ): try: int(lowerCAmelCase_ ) return True except ValueError: return False def a_ ( lowerCAmelCase_ : Dict ): try: float(lowerCAmelCase_ ) return True except ValueError: return False class _UpperCAmelCase : """simple docstring""" def __init__( self : Union[str, Any] , lowerCAmelCase_ : List[Any] ) -> Union[str, Any]: __lowerCAmelCase = args __lowerCAmelCase = defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}} ) with open(self.args.csv_file , newline='' ) as csv_file: __lowerCAmelCase = csv.DictReader(lowerCAmelCase_ ) for row in reader: __lowerCAmelCase = row['model'] self.result_dict[model_name]["bsz"].append(int(row['batch_size'] ) ) self.result_dict[model_name]["seq_len"].append(int(row['sequence_length'] ) ) if can_convert_to_int(row['result'] ): # value is not None __lowerCAmelCase = int(row['result'] ) elif can_convert_to_float(row['result'] ): # value is not None __lowerCAmelCase = float(row['result'] ) def lowercase ( self : List[Any] ) -> Tuple: __lowerCAmelCase , __lowerCAmelCase = plt.subplots() __lowerCAmelCase = 'Time usage' if self.args.is_time else 'Memory usage' __lowerCAmelCase = title_str + ' for training' if self.args.is_train else title_str + ' for inference' if not self.args.no_log_scale: # set logarithm scales ax.set_xscale('log' ) ax.set_yscale('log' ) for axis in [ax.xaxis, ax.yaxis]: axis.set_major_formatter(ScalarFormatter() ) for model_name_idx, model_name in enumerate(self.result_dict.keys() ): __lowerCAmelCase = sorted(set(self.result_dict[model_name]['bsz'] ) ) __lowerCAmelCase = sorted(set(self.result_dict[model_name]['seq_len'] ) ) __lowerCAmelCase = self.result_dict[model_name]['result'] ((__lowerCAmelCase) , (__lowerCAmelCase)) = ( (batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes) ) __lowerCAmelCase = ( model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx] ) for inner_loop_value in inner_loop_array: if self.args.plot_along_batch: __lowerCAmelCase = np.asarray( [results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results] , dtype=lowerCAmelCase_ , ) else: __lowerCAmelCase = np.asarray( [results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results] , dtype=np.floataa , ) ((__lowerCAmelCase) , (__lowerCAmelCase)) = ( ('batch_size', 'len') if self.args.plot_along_batch else ('in #tokens', 'bsz') ) __lowerCAmelCase = np.asarray(lowerCAmelCase_ , lowerCAmelCase_ )[: len(lowerCAmelCase_ )] plt.scatter( lowerCAmelCase_ , lowerCAmelCase_ , label=f"""{label_model_name} - {inner_loop_label}: {inner_loop_value}""" ) plt.plot(lowerCAmelCase_ , lowerCAmelCase_ , '--' ) title_str += f""" {label_model_name} vs.""" __lowerCAmelCase = title_str[:-4] __lowerCAmelCase = 'Time in s' if self.args.is_time else 'Memory in MB' # plot plt.title(lowerCAmelCase_ ) plt.xlabel(lowerCAmelCase_ ) plt.ylabel(lowerCAmelCase_ ) plt.legend() if self.args.figure_png_file is not None: plt.savefig(self.args.figure_png_file ) else: plt.show() def a_ ( ): __lowerCAmelCase = HfArgumentParser(lowerCAmelCase_ ) __lowerCAmelCase = parser.parse_args_into_dataclasses()[0] __lowerCAmelCase = Plot(args=lowerCAmelCase_ ) plot.plot() if __name__ == "__main__": main()
53
"""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
0
import warnings from ...utils import logging from .image_processing_glpn import GLPNImageProcessor __lowercase : List[Any] =logging.get_logger(__name__) class A ( __lowercase ): def __init__( self: List[Any] , *_lowerCAmelCase: Optional[Any] , **_lowerCAmelCase: List[str] ) -> None: '''simple docstring''' warnings.warn( "The class GLPNFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use GLPNImageProcessor instead." , _lowerCAmelCase , ) super().__init__(*_lowerCAmelCase , **_lowerCAmelCase )
54
"""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
0
from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import ScoreSdeVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = 42 snake_case_ = 42 def __init__( self : List[Any] ,A : UNetaDModel ,A : ScoreSdeVeScheduler ): super().__init__() self.register_modules(unet=A ,scheduler=A ) @torch.no_grad() def __call__( self : int ,A : int = 1 ,A : int = 20_00 ,A : Optional[Union[torch.Generator, List[torch.Generator]]] = None ,A : Optional[str] = "pil" ,A : bool = True ,**A : Optional[int] ,): __A = self.unet.config.sample_size __A = (batch_size, 3, img_size, img_size) __A = self.unet __A = randn_tensor(A ,generator=A ) * self.scheduler.init_noise_sigma __A = sample.to(self.device ) self.scheduler.set_timesteps(A ) self.scheduler.set_sigmas(A ) for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): __A = self.scheduler.sigmas[i] * torch.ones(shape[0] ,device=self.device ) # correction step for _ in range(self.scheduler.config.correct_steps ): __A = self.unet(A ,A ).sample __A = self.scheduler.step_correct(A ,A ,generator=A ).prev_sample # prediction step __A = model(A ,A ).sample __A = self.scheduler.step_pred(A ,A ,A ,generator=A ) __A , __A = output.prev_sample, output.prev_sample_mean __A = sample_mean.clamp(0 ,1 ) __A = sample.cpu().permute(0 ,2 ,3 ,1 ).numpy() if output_type == "pil": __A = self.numpy_to_pil(A ) if not return_dict: return (sample,) return ImagePipelineOutput(images=A )
55
"""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
0
'''simple docstring''' import sys from typing import Tuple import numpy as np import torch from PIL import Image from torch import nn from transformers.image_utils import PILImageResampling from utils import img_tensorize class _lowercase : def __init__( self : Any , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Optional[int]=sys.maxsize ) -> Optional[Any]: __snake_case = 'bilinear' __snake_case = max_size __snake_case = short_edge_length def __call__( self : int , SCREAMING_SNAKE_CASE_ : List[Any] ) -> List[str]: __snake_case = [] for img in imgs: __snake_case , __snake_case = img.shape[:2] # later: provide list and randomly choose index for resize __snake_case = np.random.randint(self.short_edge_length[0] , self.short_edge_length[1] + 1 ) if size == 0: return img __snake_case = size * 1.0 / min(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if h < w: __snake_case , __snake_case = size, scale * w else: __snake_case , __snake_case = scale * h, size if max(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) > self.max_size: __snake_case = self.max_size * 1.0 / max(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) __snake_case = newh * scale __snake_case = neww * scale __snake_case = int(neww + 0.5 ) __snake_case = int(newh + 0.5 ) if img.dtype == np.uinta: __snake_case = Image.fromarray(SCREAMING_SNAKE_CASE_ ) __snake_case = pil_image.resize((neww, newh) , PILImageResampling.BILINEAR ) __snake_case = np.asarray(SCREAMING_SNAKE_CASE_ ) else: __snake_case = img.permute(2 , 0 , 1 ).unsqueeze(0 ) # 3, 0, 1) # hw(c) -> nchw __snake_case = nn.functional.interpolate( SCREAMING_SNAKE_CASE_ , (newh, neww) , mode=self.interp_method , align_corners=SCREAMING_SNAKE_CASE_ ).squeeze(0 ) img_augs.append(SCREAMING_SNAKE_CASE_ ) return img_augs class _lowercase : def __init__( self : int , SCREAMING_SNAKE_CASE_ : Dict ) -> List[Any]: __snake_case = ResizeShortestEdge([cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST] , cfg.INPUT.MAX_SIZE_TEST ) __snake_case = cfg.INPUT.FORMAT __snake_case = cfg.SIZE_DIVISIBILITY __snake_case = cfg.PAD_VALUE __snake_case = cfg.INPUT.MAX_SIZE_TEST __snake_case = cfg.MODEL.DEVICE __snake_case = torch.tensor(cfg.MODEL.PIXEL_STD ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) __snake_case = torch.tensor(cfg.MODEL.PIXEL_MEAN ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) __snake_case = lambda SCREAMING_SNAKE_CASE_ : (x - self.pixel_mean) / self.pixel_std def a ( self : str , SCREAMING_SNAKE_CASE_ : int ) -> int: __snake_case = tuple(max(SCREAMING_SNAKE_CASE_ ) for s in zip(*[img.shape for img in images] ) ) __snake_case = [im.shape[-2:] for im in images] __snake_case = [ nn.functional.pad( SCREAMING_SNAKE_CASE_ , [0, max_size[-1] - size[1], 0, max_size[-2] - size[0]] , value=self.pad_value , ) for size, im in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ] return torch.stack(SCREAMING_SNAKE_CASE_ ), torch.tensor(SCREAMING_SNAKE_CASE_ ) def __call__( self : Optional[int] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Optional[Any]=False ) -> str: with torch.no_grad(): if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): __snake_case = [images] if single_image: assert len(SCREAMING_SNAKE_CASE_ ) == 1 for i in range(len(SCREAMING_SNAKE_CASE_ ) ): if isinstance(images[i] , torch.Tensor ): images.insert(SCREAMING_SNAKE_CASE_ , images.pop(SCREAMING_SNAKE_CASE_ ).to(self.device ).float() ) elif not isinstance(images[i] , torch.Tensor ): images.insert( SCREAMING_SNAKE_CASE_ , torch.as_tensor(img_tensorize(images.pop(SCREAMING_SNAKE_CASE_ ) , input_format=self.input_format ) ) .to(self.device ) .float() , ) # resize smallest edge __snake_case = torch.tensor([im.shape[:2] for im in images] ) __snake_case = self.aug(SCREAMING_SNAKE_CASE_ ) # transpose images and convert to torch tensors # images = [torch.as_tensor(i.astype("float32")).permute(2, 0, 1).to(self.device) for i in images] # now normalize before pad to avoid useless arithmetic __snake_case = [self.normalizer(SCREAMING_SNAKE_CASE_ ) for x in images] # now pad them to do the following operations __snake_case , __snake_case = self.pad(SCREAMING_SNAKE_CASE_ ) # Normalize if self.size_divisibility > 0: raise NotImplementedError() # pad __snake_case = torch.true_divide(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if single_image: return images[0], sizes[0], scales_yx[0] else: return images, sizes, scales_yx def _a (lowercase__ : Tuple , lowercase__ : str ) -> Tuple: """simple docstring""" boxes[:, 0::2] *= scale_yx[:, 1] boxes[:, 1::2] *= scale_yx[:, 0] return boxes def _a (lowercase__ : Union[str, Any] , lowercase__ : Tuple[int, int] ) -> Any: """simple docstring""" assert torch.isfinite(lowercase__ ).all(), "Box tensor contains infinite or NaN!" __snake_case , __snake_case = box_size tensor[:, 0].clamp_(min=0 , max=lowercase__ ) tensor[:, 1].clamp_(min=0 , max=lowercase__ ) tensor[:, 2].clamp_(min=0 , max=lowercase__ ) tensor[:, 3].clamp_(min=0 , max=lowercase__ )
56
"""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
0
def snake_case (UpperCAmelCase__ ) -> list: if len(UpperCAmelCase__ ) < 2: return collection def circle_sort_util(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> bool: UpperCamelCase_: List[Any] = False if low == high: return swapped UpperCamelCase_: Optional[Any] = low UpperCamelCase_: str = high while left < right: if collection[left] > collection[right]: UpperCamelCase_ ,UpperCamelCase_: Union[str, Any] = ( collection[right], collection[left], ) UpperCamelCase_: Any = True left += 1 right -= 1 if left == right and collection[left] > collection[right + 1]: UpperCamelCase_ ,UpperCamelCase_: int = ( collection[right + 1], collection[left], ) UpperCamelCase_: Dict = True UpperCamelCase_: Optional[int] = low + int((high - low) / 2 ) UpperCamelCase_: Optional[int] = circle_sort_util(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: List[str] = circle_sort_util(UpperCAmelCase__ , mid + 1 , UpperCAmelCase__ ) return swapped or left_swap or right_swap UpperCamelCase_: List[Any] = True while is_not_sorted is True: UpperCamelCase_: Union[str, Any] = circle_sort_util(UpperCAmelCase__ , 0 , len(UpperCAmelCase__ ) - 1 ) return collection if __name__ == "__main__": A_ : Any = input('Enter numbers separated by a comma:\n').strip() A_ : Tuple = [int(item) for item in user_input.split(',')] print(circle_sort(unsorted))
57
"""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
0
"""simple docstring""" import argparse import os import re import packaging.version __lowerCAmelCase : Optional[Any] = '''examples/''' __lowerCAmelCase : Union[str, Any] = { '''examples''': (re.compile(R'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''), '''init''': (re.compile(R'''^__version__\s+=\s+"([^"]+)"\s*$''', re.MULTILINE), '''__version__ = "VERSION"\n'''), '''setup''': (re.compile(R'''^(\s*)version\s*=\s*"[^"]+",''', re.MULTILINE), R'''\1version="VERSION",'''), '''doc''': (re.compile(R'''^(\s*)release\s*=\s*"[^"]+"$''', re.MULTILINE), '''release = "VERSION"\n'''), } __lowerCAmelCase : Union[str, Any] = { '''init''': '''src/diffusers/__init__.py''', '''setup''': '''setup.py''', } __lowerCAmelCase : List[Any] = '''README.md''' def __lowerCAmelCase ( __UpperCamelCase : Any , __UpperCamelCase : Optional[int] , __UpperCamelCase : Dict ): '''simple docstring''' with open(__UpperCamelCase , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: snake_case_ : Any = f.read() snake_case_ , snake_case_ : Optional[int] = REPLACE_PATTERNS[pattern] snake_case_ : Union[str, Any] = replace.replace("""VERSION""" , __UpperCamelCase ) snake_case_ : List[Any] = re_pattern.sub(__UpperCamelCase , __UpperCamelCase ) with open(__UpperCamelCase , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.write(__UpperCamelCase ) def __lowerCAmelCase ( __UpperCamelCase : List[str] ): '''simple docstring''' for folder, directories, fnames in os.walk(__UpperCamelCase ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove("""research_projects""" ) if "legacy" in directories: directories.remove("""legacy""" ) for fname in fnames: if fname.endswith(""".py""" ): update_version_in_file(os.path.join(__UpperCamelCase , __UpperCamelCase ) , __UpperCamelCase , pattern="""examples""" ) def __lowerCAmelCase ( __UpperCamelCase : List[str] , __UpperCamelCase : int=False ): '''simple docstring''' for pattern, fname in REPLACE_FILES.items(): update_version_in_file(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) if not patch: update_version_in_examples(__UpperCamelCase ) def __lowerCAmelCase ( ): '''simple docstring''' snake_case_ : Dict = """🤗 Transformers currently provides the following architectures""" snake_case_ : Union[str, Any] = """1. Want to contribute a new model?""" with open(__UpperCamelCase , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: snake_case_ : str = f.readlines() # Find the start of the list. snake_case_ : List[Any] = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 snake_case_ : Optional[int] = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith("""1.""" ): snake_case_ : Any = lines[index].replace( """https://huggingface.co/docs/diffusers/main/model_doc""" , """https://huggingface.co/docs/diffusers/model_doc""" , ) index += 1 with open(__UpperCamelCase , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(__UpperCamelCase ) def __lowerCAmelCase ( ): '''simple docstring''' with open(REPLACE_FILES["""init"""] , """r""" ) as f: snake_case_ : Any = f.read() snake_case_ : Tuple = REPLACE_PATTERNS["""init"""][0].search(__UpperCamelCase ).groups()[0] return packaging.version.parse(__UpperCamelCase ) def __lowerCAmelCase ( __UpperCamelCase : str=False ): '''simple docstring''' snake_case_ : Union[str, Any] = get_version() if patch and default_version.is_devrelease: raise ValueError("""Can't create a patch version from the dev branch, checkout a released version!""" ) if default_version.is_devrelease: snake_case_ : str = default_version.base_version elif patch: snake_case_ : str = F'{default_version.major}.{default_version.minor}.{default_version.micro + 1}' else: snake_case_ : str = F'{default_version.major}.{default_version.minor + 1}.0' # Now let's ask nicely if that's the right one. snake_case_ : int = input(F'Which version are you releasing? [{default_version}]' ) if len(__UpperCamelCase ) == 0: snake_case_ : Optional[int] = default_version print(F'Updating version to {version}.' ) global_version_update(__UpperCamelCase , patch=__UpperCamelCase ) def __lowerCAmelCase ( ): '''simple docstring''' snake_case_ : Dict = get_version() snake_case_ : str = F'{current_version.major}.{current_version.minor + 1}.0.dev0' snake_case_ : Tuple = current_version.base_version # Check with the user we got that right. snake_case_ : Optional[int] = input(F'Which version are we developing now? [{dev_version}]' ) if len(__UpperCamelCase ) == 0: snake_case_ : Dict = dev_version print(F'Updating version to {version}.' ) global_version_update(__UpperCamelCase ) # print("Cleaning main README, don't forget to run `make fix-copies`.") # clean_main_ref_in_model_list() if __name__ == "__main__": __lowerCAmelCase : Dict = argparse.ArgumentParser() parser.add_argument('''--post_release''', action='''store_true''', help='''Whether this is pre or post release.''') parser.add_argument('''--patch''', action='''store_true''', help='''Whether or not this is a patch release.''') __lowerCAmelCase : str = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print('''Nothing to do after a patch :-)''') else: post_release_work()
58
"""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
0
import math import sys def lowerCAmelCase_ ( __a ) -> int: """simple docstring""" if number != int(__a ): raise ValueError("the value of input must be a natural number" ) if number < 0: raise ValueError("the value of input must not be a negative number" ) if number == 0: return 1 lowerCamelCase__: int =[-1] * (number + 1) lowerCamelCase__: Tuple =0 for i in range(1 , number + 1 ): lowerCamelCase__: List[Any] =sys.maxsize lowerCamelCase__: Union[str, Any] =int(math.sqrt(__a ) ) for j in range(1 , root + 1 ): lowerCamelCase__: Tuple =1 + answers[i - (j**2)] lowerCamelCase__: Union[str, Any] =min(__a , __a ) lowerCamelCase__: Optional[int] =answer return answers[number] if __name__ == "__main__": import doctest doctest.testmod()
59
"""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
0
lowerCAmelCase_ = 8.314_462 # Unit - J mol-1 K-1 def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> float: """simple docstring""" if moles < 0 or kelvin < 0 or volume < 0: raise ValueError('''Invalid inputs. Enter positive value.''' ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> float: """simple docstring""" if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError('''Invalid inputs. Enter positive value.''' ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure if __name__ == "__main__": from doctest import testmod testmod()
60
"""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
0
import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, TimesformerForVideoClassification, TimesformerModel, ) from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class __lowerCamelCase : """simple docstring""" def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple=13 , SCREAMING_SNAKE_CASE__ : Optional[Any]=10 , SCREAMING_SNAKE_CASE__ : Optional[int]=3 , SCREAMING_SNAKE_CASE__ : List[str]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=2 , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : Optional[int]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : List[Any]=37 , SCREAMING_SNAKE_CASE__ : int="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Any=10 , SCREAMING_SNAKE_CASE__ : int=0.02 , SCREAMING_SNAKE_CASE__ : Tuple="divided_space_time" , SCREAMING_SNAKE_CASE__ : Optional[int]=None , ) -> List[str]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = image_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_frames lowerCAmelCase__ = is_training lowerCAmelCase__ = use_labels lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = attention_type lowerCAmelCase__ = initializer_range lowerCAmelCase__ = scope lowerCAmelCase__ = num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token lowerCAmelCase__ = (image_size // patch_size) ** 2 lowerCAmelCase__ = (num_frames) * self.num_patches_per_frame + 1 def a ( self : int ) -> Tuple: lowerCAmelCase__ = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase__ = None if self.use_labels: lowerCAmelCase__ = ids_tensor([self.batch_size] , self.num_labels ) lowerCAmelCase__ = self.get_config() return config, pixel_values, labels def a ( self : List[Any] ) -> Any: lowerCAmelCase__ = TimesformerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , initializer_range=self.initializer_range , attention_type=self.attention_type , ) lowerCAmelCase__ = self.num_labels return config def a ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: lowerCAmelCase__ = TimesformerModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple ) -> Tuple: lowerCAmelCase__ = TimesformerForVideoClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) # verify the logits shape lowerCAmelCase__ = torch.Size((self.batch_size, self.num_labels) ) self.parent.assertEqual(result.logits.shape , SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> Dict: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else () snake_case__ = ( {"feature-extraction": TimesformerModel, "video-classification": TimesformerForVideoClassification} if is_torch_available() else {} ) snake_case__ = False snake_case__ = False snake_case__ = False snake_case__ = False def a ( self : List[str] ) -> List[Any]: lowerCAmelCase__ = TimesformerModelTester(self ) lowerCAmelCase__ = ConfigTester( self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ , hidden_size=37 ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple=False ) -> str: lowerCAmelCase__ = copy.deepcopy(SCREAMING_SNAKE_CASE__ ) if return_labels: if model_class in get_values(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) return inputs_dict def a ( self : Optional[Any] ) -> List[str]: self.config_tester.run_common_tests() @unittest.skip(reason="TimeSformer does not use inputs_embeds" ) def a ( self : Union[str, Any] ) -> Tuple: pass def a ( self : Dict ) -> List[str]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowerCAmelCase__ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__ , nn.Linear ) ) def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase__ = [*signature.parameters.keys()] lowerCAmelCase__ = ["pixel_values"] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] ) -> Tuple: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*SCREAMING_SNAKE_CASE__ ) @slow def a ( self : str ) -> Tuple: for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase__ = TimesformerModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Dict: if not self.has_attentions: pass else: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ = True for model_class in self.all_model_classes: lowerCAmelCase__ = self.model_tester.seq_length lowerCAmelCase__ = self.model_tester.num_frames lowerCAmelCase__ = True lowerCAmelCase__ = False lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) lowerCAmelCase__ = len(SCREAMING_SNAKE_CASE__ ) # Check attention is always last and order is fine lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(out_len + 1 , len(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) def a ( self : List[str] ) -> Any: def check_hidden_states_output(SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] ): lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.hidden_states lowerCAmelCase__ = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _A ( ): """simple docstring""" lowerCAmelCase__ = hf_hub_download( repo_id="hf-internal-testing/spaghetti-video" , filename="eating_spaghetti.npy" , repo_type="dataset" ) lowerCAmelCase__ = np.load(lowerCAmelCase_ ) return list(lowerCAmelCase_ ) @require_torch @require_vision class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @cached_property def a ( self : Optional[Any] ) -> Union[str, Any]: # logits were tested with a different mean and std, so we use the same here return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) if is_vision_available() else None ) @slow def a ( self : Optional[Any] ) -> str: lowerCAmelCase__ = TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400" ).to( SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.default_image_processor lowerCAmelCase__ = prepare_video() lowerCAmelCase__ = image_processor(video[:8] , return_tensors="pt" ).to(SCREAMING_SNAKE_CASE__ ) # forward pass with torch.no_grad(): lowerCAmelCase__ = model(**SCREAMING_SNAKE_CASE__ ) # verify the logits lowerCAmelCase__ = torch.Size((1, 400) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = torch.tensor([-0.3_016, -0.7_713, -0.4_205] ).to(SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
"""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
0
import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def lowerCamelCase__ ( lowercase ): """simple docstring""" if is_torch_version("<" , "2.0.0" ) or not hasattr(lowercase , "_dynamo" ): return False return isinstance(lowercase , torch._dynamo.eval_frame.OptimizedModule ) def lowerCamelCase__ ( lowercase , lowercase = True ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) SCREAMING_SNAKE_CASE : Optional[int] = is_compiled_module(lowercase ) if is_compiled: SCREAMING_SNAKE_CASE : Optional[Any] = model SCREAMING_SNAKE_CASE : int = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(lowercase , lowercase ): SCREAMING_SNAKE_CASE : List[str] = model.module if not keep_fpaa_wrapper: SCREAMING_SNAKE_CASE : Tuple = getattr(lowercase , "forward" ) SCREAMING_SNAKE_CASE : Any = model.__dict__.pop("_original_forward" , lowercase ) if original_forward is not None: while hasattr(lowercase , "__wrapped__" ): SCREAMING_SNAKE_CASE : Any = forward.__wrapped__ if forward == original_forward: break SCREAMING_SNAKE_CASE : Optional[Any] = forward if getattr(lowercase , "_converted_to_transformer_engine" , lowercase ): convert_model(lowercase , to_transformer_engine=lowercase ) if is_compiled: SCREAMING_SNAKE_CASE : str = model SCREAMING_SNAKE_CASE : Optional[Any] = compiled_model return model def lowerCamelCase__ ( ): """simple docstring""" PartialState().wait_for_everyone() def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" if PartialState().distributed_type == DistributedType.TPU: xm.save(lowercase , lowercase ) elif PartialState().local_process_index == 0: torch.save(lowercase , lowercase ) @contextmanager def lowerCamelCase__ ( **lowercase ): """simple docstring""" for key, value in kwargs.items(): SCREAMING_SNAKE_CASE : str = str(lowercase ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def lowerCamelCase__ ( lowercase ): """simple docstring""" if not hasattr(lowercase , "__qualname__" ) and not hasattr(lowercase , "__name__" ): SCREAMING_SNAKE_CASE : int = getattr(lowercase , "__class__" , lowercase ) if hasattr(lowercase , "__qualname__" ): return obj.__qualname__ if hasattr(lowercase , "__name__" ): return obj.__name__ return str(lowercase ) def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" for key, value in source.items(): if isinstance(lowercase , lowercase ): SCREAMING_SNAKE_CASE : List[str] = destination.setdefault(lowercase , {} ) merge_dicts(lowercase , lowercase ) else: SCREAMING_SNAKE_CASE : Any = value return destination def lowerCamelCase__ ( lowercase = None ): """simple docstring""" if port is None: SCREAMING_SNAKE_CASE : str = 29500 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(("localhost", port) ) == 0
62
"""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
0
import numpy as np import torch from imwatermark import WatermarkEncoder # Copied from https://github.com/Stability-AI/generative-models/blob/613af104c6b85184091d42d374fef420eddb356d/scripts/demo/streamlit_helpers.py#L66 a : Optional[Any] = 0B1011_0011_1110_1100_1001_0000_0111_1011_1011_0001_1001_1110 # bin(x)[2:] gives bits of x as str, use int to convert them to 0/1 a : int = [int(bit) for bit in bin(WATERMARK_MESSAGE)[2:]] class a : """simple docstring""" def __init__( self : int ) -> Optional[Any]: __UpperCAmelCase : Tuple = WATERMARK_BITS __UpperCAmelCase : Tuple = WatermarkEncoder() self.encoder.set_watermark("""bits""" , self.watermark ) def UpperCAmelCase ( self : Dict , __lowercase : torch.FloatTensor ) -> Optional[Any]: # can't encode images that are smaller than 256 if images.shape[-1] < 256: return images __UpperCAmelCase : Tuple = (255 * (images / 2 + 0.5)).cpu().permute(0 , 2 , 3 , 1 ).float().numpy() __UpperCAmelCase : Tuple = [self.encoder.encode(__lowercase , """dwtDct""" ) for image in images] __UpperCAmelCase : int = torch.from_numpy(np.array(__lowercase ) ).permute(0 , 3 , 1 , 2 ) __UpperCAmelCase : Optional[Any] = torch.clamp(2 * (images / 255 - 0.5) , min=-1.0 , max=1.0 ) return images
63
"""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
0
class _lowerCamelCase : def __init__( self ) -> List[str]: SCREAMING_SNAKE_CASE__: Tuple= '''''' SCREAMING_SNAKE_CASE__: int= '''''' SCREAMING_SNAKE_CASE__: Optional[int]= [] def UpperCamelCase_ ( self , lowerCAmelCase , lowerCAmelCase ) -> int: if m == -1: return n + 1 elif n == -1: return m + 1 elif self.dp[m][n] > -1: return self.dp[m][n] else: if self.worda[m] == self.worda[n]: SCREAMING_SNAKE_CASE__: Optional[int]= self.__min_dist_top_down_dp(m - 1 , n - 1 ) else: SCREAMING_SNAKE_CASE__: List[str]= self.__min_dist_top_down_dp(lowerCAmelCase , n - 1 ) SCREAMING_SNAKE_CASE__: str= self.__min_dist_top_down_dp(m - 1 , lowerCAmelCase ) SCREAMING_SNAKE_CASE__: Optional[Any]= self.__min_dist_top_down_dp(m - 1 , n - 1 ) SCREAMING_SNAKE_CASE__: Optional[int]= 1 + min(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) return self.dp[m][n] def UpperCamelCase_ ( self , lowerCAmelCase , lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__: Optional[int]= worda SCREAMING_SNAKE_CASE__: Optional[int]= worda SCREAMING_SNAKE_CASE__: Optional[int]= [[-1 for _ in range(len(lowerCAmelCase ) )] for _ in range(len(lowerCAmelCase ) )] return self.__min_dist_top_down_dp(len(lowerCAmelCase ) - 1 , len(lowerCAmelCase ) - 1 ) def UpperCamelCase_ ( self , lowerCAmelCase , lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__: int= worda SCREAMING_SNAKE_CASE__: Any= worda SCREAMING_SNAKE_CASE__: List[str]= len(lowerCAmelCase ) SCREAMING_SNAKE_CASE__: int= len(lowerCAmelCase ) SCREAMING_SNAKE_CASE__: Union[str, Any]= [[0 for _ in range(n + 1 )] for _ in range(m + 1 )] for i in range(m + 1 ): for j in range(n + 1 ): if i == 0: # first string is empty SCREAMING_SNAKE_CASE__: Optional[Any]= j elif j == 0: # second string is empty SCREAMING_SNAKE_CASE__: List[Any]= i elif worda[i - 1] == worda[j - 1]: # last characters are equal SCREAMING_SNAKE_CASE__: Dict= self.dp[i - 1][j - 1] else: SCREAMING_SNAKE_CASE__: List[Any]= self.dp[i][j - 1] SCREAMING_SNAKE_CASE__: int= self.dp[i - 1][j] SCREAMING_SNAKE_CASE__: Tuple= self.dp[i - 1][j - 1] SCREAMING_SNAKE_CASE__: str= 1 + min(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) return self.dp[m][n] if __name__ == "__main__": lowercase_ : Any = EditDistance() print('****************** Testing Edit Distance DP Algorithm ******************') print() lowercase_ : Optional[Any] = input('Enter the first string: ').strip() lowercase_ : List[Any] = input('Enter the second string: ').strip() print() print(f'''The minimum edit distance is: {solver.min_dist_top_down(Sa, Sa)}''') print(f'''The minimum edit distance is: {solver.min_dist_bottom_up(Sa, Sa)}''') print() print('*************** End of Testing Edit Distance DP Algorithm ***************')
64
"""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
0
"""simple docstring""" import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=__lowerCamelCase ) class __lowercase ( __lowerCamelCase ): snake_case_ = field(default="""image-classification""" , metadata={"""include_in_asdict_even_if_is_default""": True} ) snake_case_ = Features({"""image""": Image()} ) snake_case_ = Features({"""labels""": ClassLabel} ) snake_case_ = "image" snake_case_ = "labels" def __lowercase ( self : Dict ,A : str ): '''simple docstring''' if self.label_column not in features: raise ValueError(f"Column {self.label_column} is not present in features." ) if not isinstance(features[self.label_column] ,A ): raise ValueError(f"Column {self.label_column} is not a ClassLabel." ) UpperCAmelCase__ : List[str] = copy.deepcopy(self ) UpperCAmelCase__ : Optional[Any] = self.label_schema.copy() UpperCAmelCase__ : List[Any] = features[self.label_column] UpperCAmelCase__ : List[Any] = label_schema return task_template @property def __lowercase ( self : int ): '''simple docstring''' return { self.image_column: "image", self.label_column: "labels", }
65
"""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
0
import unittest from transformers import AutoTokenizer, FalconConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, ) class lowerCAmelCase_ : def __init__( self , _lowerCAmelCase , _lowerCAmelCase=3 , _lowerCAmelCase=7 , _lowerCAmelCase=True , _lowerCAmelCase=True , _lowerCAmelCase=False , _lowerCAmelCase=True , _lowerCAmelCase=9_9 , _lowerCAmelCase=3_2 , _lowerCAmelCase=5 , _lowerCAmelCase=4 , _lowerCAmelCase=3_7 , _lowerCAmelCase="gelu" , _lowerCAmelCase=0.1 , _lowerCAmelCase=0.1 , _lowerCAmelCase=5_1_2 , _lowerCAmelCase=1_6 , _lowerCAmelCase=2 , _lowerCAmelCase=0.02 , _lowerCAmelCase=3 , _lowerCAmelCase=4 , _lowerCAmelCase=None , ): _lowercase : Dict = parent _lowercase : Optional[int] = batch_size _lowercase : List[str] = seq_length _lowercase : List[str] = is_training _lowercase : Optional[int] = use_input_mask _lowercase : Union[str, Any] = use_token_type_ids _lowercase : List[str] = use_labels _lowercase : Tuple = vocab_size _lowercase : Tuple = hidden_size _lowercase : Any = num_hidden_layers _lowercase : Union[str, Any] = num_attention_heads _lowercase : Dict = intermediate_size _lowercase : List[str] = hidden_act _lowercase : Any = hidden_dropout_prob _lowercase : Dict = attention_probs_dropout_prob _lowercase : Optional[int] = max_position_embeddings _lowercase : Optional[Any] = type_vocab_size _lowercase : str = type_sequence_label_size _lowercase : str = initializer_range _lowercase : List[Any] = num_labels _lowercase : List[str] = num_choices _lowercase : Union[str, Any] = scope def __a ( self ): _lowercase : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _lowercase : str = None if self.use_input_mask: _lowercase : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) _lowercase : str = None _lowercase : List[str] = None _lowercase : Optional[int] = None _lowercase : List[str] = None if self.use_labels: _lowercase : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowercase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _lowercase : Union[str, Any] = ids_tensor([self.batch_size] , self.num_choices ) _lowercase : Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __a ( self ): return FalconConfig( 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=_lowerCAmelCase , initializer_range=self.initializer_range , pad_token_id=1 , new_decoder_architecture=_lowerCAmelCase , ) def __a ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): _lowercase : Dict = FalconModel(config=_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() _lowercase : Optional[Any] = model(_lowerCAmelCase , attention_mask=_lowerCAmelCase ) _lowercase : str = model(_lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __a ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , ): _lowercase : Union[str, Any] = True _lowercase : str = FalconModel(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() _lowercase : Any = model( _lowerCAmelCase , attention_mask=_lowerCAmelCase , encoder_hidden_states=_lowerCAmelCase , encoder_attention_mask=_lowerCAmelCase , ) _lowercase : List[Any] = model( _lowerCAmelCase , attention_mask=_lowerCAmelCase , encoder_hidden_states=_lowerCAmelCase , ) _lowercase : Tuple = model(_lowerCAmelCase , attention_mask=_lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __a ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , ): _lowercase : Union[str, Any] = FalconForCausalLM(config=_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() _lowercase : Tuple = model(_lowerCAmelCase , attention_mask=_lowerCAmelCase , labels=_lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __a ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , ): _lowercase : Optional[Any] = True _lowercase : Dict = True _lowercase : Optional[int] = FalconForCausalLM(config=_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() # first forward pass _lowercase : Tuple = model( _lowerCAmelCase , attention_mask=_lowerCAmelCase , encoder_hidden_states=_lowerCAmelCase , encoder_attention_mask=_lowerCAmelCase , use_cache=_lowerCAmelCase , ) _lowercase : Optional[Any] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids _lowercase : List[str] = ids_tensor((self.batch_size, 3) , config.vocab_size ) _lowercase : List[Any] = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and _lowercase : Union[str, Any] = torch.cat([input_ids, next_tokens] , dim=-1 ) _lowercase : Optional[int] = torch.cat([input_mask, next_mask] , dim=-1 ) _lowercase : Tuple = model( _lowerCAmelCase , attention_mask=_lowerCAmelCase , encoder_hidden_states=_lowerCAmelCase , encoder_attention_mask=_lowerCAmelCase , output_hidden_states=_lowerCAmelCase , )['hidden_states'][0] _lowercase : Any = model( _lowerCAmelCase , attention_mask=_lowerCAmelCase , encoder_hidden_states=_lowerCAmelCase , encoder_attention_mask=_lowerCAmelCase , past_key_values=_lowerCAmelCase , output_hidden_states=_lowerCAmelCase , )['hidden_states'][0] # select random slice _lowercase : Union[str, Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item() _lowercase : Union[str, Any] = output_from_no_past[:, -3:, random_slice_idx].detach() _lowercase : Tuple = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(_lowerCAmelCase , _lowerCAmelCase , atol=1E-3 ) ) def __a ( self ): _lowercase : Optional[int] = self.prepare_config_and_inputs() ( ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ) : Union[str, Any] = config_and_inputs _lowercase : List[Any] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class lowerCAmelCase_ ( __snake_case , __snake_case , __snake_case , unittest.TestCase ): _UpperCamelCase : Union[str, Any] = ( ( FalconModel, FalconForCausalLM, FalconForSequenceClassification, FalconForTokenClassification, FalconForQuestionAnswering, ) if is_torch_available() else () ) _UpperCamelCase : Optional[Any] = (FalconForCausalLM,) if is_torch_available() else () _UpperCamelCase : str = ( { "feature-extraction": FalconModel, "text-classification": FalconForSequenceClassification, "text-generation": FalconForCausalLM, "question-answering": FalconForQuestionAnswering, "token-classification": FalconForTokenClassification, "zero-shot": FalconForSequenceClassification, } if is_torch_available() else {} ) _UpperCamelCase : Tuple = False _UpperCamelCase : str = False def __a ( self ): _lowercase : Dict = FalconModelTester(self ) _lowercase : Dict = ConfigTester(self , config_class=_lowerCAmelCase , hidden_size=3_7 ) def __a ( self ): self.config_tester.run_common_tests() def __a ( self ): _lowercase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCAmelCase ) def __a ( self ): _lowercase , *_lowercase : Dict = self.model_tester.prepare_config_and_inputs() for alibi in [True, False]: _lowercase : Union[str, Any] = alibi self.model_tester.create_and_check_model(_lowerCAmelCase , *_lowerCAmelCase ) def __a ( self ): _lowercase , _lowercase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() _lowercase : Optional[Any] = 3 _lowercase : int = input_dict['input_ids'] _lowercase : List[Any] = input_ids.ne(1 ).to(_lowerCAmelCase ) _lowercase : Optional[int] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) _lowercase : List[str] = FalconForSequenceClassification(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() _lowercase : Tuple = model(_lowerCAmelCase , attention_mask=_lowerCAmelCase , labels=_lowerCAmelCase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __a ( self ): _lowercase , _lowercase : Any = self.model_tester.prepare_config_and_inputs_for_common() _lowercase : List[Any] = 3 _lowercase : Tuple = 'single_label_classification' _lowercase : Dict = input_dict['input_ids'] _lowercase : Union[str, Any] = input_ids.ne(1 ).to(_lowerCAmelCase ) _lowercase : Dict = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) _lowercase : Tuple = FalconForSequenceClassification(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() _lowercase : Optional[Any] = model(_lowerCAmelCase , attention_mask=_lowerCAmelCase , labels=_lowerCAmelCase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __a ( self ): _lowercase , _lowercase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() _lowercase : Optional[Any] = input_dict['input_ids'] _lowercase : Union[str, Any] = FalconForCausalLM(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() _lowercase : List[Any] = model(_lowerCAmelCase , use_cache=_lowerCAmelCase ) _lowercase : int = input_ids.shape[0] _lowercase : str = model._convert_to_rw_cache(result.past_key_values ) _lowercase : List[str] = model._convert_cache_to_standard_format(_lowerCAmelCase , _lowerCAmelCase ) for layer in range(len(_lowerCAmelCase ) ): for tensor_idx in range(2 ): self.assertTrue(rw_cache[layer][tensor_idx].ndim == 3 ) self.assertTrue(result.past_key_values[layer][tensor_idx].ndim == 4 ) self.assertTrue( torch.all(result.past_key_values[layer][tensor_idx] == standard_cache[layer][tensor_idx] ) ) def __a ( self ): _lowercase , _lowercase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() _lowercase : List[str] = 3 _lowercase : List[Any] = 'multi_label_classification' _lowercase : Union[str, Any] = input_dict['input_ids'] _lowercase : int = input_ids.ne(1 ).to(_lowerCAmelCase ) _lowercase : List[str] = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) _lowercase : Dict = FalconForSequenceClassification(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() _lowercase : Optional[Any] = model(_lowerCAmelCase , attention_mask=_lowerCAmelCase , labels=_lowerCAmelCase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __a ( self ): # Falcon can have different numbers of KV-heads than the number of query heads, so we need # to override this test to use the right head counts. for model_class in self.all_generative_model_classes: _lowercase , _lowercase : Any = self.model_tester.prepare_config_and_inputs_for_common() # If it doesn't support cache, pass the test if not hasattr(_lowerCAmelCase , 'use_cache' ): return _lowercase : Any = model_class(_lowerCAmelCase ).to(_lowerCAmelCase ) if "use_cache" not in inputs: _lowercase : Optional[int] = True _lowercase : Tuple = model(**_lowerCAmelCase ) # If "past_key_values" is not returned, pass the test (e.g. RWKV uses a different cache name and format) if "past_key_values" not in outputs: return _lowercase : str = ( getattr(_lowerCAmelCase , 'decoder_layers' , _lowerCAmelCase ) or getattr(_lowerCAmelCase , 'num_decoder_layers' , _lowerCAmelCase ) or config.num_hidden_layers ) _lowercase : Tuple = getattr(_lowerCAmelCase , 'num_kv_heads' , config.num_attention_heads ) _lowercase : Any = getattr(_lowerCAmelCase , 'd_model' , config.hidden_size ) _lowercase : List[Any] = embed_dim // num_attention_heads _lowercase : List[str] = outputs['past_key_values'] self.assertEqual(len(_lowerCAmelCase ) , _lowerCAmelCase ) _lowercase , _lowercase : Optional[Any] = inputs['input_ids'].shape for i in range(_lowerCAmelCase ): if config.new_decoder_architecture: _lowercase : Dict = config.num_attention_heads elif config.multi_query: _lowercase : Dict = 1 self.assertEqual(len(past_kv[0] ) , 2 ) # K V for the decoder = 2 self.assertEqual( past_kv[i][0].shape , (batch_size, num_attention_heads, seq_length, per_head_embed_dim) ) self.assertEqual( past_kv[i][1].shape , (batch_size, num_attention_heads, seq_length, per_head_embed_dim) ) @require_torch class lowerCAmelCase_ ( unittest.TestCase ): @slow def __a ( self ): _lowercase : List[str] = AutoTokenizer.from_pretrained('Rocketknight1/falcon-rw-1b' ) _lowercase : Any = FalconForCausalLM.from_pretrained('Rocketknight1/falcon-rw-1b' ) model.eval() model.to(_lowerCAmelCase ) _lowercase : Union[str, Any] = tokenizer('My favorite food is' , return_tensors='pt' ).to(_lowerCAmelCase ) _lowercase : Tuple = ( 'My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday.' ) _lowercase : Optional[Any] = model.generate(**_lowerCAmelCase , do_sample=_lowerCAmelCase , max_new_tokens=1_9 ) _lowercase : Tuple = tokenizer.batch_decode(_lowerCAmelCase )[0] self.assertEqual(_lowerCAmelCase , _lowerCAmelCase ) @slow def __a ( self ): # The big models are way too big for the CI, so we use tiny random models that resemble their # architectures but with much smaller and fewer layers for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]: _lowercase : List[str] = AutoTokenizer.from_pretrained(_lowerCAmelCase ) _lowercase : str = FalconForCausalLM.from_pretrained(_lowerCAmelCase ) model.eval() model.to(_lowerCAmelCase ) _lowercase : str = tokenizer('My favorite food is' , return_tensors='pt' ).to(_lowerCAmelCase ) # We just test that these run without errors - the models are randomly initialized # and so the actual text outputs will be garbage model.generate(**_lowerCAmelCase , do_sample=_lowerCAmelCase , max_new_tokens=4 ) model.generate(**_lowerCAmelCase , do_sample=_lowerCAmelCase , max_new_tokens=4 ) model.generate(**_lowerCAmelCase , num_beams=2 , max_new_tokens=4 ) @slow def __a ( self ): # The big models are way too big for the CI, so we use tiny random models that resemble their # architectures but with much smaller and fewer layers with torch.no_grad(): for repo in [ "Rocketknight1/falcon-rw-1b", "Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b", ]: _lowercase : str = AutoTokenizer.from_pretrained(_lowerCAmelCase ) _lowercase : Union[str, Any] = FalconForCausalLM.from_pretrained(_lowerCAmelCase ) model.eval() model.to(device=_lowerCAmelCase ) _lowercase : Any = tokenizer('My favorite food is' , return_tensors='pt' ).to(_lowerCAmelCase ) # Test results are the same with and without cache _lowercase : str = model.generate(**_lowerCAmelCase , do_sample=_lowerCAmelCase , max_new_tokens=2_0 , use_cache=_lowerCAmelCase ) _lowercase : Dict = model.generate(**_lowerCAmelCase , do_sample=_lowerCAmelCase , max_new_tokens=2_0 , use_cache=_lowerCAmelCase ) self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0 )
66
"""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
0
from ....configuration_utils import PretrainedConfig from ....utils import logging snake_case = logging.get_logger(__name__) snake_case = { """CarlCochet/trajectory-transformer-halfcheetah-medium-v2""": ( """https://huggingface.co/CarlCochet/trajectory-transformer-halfcheetah-medium-v2/resolve/main/config.json""" ), # See all TrajectoryTransformer models at https://huggingface.co/models?filter=trajectory_transformer } class A_ ( UpperCAmelCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = '''trajectory_transformer''' SCREAMING_SNAKE_CASE_ : List[Any] = ['''past_key_values'''] SCREAMING_SNAKE_CASE_ : Union[str, Any] = { '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self : str ,__A : Any=100 ,__A : Dict=5 ,__A : Tuple=1 ,__A : Union[str, Any]=1 ,__A : Optional[Any]=249 ,__A : Optional[Any]=6 ,__A : List[Any]=17 ,__A : List[str]=25 ,__A : Optional[int]=4 ,__A : Dict=4 ,__A : Dict=128 ,__A : Optional[int]=0.1 ,__A : int=0.1 ,__A : Tuple=0.1 ,__A : Tuple=0.0006 ,__A : List[Any]=512 ,__A : Tuple=0.02 ,__A : List[Any]=1e-12 ,__A : List[Any]=1 ,__A : List[Any]=True ,__A : Dict=1 ,__A : Any=5_0256 ,__A : int=5_0256 ,**__A : Union[str, Any] ,) -> List[str]: _lowercase = vocab_size _lowercase = action_weight _lowercase = reward_weight _lowercase = value_weight _lowercase = max_position_embeddings _lowercase = block_size _lowercase = action_dim _lowercase = observation_dim _lowercase = transition_dim _lowercase = learning_rate _lowercase = n_layer _lowercase = n_head _lowercase = n_embd _lowercase = embd_pdrop _lowercase = attn_pdrop _lowercase = resid_pdrop _lowercase = initializer_range _lowercase = layer_norm_eps _lowercase = kaiming_initializer_range _lowercase = use_cache super().__init__(pad_token_id=__A ,bos_token_id=__A ,eos_token_id=__A ,**__A )
67
"""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
0
def lowercase__ ( A_: Tuple ) -> str: """simple docstring""" __UpperCAmelCase =len(A_ ) __UpperCAmelCase =sum(A_ ) __UpperCAmelCase =[[False for x in range(s + 1 )] for y in range(n + 1 )] for i in range(1 , n + 1 ): __UpperCAmelCase =True for i in range(1 , s + 1 ): __UpperCAmelCase =False for i in range(1 , n + 1 ): for j in range(1 , s + 1 ): __UpperCAmelCase =dp[i][j - 1] if arr[i - 1] <= j: __UpperCAmelCase =dp[i][j] or dp[i - 1][j - arr[i - 1]] for j in range(int(s / 2 ) , -1 , -1 ): if dp[n][j] is True: __UpperCAmelCase =s - 2 * j break return diff
68
"""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
0
'''simple docstring''' import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( AlbertTokenizer, AutoTokenizer, BertTokenizer, BertTokenizerFast, GPTaTokenizerFast, is_tokenizers_available, ) from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers from transformers.tokenization_utils import Trie sys.path.append(str(Path(__file__).parent.parent / '''utils''')) from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def A ( self : Optional[Any] ): """simple docstring""" __snake_case = mock.Mock() __snake_case = 500 __snake_case = {} __snake_case = HTTPError __snake_case = {} # Download this model to make sure it's in the cache. __snake_case = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert" ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch("requests.Session.request" , return_value=a_ ) as mock_head: __snake_case = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert" ) # This check we did call the fake head request mock_head.assert_called() @require_tokenizers def A ( self : Optional[Any] ): """simple docstring""" __snake_case = mock.Mock() __snake_case = 500 __snake_case = {} __snake_case = HTTPError __snake_case = {} # Download this model to make sure it's in the cache. __snake_case = GPTaTokenizerFast.from_pretrained("gpt2" ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch("requests.Session.request" , return_value=a_ ) as mock_head: __snake_case = GPTaTokenizerFast.from_pretrained("gpt2" ) # This check we did call the fake head request mock_head.assert_called() def A ( self : Optional[Any] ): """simple docstring""" try: __snake_case = tempfile.mktemp() with open(a_ , "wb" ) as f: http_get("https://huggingface.co/albert-base-v1/resolve/main/spiece.model" , a_ ) __snake_case = AlbertTokenizer.from_pretrained(a_ ) finally: os.remove(a_ ) # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in # the current folder and have the right name. if os.path.isfile("tokenizer.json" ): # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it. return try: with open("tokenizer.json" , "wb" ) as f: http_get("https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json" , a_ ) __snake_case = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000 self.assertEqual(tokenizer.vocab_size , 1_000 ) # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. finally: os.remove("tokenizer.json" ) def A ( self : str ): """simple docstring""" __snake_case = AlbertTokenizer.from_pretrained("https://huggingface.co/albert-base-v1/resolve/main/spiece.model" ) @is_staging_test class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): __SCREAMING_SNAKE_CASE = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """bla""", """blou"""] @classmethod def A ( cls : List[Any] ): """simple docstring""" __snake_case = TOKEN HfFolder.save_token(a_ ) @classmethod def A ( cls : List[Any] ): """simple docstring""" try: delete_repo(token=cls._token , repo_id="test-tokenizer" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="valid_org/test-tokenizer-org" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="test-dynamic-tokenizer" ) except HTTPError: pass def A ( self : int ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: __snake_case = os.path.join(a_ , "vocab.txt" ) with open(a_ , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) ) __snake_case = BertTokenizer(a_ ) tokenizer.push_to_hub("test-tokenizer" , use_auth_token=self._token ) __snake_case = BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer''' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) # Reset repo delete_repo(token=self._token , repo_id="test-tokenizer" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(a_ , repo_id="test-tokenizer" , push_to_hub=a_ , use_auth_token=self._token ) __snake_case = BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer''' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) def A ( self : int ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: __snake_case = os.path.join(a_ , "vocab.txt" ) with open(a_ , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) ) __snake_case = BertTokenizer(a_ ) tokenizer.push_to_hub("valid_org/test-tokenizer-org" , use_auth_token=self._token ) __snake_case = BertTokenizer.from_pretrained("valid_org/test-tokenizer-org" ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) # Reset repo delete_repo(token=self._token , repo_id="valid_org/test-tokenizer-org" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained( a_ , repo_id="valid_org/test-tokenizer-org" , push_to_hub=a_ , use_auth_token=self._token ) __snake_case = BertTokenizer.from_pretrained("valid_org/test-tokenizer-org" ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) @require_tokenizers def A ( self : List[str] ): """simple docstring""" CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: __snake_case = os.path.join(a_ , "vocab.txt" ) with open(a_ , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) ) __snake_case = CustomTokenizer(a_ ) # No fast custom tokenizer tokenizer.push_to_hub("test-dynamic-tokenizer" , use_auth_token=self._token ) __snake_case = AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer''' , trust_remote_code=a_ ) # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , "CustomTokenizer" ) # Fast and slow custom tokenizer CustomTokenizerFast.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: __snake_case = os.path.join(a_ , "vocab.txt" ) with open(a_ , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) ) __snake_case = BertTokenizerFast.from_pretrained(a_ ) bert_tokenizer.save_pretrained(a_ ) __snake_case = CustomTokenizerFast.from_pretrained(a_ ) tokenizer.push_to_hub("test-dynamic-tokenizer" , use_auth_token=self._token ) __snake_case = AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer''' , trust_remote_code=a_ ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , "CustomTokenizerFast" ) __snake_case = AutoTokenizer.from_pretrained( f'''{USER}/test-dynamic-tokenizer''' , use_fast=a_ , trust_remote_code=a_ ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , "CustomTokenizer" ) class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def A ( self : Optional[int] ): """simple docstring""" __snake_case = Trie() trie.add("Hello 友達" ) self.assertEqual(trie.data , {"H": {"e": {"l": {"l": {"o": {" ": {"友": {"達": {"": 1}}}}}}}}} ) trie.add("Hello" ) trie.data self.assertEqual(trie.data , {"H": {"e": {"l": {"l": {"o": {"": 1, " ": {"友": {"達": {"": 1}}}}}}}}} ) def A ( self : str ): """simple docstring""" __snake_case = Trie() self.assertEqual(trie.split("[CLS] This is a extra_id_100" ) , ["[CLS] This is a extra_id_100"] ) trie.add("[CLS]" ) trie.add("extra_id_1" ) trie.add("extra_id_100" ) self.assertEqual(trie.split("[CLS] This is a extra_id_100" ) , ["[CLS]", " This is a ", "extra_id_100"] ) def A ( self : Optional[Any] ): """simple docstring""" __snake_case = Trie() trie.add("A" ) self.assertEqual(trie.split("ABC" ) , ["A", "BC"] ) self.assertEqual(trie.split("BCA" ) , ["BC", "A"] ) def A ( self : List[Any] ): """simple docstring""" __snake_case = Trie() trie.add("TOKEN]" ) trie.add("[SPECIAL_TOKEN]" ) self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]" ) , ["This is something ", "[SPECIAL_TOKEN]"] ) def A ( self : str ): """simple docstring""" __snake_case = Trie() trie.add("A" ) trie.add("P" ) trie.add("[SPECIAL_TOKEN]" ) self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]" ) , ["This is something ", "[SPECIAL_TOKEN]"] ) def A ( self : Optional[int] ): """simple docstring""" __snake_case = Trie() trie.add("AB" ) trie.add("B" ) trie.add("C" ) self.assertEqual(trie.split("ABC" ) , ["AB", "C"] ) def A ( self : Tuple ): """simple docstring""" __snake_case = Trie() trie.add("ABC" ) trie.add("B" ) trie.add("CD" ) self.assertEqual(trie.split("ABCD" ) , ["ABC", "D"] ) def A ( self : Any ): """simple docstring""" __snake_case = Trie() __snake_case = trie.cut_text("ABC" , [0, 0, 2, 1, 2, 3] ) self.assertEqual(a_ , ["AB", "C"] )
69
"""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
0
import numpy as np from transformers import Pipeline def _SCREAMING_SNAKE_CASE ( lowercase : List[Any] ): '''simple docstring''' lowerCamelCase_ = np.max(lowercase , axis=-1 , keepdims=lowercase ) lowerCamelCase_ = np.exp(outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=lowercase ) class A( UpperCamelCase ): '''simple docstring''' def a__ ( self : Tuple , **A_ : str ) -> str: """simple docstring""" lowerCamelCase_ = {} if "second_text" in kwargs: lowerCamelCase_ = kwargs['second_text'] return preprocess_kwargs, {}, {} def a__ ( self : Union[str, Any] , A_ : List[str] , A_ : int=None ) -> str: """simple docstring""" return self.tokenizer(A_ , text_pair=A_ , return_tensors=self.framework ) def a__ ( self : List[str] , A_ : int ) -> Optional[Any]: """simple docstring""" return self.model(**A_ ) def a__ ( self : Optional[Any] , A_ : Tuple ) -> Optional[Any]: """simple docstring""" lowerCamelCase_ = model_outputs.logits[0].numpy() lowerCamelCase_ = softmax(A_ ) lowerCamelCase_ = np.argmax(A_ ) lowerCamelCase_ = self.model.config.idalabel[best_class] lowerCamelCase_ = probabilities[best_class].item() lowerCamelCase_ = logits.tolist() return {"label": label, "score": score, "logits": logits}
70
"""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
0
'''simple docstring''' import random from .binary_exp_mod import bin_exp_mod def a__ ( _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[int]=10_00 ) -> List[str]: """simple docstring""" if n < 2: return False if n % 2 == 0: return n == 2 # this means n is odd UpperCAmelCase_ : Union[str, Any] = n - 1 UpperCAmelCase_ : Optional[Any] = 0 while d % 2 == 0: d /= 2 exp += 1 # n - 1=d*(2**exp) UpperCAmelCase_ : Dict = 0 while count < prec: UpperCAmelCase_ : Any = random.randint(2 , n - 1 ) UpperCAmelCase_ : int = bin_exp_mod(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if b != 1: UpperCAmelCase_ : Any = True for _ in range(_SCREAMING_SNAKE_CASE ): if b == n - 1: UpperCAmelCase_ : Union[str, Any] = False break UpperCAmelCase_ : List[Any] = b * b b %= n if flag: return False count += 1 return True if __name__ == "__main__": _lowerCamelCase = abs(int(input("""Enter bound : """).strip())) print("""Here's the list of primes:""") print(""", """.join(str(i) for i in range(n + 1) if is_prime_big(i)))
71
"""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
0
'''simple docstring''' from numpy import exp, pi, sqrt def UpperCamelCase ( lowercase_ : Union[str, Any] , lowercase_ : float = 0.0 , lowercase_ : float = 1.0 ) -> int: '''simple docstring''' return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 * sigma**2) ) if __name__ == "__main__": import doctest doctest.testmod()
72
"""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
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, is_vision_available, ) a_ : Optional[int] = {'processing_layoutxlm': ['LayoutXLMProcessor']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Dict = ['LayoutXLMTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : int = ['LayoutXLMTokenizerFast'] if TYPE_CHECKING: from .processing_layoutxlm import LayoutXLMProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm import LayoutXLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm_fast import LayoutXLMTokenizerFast else: import sys a_ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
73
"""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
0
def a__ ( snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = [] if len(snake_case ) == 1: return [nums.copy()] for _ in range(len(snake_case ) ): __SCREAMING_SNAKE_CASE : Optional[int] = nums.pop(0 ) __SCREAMING_SNAKE_CASE : int = permute(snake_case ) for perm in permutations: perm.append(snake_case ) result.extend(snake_case ) nums.append(snake_case ) return result def a__ ( snake_case ): """simple docstring""" def backtrack(snake_case ): if start == len(snake_case ) - 1: output.append(nums[:] ) else: for i in range(snake_case , len(snake_case ) ): __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Dict = nums[i], nums[start] backtrack(start + 1 ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Union[str, Any] = nums[i], nums[start] # backtrack __SCREAMING_SNAKE_CASE : Optional[Any] = [] backtrack(0 ) return output if __name__ == "__main__": import doctest # use res to print the data in permute2 function lowercase_ = permutea([1, 2, 3]) print(res) doctest.testmod()
74
"""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
0
'''simple docstring''' from __future__ import annotations from collections import namedtuple def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> tuple: UpperCAmelCase__ : Optional[Any] = namedtuple('''result''' , '''name value''' ) if (voltage, current, power).count(0 ) != 1: raise ValueError('''Only one argument must be 0''' ) elif power < 0: raise ValueError( '''Power cannot be negative in any electrical/electronics system''' ) elif voltage == 0: return result('''voltage''' , power / current ) elif current == 0: return result('''current''' , power / voltage ) elif power == 0: return result('''power''' , float(round(abs(voltage * current ) , 2 ) ) ) else: raise ValueError('''Exactly one argument must be 0''' ) if __name__ == "__main__": import doctest doctest.testmod()
75
"""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
0
"""simple docstring""" import os import sys a_ = os.path.join(os.path.dirname(__file__), 'src') sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) a_ = [ 'torch', 'numpy', 'tokenizers', 'filelock', 'requests', 'tqdm', 'regex', 'sentencepiece', 'sacremoses', 'importlib_metadata', 'huggingface_hub', ] @add_start_docstrings(AutoConfig.__doc__ ) def __UpperCAmelCase ( *__UpperCamelCase , **__UpperCamelCase ): return AutoConfig.from_pretrained(*__UpperCamelCase , **__UpperCamelCase ) @add_start_docstrings(AutoTokenizer.__doc__ ) def __UpperCAmelCase ( *__UpperCamelCase , **__UpperCamelCase ): return AutoTokenizer.from_pretrained(*__UpperCamelCase , **__UpperCamelCase ) @add_start_docstrings(AutoModel.__doc__ ) def __UpperCAmelCase ( *__UpperCamelCase , **__UpperCamelCase ): return AutoModel.from_pretrained(*__UpperCamelCase , **__UpperCamelCase ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def __UpperCAmelCase ( *__UpperCamelCase , **__UpperCamelCase ): return AutoModelForCausalLM.from_pretrained(*__UpperCamelCase , **__UpperCamelCase ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def __UpperCAmelCase ( *__UpperCamelCase , **__UpperCamelCase ): return AutoModelForMaskedLM.from_pretrained(*__UpperCamelCase , **__UpperCamelCase ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def __UpperCAmelCase ( *__UpperCamelCase , **__UpperCamelCase ): return AutoModelForSequenceClassification.from_pretrained(*__UpperCamelCase , **__UpperCamelCase ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def __UpperCAmelCase ( *__UpperCamelCase , **__UpperCamelCase ): return AutoModelForQuestionAnswering.from_pretrained(*__UpperCamelCase , **__UpperCamelCase )
76
"""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
0
"""simple docstring""" from __future__ import annotations A = list[list[int]] # assigning initial values to the grid A = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution A = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def _UpperCamelCase ( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> bool: """simple docstring""" for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def _UpperCamelCase ( UpperCamelCase ) -> tuple[int, int] | None: """simple docstring""" for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def _UpperCamelCase ( UpperCamelCase ) -> Matrix | None: """simple docstring""" if location := find_empty_location(UpperCamelCase ): __UpperCAmelCase , __UpperCAmelCase : Dict = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 10 ): if is_safe(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ): __UpperCAmelCase : Dict = digit if sudoku(UpperCamelCase ) is not None: return grid __UpperCAmelCase : Optional[Any] = 0 return None def _UpperCamelCase ( UpperCamelCase ) -> None: """simple docstring""" for row in grid: for cell in row: print(UpperCamelCase , end=" " ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print("""\nExample grid:\n""" + """=""" * 20) print_solution(example_grid) print("""\nExample grid solution:""") A = sudoku(example_grid) if solution is not None: print_solution(solution) else: print("""Cannot find a solution.""")
77
"""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
0
'''simple docstring''' import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() SCREAMING_SNAKE_CASE_: Any =logging.get_logger(__name__) SCREAMING_SNAKE_CASE_: 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', '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', 'mask_emb': 'masked_spec_embed', } SCREAMING_SNAKE_CASE_: Union[str, Any] =[ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', ] def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : Tuple , snake_case_ : Any , snake_case_ : Tuple , snake_case_ : Tuple ) -> str: '''simple docstring''' for attribute in key.split("." ): UpperCAmelCase_ = getattr(snake_case_ , snake_case_ ) if weight_type is not None: UpperCAmelCase_ = getattr(snake_case_ , snake_case_ ).shape else: UpperCAmelCase_ = hf_pointer.shape assert hf_shape == value.shape, ( f"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": UpperCAmelCase_ = value elif weight_type == "weight_g": UpperCAmelCase_ = value elif weight_type == "weight_v": UpperCAmelCase_ = value elif weight_type == "bias": UpperCAmelCase_ = value else: UpperCAmelCase_ = value logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : Any ) -> List[Any]: '''simple docstring''' UpperCAmelCase_ = [] UpperCAmelCase_ = fairseq_model.state_dict() UpperCAmelCase_ = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight UpperCAmelCase_ = None for name, value in fairseq_dict.items(): UpperCAmelCase_ = False if "conv_layers" in name: load_conv_layer( snake_case_ , snake_case_ , snake_case_ , snake_case_ , hf_model.config.feat_extract_norm == "group" , ) UpperCAmelCase_ = True elif name.split("." )[0] == "proj": UpperCAmelCase_ = fairseq_model.proj UpperCAmelCase_ = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("w2v_model." )[-1] == name.split("." )[0]: UpperCAmelCase_ = True if "*" in mapped_key: UpperCAmelCase_ = name.split(snake_case_ )[0].split("." )[-2] UpperCAmelCase_ = mapped_key.replace("*" , snake_case_ ) if "weight_g" in name: UpperCAmelCase_ = "weight_g" elif "weight_v" in name: UpperCAmelCase_ = "weight_v" elif "bias" in name: UpperCAmelCase_ = "bias" elif "weight" in name: UpperCAmelCase_ = "weight" else: UpperCAmelCase_ = None set_recursively(snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) continue if not is_used: unused_weights.append(snake_case_ ) logger.warning(f"""Unused weights: {unused_weights}""" ) return proj_weight def lowerCAmelCase_ ( snake_case_ : List[Any] , snake_case_ : Any , snake_case_ : List[str] , snake_case_ : str , snake_case_ : List[Any] ) -> Any: '''simple docstring''' UpperCAmelCase_ = full_name.split("conv_layers." )[-1] UpperCAmelCase_ = name.split("." ) UpperCAmelCase_ = int(items[0] ) UpperCAmelCase_ = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) UpperCAmelCase_ = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) UpperCAmelCase_ = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) UpperCAmelCase_ = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) UpperCAmelCase_ = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(snake_case_ ) def lowerCAmelCase_ ( snake_case_ : Optional[int] ) -> List[str]: '''simple docstring''' UpperCAmelCase_ , UpperCAmelCase_ = emb.weight.shape UpperCAmelCase_ = nn.Linear(snake_case_ , snake_case_ , bias=snake_case_ ) UpperCAmelCase_ = emb.weight.data return lin_layer def lowerCAmelCase_ ( snake_case_ : Any ) -> List[Any]: '''simple docstring''' with open(snake_case_ , "r" , encoding="utf-8" ) as f: UpperCAmelCase_ = f.readlines() UpperCAmelCase_ = [line.split(" " )[0] for line in lines] UpperCAmelCase_ = len(snake_case_ ) UpperCAmelCase_ = { "<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3, } vocab_dict.update(dict(zip(snake_case_ , range(4 , num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def lowerCAmelCase_ ( snake_case_ : List[Any] , snake_case_ : List[Any] , snake_case_ : int , snake_case_ : Optional[Any] , snake_case_ : int , snake_case_ : str , snake_case_ : Optional[int] , ) -> Dict: '''simple docstring''' UpperCAmelCase_ = WavaVecaConfig.from_pretrained(snake_case_ ) UpperCAmelCase_ = SpeechaTextaConfig.from_pretrained( snake_case_ , vocab_size=snake_case_ , decoder_layers=snake_case_ , do_stable_layer_norm=snake_case_ ) UpperCAmelCase_ = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=snake_case_ , return_attention_mask=snake_case_ , ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"data": "/".join(dict_path.split("/" )[:-1] )} ) UpperCAmelCase_ = model[0].eval() # set weights for wav2vec2 encoder UpperCAmelCase_ = WavaVecaModel(snake_case_ ) UpperCAmelCase_ = recursively_load_weights_wavaveca(model.encoder , snake_case_ ) UpperCAmelCase_ = SpeechaTextaForCausalLM(snake_case_ ) UpperCAmelCase_ , UpperCAmelCase_ = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=snake_case_ ) # set output linear layer unexpected_keys.remove("embed_out" ) UpperCAmelCase_ = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(f"""The following keys are missing when loading the decoder weights: {missing_keys}""" ) logger.warning(f"""The following keys are unexpected when loading the decoder weights: {unexpected_keys}""" ) UpperCAmelCase_ = SpeechEncoderDecoderModel(encoder=snake_case_ , decoder=snake_case_ ) UpperCAmelCase_ = False # add projection layer UpperCAmelCase_ = nn.Parameter(projection_layer.weight ) UpperCAmelCase_ = nn.Parameter(projection_layer.bias ) UpperCAmelCase_ = create_vocab_dict(snake_case_ ) with open(os.path.join(snake_case_ , "vocab.json" ) , "w" ) as fp: json.dump(snake_case_ , snake_case_ ) UpperCAmelCase_ = SpeechaTextaTokenizer(os.path.join(snake_case_ , "vocab.json" ) ) tokenizer.save_pretrained(snake_case_ ) UpperCAmelCase_ = hf_wavavec.config.to_dict() UpperCAmelCase_ = tokenizer.pad_token_id UpperCAmelCase_ = tokenizer.bos_token_id UpperCAmelCase_ = tokenizer.eos_token_id UpperCAmelCase_ = "speech_to_text_2" UpperCAmelCase_ = "wav2vec2" UpperCAmelCase_ = SpeechEncoderDecoderConfig.from_dict(snake_case_ ) hf_wavavec.save_pretrained(snake_case_ ) feature_extractor.save_pretrained(snake_case_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_: Optional[int] =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( '--encoder_config_path', default='facebook/wav2vec2-large-lv60', type=str, help='Path to hf encoder wav2vec2 checkpoint config', ) parser.add_argument( '--decoder_config_path', default='facebook/s2t-small-mustc-en-fr-st', type=str, help='Path to hf decoder s2t checkpoint config', ) parser.add_argument('--vocab_size', default=1_02_24, type=int, help='Vocab size of decoder') parser.add_argument('--num_decoder_layers', default=7, type=int, help='Number of decoder layers') SCREAMING_SNAKE_CASE_: Tuple =parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
78
"""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
0
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : str = { """microsoft/markuplm-base""": """https://huggingface.co/microsoft/markuplm-base/resolve/main/config.json""", """microsoft/markuplm-large""": """https://huggingface.co/microsoft/markuplm-large/resolve/main/config.json""", } class UpperCAmelCase_ ( __lowerCamelCase ): __lowerCamelCase = 'markuplm' def __init__( self , _lowerCAmelCase=30522 , _lowerCAmelCase=768 , _lowerCAmelCase=12 , _lowerCAmelCase=12 , _lowerCAmelCase=3072 , _lowerCAmelCase="gelu" , _lowerCAmelCase=0.1 , _lowerCAmelCase=0.1 , _lowerCAmelCase=512 , _lowerCAmelCase=2 , _lowerCAmelCase=0.0_2 , _lowerCAmelCase=1e-12 , _lowerCAmelCase=0 , _lowerCAmelCase=0 , _lowerCAmelCase=2 , _lowerCAmelCase=256 , _lowerCAmelCase=1024 , _lowerCAmelCase=216 , _lowerCAmelCase=1001 , _lowerCAmelCase=32 , _lowerCAmelCase=50 , _lowerCAmelCase="absolute" , _lowerCAmelCase=True , _lowerCAmelCase=None , **_lowerCAmelCase , ): super().__init__( pad_token_id=_lowerCAmelCase , bos_token_id=_lowerCAmelCase , eos_token_id=_lowerCAmelCase , **_lowerCAmelCase , ) UpperCAmelCase__ : Optional[int] = vocab_size UpperCAmelCase__ : Any = hidden_size UpperCAmelCase__ : Dict = num_hidden_layers UpperCAmelCase__ : List[str] = num_attention_heads UpperCAmelCase__ : int = hidden_act UpperCAmelCase__ : List[Any] = intermediate_size UpperCAmelCase__ : Dict = hidden_dropout_prob UpperCAmelCase__ : Optional[int] = attention_probs_dropout_prob UpperCAmelCase__ : Tuple = max_position_embeddings UpperCAmelCase__ : Dict = type_vocab_size UpperCAmelCase__ : Any = initializer_range UpperCAmelCase__ : Dict = layer_norm_eps UpperCAmelCase__ : Optional[Any] = position_embedding_type UpperCAmelCase__ : List[str] = use_cache UpperCAmelCase__ : Union[str, Any] = classifier_dropout # additional properties UpperCAmelCase__ : List[str] = max_depth UpperCAmelCase__ : int = max_xpath_tag_unit_embeddings UpperCAmelCase__ : Union[str, Any] = max_xpath_subs_unit_embeddings UpperCAmelCase__ : Union[str, Any] = tag_pad_id UpperCAmelCase__ : List[str] = subs_pad_id UpperCAmelCase__ : Optional[int] = xpath_unit_hidden_size
79
"""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
0